forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

project.rs21001 lines, 919.6 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::{KEY_SCALE_RANGE, TitleAnim, TitleKey};
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 with_cut_key,
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 four ramp shapes a clip's speed can be laid in: the speed card and the palette lay them
351/// across a clip's length, and the MCP `speed_ramp` takes them by name ([`SpeedRampShape::name`]).
352#[derive(Clone, Copy, PartialEq, Eq, Debug)]
353pub enum SpeedRampShape {
354 /// Real time easing up to double.
355 SpeedUp,
356 /// Double easing down to real time.
357 SlowDown,
358 /// Slow, then fast through the middle, then slow: the classic speed ramp.
359 FastMiddle,
360 /// Fast, then slow through the middle, then fast: the hero shot.
361 SlowMiddle,
362}
363
364impl SpeedRampShape {
365 /// Every shape, in the order the speed card shows them.
366 pub const ALL: [SpeedRampShape; 4] = [
367 SpeedRampShape::SpeedUp,
368 SpeedRampShape::SlowDown,
369 SpeedRampShape::FastMiddle,
370 SpeedRampShape::SlowMiddle,
371 ];
372
373 /// The shape's name as the MCP takes it: `speed_up`, `slow_down`, `fast_middle` or `slow_middle`.
374 pub fn name(self) -> &'static str {
375 match self {
376 SpeedRampShape::SpeedUp => "speed_up",
377 SpeedRampShape::SlowDown => "slow_down",
378 SpeedRampShape::FastMiddle => "fast_middle",
379 SpeedRampShape::SlowMiddle => "slow_middle",
380 }
381 }
382
383 /// The keys of the shape over a clip `frames` timeline frames long. `None` when the clip is
384 /// too short to hold the shape's keys one frame apart.
385 pub fn keys(self, frames: u32) -> Option<Vec<SpeedKey>> {
386 let key = |at: u32, permille: u16| SpeedKey { at, speed: Speed::from_permille(permille) };
387 match self {
388 SpeedRampShape::SpeedUp => (frames >= 1).then(|| vec![key(0, 1000), key(frames, 2000)]),
389 SpeedRampShape::SlowDown => (frames >= 1).then(|| vec![key(0, 2000), key(frames, 1000)]),
390 SpeedRampShape::FastMiddle => {
391 (frames >= 2).then(|| vec![key(0, 500), key(frames / 2, 2000), key(frames, 500)])
392 }
393 SpeedRampShape::SlowMiddle => {
394 (frames >= 2).then(|| vec![key(0, 2000), key(frames / 2, 500), key(frames, 2000)])
395 }
396 }
397 }
398}
399
400/// The source position a speed ramp has carried a clip through by its clip-relative
401/// timeline frame `t`: the integral of the piecewise-linear speed from frame 0 to
402/// `t`, in source frames (fractional). Each segment's integral is the trapezoid of
403/// its two ends, exact for a linear speed, so this is the closed form and needs no
404/// table. `keys` must be sorted by `at` with no two alike (see
405/// [`valid_speed_keys`]); empty keys are real time.
406///
407/// A 1x-to-2x ramp over 60 frames -- keys `(0, 1x), (60, 2x)` -- gives 90 at frame 60.
408pub fn ramp_source_at(keys: &[SpeedKey], t: f64) -> f64 {
409 let Some(first) = keys.first() else {
410 return t.max(0.0);
411 };
412 let t = t.max(0.0);
413 // Held before the first key at its speed.
414 let mut acc = t.min(f64::from(first.at)) * first.speed.as_f64();
415 for w in keys.windows(2) {
416 let (a, b) = (w[0], w[1]);
417 let (ta, tb) = (f64::from(a.at), f64::from(b.at));
418 if t <= ta {
419 return acc;
420 }
421 let (ra, rb) = (a.speed.as_f64(), b.speed.as_f64());
422 let d = t.min(tb) - ta;
423 // The speed at the end of the part walked: linear between the two keys.
424 let rate_there = ra + (rb - ra) * d / (tb - ta);
425 acc += d * (ra + rate_there) / 2.;
426 if t <= tb {
427 return acc;
428 }
429 }
430 // Held after the last key.
431 let last = keys[keys.len() - 1];
432 acc + (t - f64::from(last.at)).max(0.) * last.speed.as_f64()
433}
434
435/// The inverse of [`ramp_source_at`]: the clip-relative timeline frame (fractional) at
436/// which a ramp has carried the clip through `source` source frames. Exact to the
437/// float -- the integral is strictly increasing, so the bisection has one answer.
438/// Empty keys are real time.
439pub fn ramp_timeline_at(keys: &[SpeedKey], source: f64) -> f64 {
440 if keys.is_empty() || source <= 0.0 {
441 return source.max(0.0);
442 }
443 let (mut lo, mut hi) = (0., 4. * source + 1.);
444 for _ in 0..64 {
445 let mid = (lo + hi) / 2.;
446 if ramp_source_at(keys, mid) < source {
447 lo = mid;
448 } else {
449 hi = mid;
450 }
451 }
452 (lo + hi) / 2.
453}
454
455/// Timeline frames a ramped clip of `source` source frames occupies: the clip-relative
456/// frame at which [`ramp_source_at`] reaches `source`, rounded, and never zero. The
457/// ramp's own footprint, the way [`Speed::frames`] is the constant one's.
458///
459/// Solved by bisection: the integral is strictly increasing (every speed is at least
460/// [`Speed::MIN`]), so the answer is unique and the bisection is exact to the float.
461pub fn ramp_frames(keys: &[SpeedKey], source: u32) -> u32 {
462 let target = f64::from(source);
463 // Every speed is at least a quarter, so frame `4 * source` has covered `source`.
464 let (mut lo, mut hi) = (0., 4. * target + 1.);
465 for _ in 0..64 {
466 let mid = (lo + hi) / 2.;
467 if ramp_source_at(keys, mid) < target {
468 lo = mid;
469 } else {
470 hi = mid;
471 }
472 }
473 ((lo + hi) / 2.).round().max(1.) as u32
474}
475
476/// Whether `keys` is a ramp the engine will play: between one and
477/// [`MAX_SPEED_KEYS`] keys, strictly increasing in `at`. The speeds are in range by
478/// construction.
479pub fn valid_speed_keys(keys: &[SpeedKey]) -> bool {
480 (1..=MAX_SPEED_KEYS).contains(&keys.len()) && keys.windows(2).all(|w| w[0].at < w[1].at)
481}
482
483/// A clip's speed ramp as a [`Span`] carries it: the keys in a fixed array (so the
484/// span stays `Copy`) and the clip-relative frame the span starts at, which is what
485/// its own offsets are counted from.
486#[derive(Clone, Copy, PartialEq, Eq, Debug)]
487pub struct SpeedRamp {
488 keys: [SpeedKey; MAX_SPEED_KEYS],
489 len: u8,
490 base: u32,
491}
492
493impl SpeedRamp {
494 /// The ramp `keys` (valid, see [`valid_speed_keys`]) for a span starting `base`
495 /// clip-relative frames into the clip.
496 pub fn new(keys: &[SpeedKey], base: u32) -> Self {
497 let mut arr = [SpeedKey::default(); MAX_SPEED_KEYS];
498 arr[..keys.len()].copy_from_slice(keys);
499 Self {
500 keys: arr,
501 len: keys.len() as u8,
502 base,
503 }
504 }
505
506 fn keys(&self) -> &[SpeedKey] {
507 &self.keys[..usize::from(self.len)]
508 }
509
510 /// The same ramp with every speed multiplied by `by`: what a pitch shift asks of the
511 /// stretch that follows a ramp, which runs `1 / 2^(pitch/12)` times as fast.
512 pub fn scaled(self, by: f64) -> Self {
513 let mut keys = self.keys;
514 for k in &mut keys[..usize::from(self.len)] {
515 k.speed = Speed::from_permille((k.speed.as_f64() * by * 1000.0).round() as u16);
516 }
517 Self { keys, ..self }
518 }
519
520 /// The same ramp for a span that starts `by` timeline frames later on it, which is
521 /// what a cut at the span's head does to where its offsets are counted from.
522 pub fn advanced(self, by: u32) -> Self {
523 Self {
524 base: self.base + by,
525 ..self
526 }
527 }
528
529 /// Source frames from the span's first frame to its `offset`th, as the difference
530 /// of two floored source positions -- so `from + source_offset(o)` is the same
531 /// frame [`source_pos`] puts `base + o` on, with no rounding drift between them.
532 pub fn source_offset(&self, offset: u32) -> u32 {
533 let at = |o: u32| ramp_source_at(self.keys(), f64::from(self.base) + f64::from(o)).floor();
534 (at(offset) - at(0)).max(0.) as u32
535 }
536
537 /// Source frames (fractional) from the floored source position of the span's first
538 /// frame to the position `offset` timeline frames (fractional) into the span: what
539 /// [`source_offset`](SpeedRamp::source_offset) is without the floors, from the very
540 /// frame `from` names. The audio follows the ramp through this.
541 pub fn source_frames(&self, offset: f64) -> f64 {
542 let base = f64::from(self.base);
543 ramp_source_at(self.keys(), base + offset.max(0.0)) - ramp_source_at(self.keys(), base).floor()
544 }
545
546 /// The inverse of [`source_frames`](SpeedRamp::source_frames): the timeline frame
547 /// (fractional) into the span at which the ramp has read `source` source frames
548 /// of it.
549 pub fn timeline_frames(&self, source: f64) -> f64 {
550 let base = f64::from(self.base);
551 let target = source.max(0.0) + ramp_source_at(self.keys(), base).floor();
552 (ramp_timeline_at(self.keys(), target) - base).max(0.0)
553 }
554
555 /// The inverse of [`source_offset`](SpeedRamp::source_offset): the first offset
556 /// whose frame is `source` or past it, which is [`Speed::timeline_at`] for a ramp.
557 pub fn timeline_at(&self, source: u32) -> u32 {
558 let (mut lo, mut hi) = (0u32, source.saturating_mul(4).saturating_add(8));
559 while lo < hi {
560 let mid = lo + (hi - lo) / 2;
561 if self.source_offset(mid) >= source {
562 hi = mid;
563 } else {
564 lo = mid + 1;
565 }
566 }
567 lo
568 }
569}
570
571impl Default for Speed {
572 fn default() -> Self {
573 Self::NORMAL
574 }
575}
576
577impl std::fmt::Display for Speed {
578 /// `2.00x` -- what a card prints and what a clip box is marked with.
579 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
580 write!(f, "{:.2}x", self.as_f64())
581 }
582}
583
584/// What a file's own frame rate is against the timeline's, as an exact
585/// rational: how many frames of the *file* one frame of the timeline is worth.
586///
587/// Every frame number in this module counts **timeline** frames -- a clip's
588/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
589/// timeline is as many frames long as the seconds it lasts, and every edit
590/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
591/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
592/// opens a worker with it and [`crate::export`] pulls pictures through it. The
593/// file's own numbering exists nowhere else.
594///
595/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
596/// export encodes at a timeline frame has to be the frame playback is holding
597/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
598/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
599///
600/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
601/// stays `800/1001` however far the timeline runs, where a rate rounded to
602/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
603/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
604///
605/// [`PlaybackSession`]: crate::PlaybackSession
606#[derive(Clone, Copy, PartialEq, Eq, Debug)]
607pub struct Rate {
608 /// Frames of the file...
609 source: u32,
610 /// ...per this many frames of the timeline it plays on. Never zero.
611 timeline: u32,
612}
613
614impl Rate {
615 /// A file shot at the timeline's own rate: every conversion below is the
616 /// identity, which is the path a single-rate project is on.
617 pub const REAL_TIME: Self = Self {
618 source: 1,
619 timeline: 1,
620 };
621
622 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
623 /// exactly.
624 ///
625 /// Both rates come out of a container as a division, so neither is ever the
626 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
627 /// already knows how to name one exactly -- it is the same pair the muxer
628 /// counts an export's frames in -- and this is that pair divided by that
629 /// pair, reduced. A rate no timescale can name is an `Err` in that
630 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
631 /// where a file carrying one is refused by name, beside the codec.
632 ///
633 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
634 /// timeline that had ever opened in this editor before mixed rates.
635 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
636 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
637 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
638 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
639 let num = u64::from(src_scale) * u64::from(tl_ticks);
640 let den = u64::from(src_ticks) * u64::from(tl_scale);
641 Ok(Self::reduced(num, den))
642 }
643
644 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
645 fn reduced(num: u64, den: u64) -> Self {
646 let g = gcd(num, den);
647 let (mut num, mut den) = (num / g, den / g);
648 // A ratio no pair of real frame rates produces, but the fields are `u32`
649 // so that every multiplication below fits a `u64` at any frame count.
650 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
651 (num, den) = (num.div_ceil(2), den.div_ceil(2));
652 }
653 Self {
654 source: num.max(1) as u32,
655 timeline: den.max(1) as u32,
656 }
657 }
658
659 /// The same file against a timeline that has itself been retimed: `self` is
660 /// its frames per frame of the old timeline and `k` is old frames per new
661 /// one, so this is its frames per frame of the *new* one -- exactly, without
662 /// going back through an `f64` fps that names neither rate
663 /// ([`crate::PlaybackSession::set_frame_rate`]).
664 pub fn then(self, k: Rate) -> Self {
665 Self::reduced(
666 u64::from(self.source) * u64::from(k.source),
667 u64::from(self.timeline) * u64::from(k.timeline),
668 )
669 }
670
671 pub fn is_real_time(self) -> bool {
672 self.source == self.timeline
673 }
674
675 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
676 /// is, given the timeline's, for a library row that names it.
677 pub fn as_f64(self) -> f64 {
678 f64::from(self.source) / f64::from(self.timeline)
679 }
680
681 /// Which frame of the file the `frame`th timeline-rate frame of it is:
682 /// floored, [`Speed::source_at`]'s half of the pair.
683 pub fn source_at(self, frame: u32) -> u32 {
684 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
685 .min(u64::from(u32::MAX)) as u32
686 }
687
688 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
689 /// timeline-rate frame that shows source frame `source_frame` -- which is
690 /// the stamp playback puts on a decoded picture, and, applied to a file's
691 /// frame *count*, how long that file is in timeline frames.
692 pub fn timeline_at(self, source_frame: u32) -> u32 {
693 (u64::from(source_frame) * u64::from(self.timeline))
694 .div_ceil(u64::from(self.source))
695 .min(u64::from(u32::MAX)) as u32
696 }
697
698 /// The same map rounded to the *nearest* timeline frame, halves up, instead
699 /// of up: what a retime ([`Project::retime`]) lands every boundary, length
700 /// and envelope on. Ceiling every one of them biased each round trip later
701 /// by up to a frame per boundary, so a dissolve and a voiceover clip grew;
702 /// rounding to nearest is unbiased, so a boundary is never more than half a
703 /// frame from where its seconds put it, and a round trip through a grid that
704 /// holds the frame exactly returns it exactly.
705 pub fn timeline_nearest(self, source_frame: u32) -> u32 {
706 let num = u64::from(source_frame) * u64::from(self.timeline) * 2 + u64::from(self.source);
707 (num / (2 * u64::from(self.source))).min(u64::from(u32::MAX)) as u32
708 }
709}
710
711/// The source frames a clip has left past its in-point, on a table of `frames`
712/// (its lane's length of the source): the wall an end edge is measured to
713/// ([`Project::clip_walls`]), as a count. Never less than one frame.
714fn source_left(clip: &Clip, frames: &[u32]) -> u32 {
715 frames
716 .get(clip.source)
717 .copied()
718 .unwrap_or(clip.out_frame)
719 .saturating_sub(clip.in_frame)
720 .max(1)
721}
722
723/// Timeline frames `n` source frames of `c` occupy: [`Speed::room`] at its constant
724/// rate, the ramp's footprint for a ramped clip. Zero for none.
725fn footprint(c: &Clip, n: u32) -> u32 {
726 match n {
727 0 => 0,
728 n if c.speed_keys.is_empty() => c.speed.frames(n),
729 n => ramp_frames(&c.speed_keys, n),
730 }
731}
732
733/// The most source an `edge` trim of `clip` may keep, on a table of `frames`: the
734/// side of the window the trim grows is the out-point at a forward clip's end and at
735/// a reversed clip's start (its head is the window's far end), and the in-point
736/// (which cannot go below the file's first frame) at a reversed clip's end.
737/// Unbounded where the edge's own wall already is the bound.
738fn keep_cap(clip: &Clip, edge: Edge, frames: &[u32]) -> u32 {
739 match (edge, clip.reversed) {
740 (Edge::End, false) | (Edge::Start, true) => source_left(clip, frames),
741 (Edge::Start, false) => u32::MAX,
742 (Edge::End, true) => clip.out_frame.max(1),
743 }
744}
745
746/// Writes the trim of `c`'s `edge` to timeline frame `to`, keeping `keep` source
747/// frames: the frames that stay play what they played, so the window's end that is
748/// *not* at the edge is the one held still.
749fn write_trim(c: &mut Clip, edge: Edge, to: u32, keep: u32, still: bool) {
750 match (edge, c.reversed && !still) {
751 // A still has no earlier frame to walk an in-point back to --
752 // every frame of it is the same picture -- so its head grows
753 // *forward*: the range it plays is however long the new room is,
754 // anchored at the source's frame 0. Bounded by `lo`, which is where
755 // the cap in `source_frames` is applied.
756 (Edge::Start, _) if still => {
757 c.in_frame = 0;
758 c.out_frame = keep;
759 c.start = to;
760 }
761 // Non-negative by `lo`, which is what keeps the in-point on the source.
762 (Edge::Start, false) => {
763 c.in_frame = c.out_frame - keep.min(c.out_frame);
764 c.start = to;
765 }
766 (Edge::Start, true) => {
767 c.out_frame = c.in_frame + keep;
768 c.start = to;
769 }
770 // Never wider than the room the edge was clamped to: see [`Speed::fit`].
771 (Edge::End, false) => c.out_frame = c.in_frame + keep,
772 (Edge::End, true) => c.in_frame = c.out_frame - keep.min(c.out_frame),
773 }
774}
775
776/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
777/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
778fn gcd(a: u64, b: u64) -> u64 {
779 match b {
780 0 => a.max(1),
781 b => gcd(b, a % b),
782 }
783}
784
785/// A half-open `[in_frame, out_frame)` range of frames of source
786/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
787/// Never empty.
788///
789/// Counted at the **timeline's** frame rate, not the file's: a source shot at
790/// another rate is converted at the decoder's door ([`Rate`]), so every edit
791/// here is frames of one clock.
792#[derive(Clone, PartialEq, Debug)]
793pub struct Clip {
794 /// Timeline frame the clip's first frame is shown at. Meaningless on a
795 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
796 /// with where the caller asked for.
797 pub start: u32,
798 pub in_frame: u32,
799 pub out_frame: u32,
800 /// Index into [`Project::sources`].
801 pub source: usize,
802 /// Group id: clips sharing one were split from the same take. `None` for a
803 /// clip that belongs to no group.
804 pub link: Option<u32>,
805 /// Index into the project's equalizer table
806 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
807 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
808 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
809 /// plain assignment. The table is append-only within a session, so an index
810 /// on a clipboard clip or inside an undo snapshot can never dangle.
811 pub eq: Option<u16>,
812 /// Index into the project's colour table
813 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
814 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
815 /// promises: `Copy`, append-only within a session, never dangling.
816 pub color: Option<u16>,
817 /// Index into the project's transform table
818 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
819 /// clip that plays at its fit policy's own placement. An index for
820 /// [`Clip::color`]'s reason and with the same promises.
821 pub transform: Option<u16>,
822 /// How this clip's picture meets a project canvas of another shape
823 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
824 /// two above: it is one byte with no parameters, so there is nothing for a
825 /// table to share, and a clip that is the project's own size never consults
826 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
827 /// where the aspect does not agree.
828 pub fit: FitPolicy,
829 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
830 /// eq and colour indexes: it is two bytes with nothing to share, and a table
831 /// would put a level of indirection between the mapping and the one number
832 /// every frame of it is divided by.
833 ///
834 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
835 /// the clip plays, so a trim and a split still address the file. What it
836 /// changes is how many *timeline* frames that range is spread over
837 /// ([`Clip::frames`]).
838 pub speed: Speed,
839 /// Timeline frames of ramp-up from silence at the clip's own start, inline
840 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
841 /// number with nothing to share, and every consumer (mixer, exporter) wants
842 /// it sitting right next to the frame range it shapes. Clamped to the
843 /// clip's own length by the setter -- never wider than the clip is long.
844 pub fade_in: u32,
845 /// Timeline frames of ramp-down to silence at the clip's own end. Same
846 /// promises as [`Clip::fade_in`].
847 pub fade_out: u32,
848 /// Timeline frames of cross-dissolve into the clip immediately after this
849 /// one on the same video lane, at this clip's own end -- `0` for a hard
850 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
851 /// reason, and clamped the same way by its setter
852 /// ([`Project::set_transition_out`]): never wider than this clip's own
853 /// length, nor than the successor it dissolves into. Meaningless -- and
854 /// left as whatever it was -- the moment the next clip stops abutting
855 /// this one; a reader that cares checks adjacency itself rather than
856 /// trusting this field alone, exactly as a stored fade is trusted only
857 /// because a clip's own length is checked beside it.
858 pub transition_out: u32,
859 /// How [`Clip::transition_out`] is drawn: the picture's blend over the
860 /// overlap ([`crate::transitions`]). The sound is a crossfade whatever it
861 /// is. Older project files have no field and mean a dissolve.
862 pub transition_kind: crate::transitions::TransitionKind,
863 /// Non-zero: this clip is a waveform of its source's sound, painted
864 /// onto a video lane. Bit 0 is the flag; bits 1-2 style; bit 3 fast.
865 /// Zero is an ordinary picture. Older project files have no field and
866 /// mean zero.
867 pub visualizer: u8,
868 /// Packed look: hue 0-255, sat 0-255, strands 0-255, glow 0-255 in the
869 /// low four bytes as they have been since v22, then the strand colour's
870 /// own bytes above them -- its hue at 32 and sat at 40
871 /// ([`crate::decode::viz_strand_hue_ui`]) -- with the top bit as
872 /// [`crate::decode::viz_strand_set`]. All-zero is the default (timeline
873 /// azure, full sat, 8 strands, glow 2, no strand colour of its own).
874 /// Older files have no field and mean zero; a v22 file's 32-bit value
875 /// is the low half of this one, byte for byte.
876 pub viz_paint: u64,
877 /// The clip's own volume in dB, on top of its lane's
878 /// ([`Project::lane_gain_db`]). `0.0` is unity and the default; the setter
879 /// keeps it within [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. It is
880 /// applied as a linear multiplier inside the clip's own envelope
881 /// ([`Fade`]), so playback and export hear the same number. Audio clips
882 /// only. Not `Eq`: a float, and nothing compared clips by it.
883 pub gain_db: f32,
884 /// The clip's volume envelope: points of dB keyed to SOURCE frames, sorted
885 /// by [`GainKey::at`] with no two alike. Empty is 0 dB. Source-keyed, so a
886 /// move, a trim or a ripple keeps each point on the same audio, and a split
887 /// keeps the whole curve on both halves. It rides on top of
888 /// [`Clip::gain_db`] and the fades, inside the same [`Fade`]. Audio clips
889 /// only ([`Project::set_gain_keys`]). Capped at [`MAX_GAIN_KEYS`].
890 pub gain_keys: Vec<GainKey>,
891 /// Where the clip sits between the speakers, in whole percent: `-100` (left) to
892 /// `100` (right), `0` the default and the middle. One byte, because it sits in the
893 /// padding where an `f32` would have grown the clip. A balance on a stereo mix: the far
894 /// side is turned down, the near one left alone. Rides in the clip's [`Fade`] like its
895 /// gain. Audio clips only ([`Project::set_clip_pan`]); [`Clip::pan_value`] reads it as
896 /// `-1.0..=1.0`.
897 pub pan: i8,
898 /// The clip's pitch in whole semitones, `-12` (an octave down) to `12` (up), `0` the
899 /// default and the original sound. Changes the pitch and keeps the speed: the
900 /// stretch and the resample that make it are built by [`Project::lane_speeds_from`],
901 /// so playback and export hear the same thing. Audio clips only
902 /// ([`Project::set_clip_pitch`]). One byte, in the same padding as [`Clip::pan`].
903 pub pitch: i8,
904 /// The clip's placement animation: whole [`TransformParams`] at SOURCE
905 /// frames, sorted by [`TransformKey::at`] with no two alike. Empty is the
906 /// single [`Clip::transform`] for the whole clip. Video lanes only
907 /// ([`Project::set_transform_keys`]). Kept on the footage the way the
908 /// volume points are: a trim leaves them, and a split divides them with a
909 /// key at the cut ([`split_transform_keys`]).
910 pub transform_keys: Vec<TransformKey>,
911 /// The clip's opacity animation: `0..=1` at SOURCE frames, sorted by
912 /// [`OpacityKey::at`] with no two alike. With keys present they give the
913 /// opacity (replacing [`TransformParams::opacity`], whose own keys are then
914 /// not read for it); the fades still multiply on top. Empty is the
915 /// transform's constant opacity. Video lanes only
916 /// ([`Project::set_opacity_keys`]); kept on the footage as the placement
917 /// keys are.
918 pub opacity_keys: Vec<OpacityKey>,
919 /// The clip's colour animation: the whole grade at SOURCE frames, sorted by
920 /// [`ColorKey::at`] with no two alike. With keys present they give the
921 /// grade (replacing the clip's constant one). Video lanes only
922 /// ([`Project::set_color_keys`]); kept on the footage as the placement keys are.
923 pub color_keys: Vec<ColorKey>,
924 /// The clip's speed ramp: keys of speed at CLIP-relative timeline frames, sorted
925 /// by [`SpeedKey::at`] with no two alike, at most [`MAX_SPEED_KEYS`]. Empty is
926 /// the constant [`Clip::speed`], which every path not named otherwise keeps. With
927 /// keys present the ramp replaces the constant: [`Clip::frames`] is the ramp's
928 /// footprint and [`source_pos`] the ramp's mapping, and [`Clip::speed`] is left
929 /// as it was, to come back when the ramp is cleared.
930 pub speed_keys: Vec<SpeedKey>,
931 /// Whether the clip plays its source window backwards: the timeline's first
932 /// frame shows the window's last source frame, the picture and the sound both.
933 /// Composes with [`Clip::speed`] and [`Clip::speed_keys`] (the rate is how fast
934 /// the window is walked, from its far end), leaves the window ([`Clip::in_frame`]
935 /// and [`Clip::out_frame`]) and the footprint ([`Clip::frames`]) as they were, and
936 /// keeps every key where it plays on the timeline ([`Project::set_reverse`]
937 /// mirrors the source-keyed ones when it flips). Fades are timeline-relative and
938 /// need nothing.
939 pub reversed: bool,
940 /// The clip's effects stack ([`crate::effects`]), drawn in order on its
941 /// picture before it is laid over the lanes beneath. Empty, or every effect
942 /// switched off, is no effect. Video lanes only ([`Project::set_effects`]); a
943 /// split gives both halves the whole stack.
944 pub effects: Vec<crate::effects::Effect>,
945 /// The clip's stabilisation, `None` for off ([`crate::stabilise`]): the
946 /// camera shake measured from its footage is taken out of each picture
947 /// before its placement ([`Clip::transform`], [`Clip::transform_keys`]) is
948 /// applied, read by the file frame shown, so it survives trims, speed,
949 /// ramps and reverse.
950 pub stabilise: Option<crate::stabilise::Stabilise>,
951 /// Which angle of a multicam clip this clip shows ([`Angle`]); the default, angle 1, for
952 /// every clip that is not a multicam clip.
953 pub angle: Angle,
954 /// How an interlaced source is made progressive ([`Deinterlace`]). Only
955 /// matters for a clip whose source is interlaced; kept on the clip so a
956 /// split, a copy, a nest and an undo carry it like any other setting.
957 pub deinterlace: Deinterlace,
958 /// The clip's colour label and whether it is switched off ([`ClipMark`]).
959 pub mark: ClipMark,
960}
961
962/// The number of colour labels a clip can carry ([`LABELS`]); label 0 is none.
963pub const LABEL_COUNT: u8 = 8;
964
965/// The fixed palette of clip labels, as Premiere names them: a clip with label `n` (1-based) is
966/// tinted `LABELS[n - 1]`. Label 0 is no label.
967pub const LABELS: [(&str, [u8; 3]); LABEL_COUNT as usize] = [
968 ("Violet", [0x9a, 0x6a, 0xd0]),
969 ("Iris", [0x5a, 0x6c, 0xd8]),
970 ("Caribbean", [0x2a, 0xa5, 0x9a]),
971 ("Lavender", [0xc0, 0x8a, 0xc4]),
972 ("Cerulean", [0x3a, 0x9a, 0xd6]),
973 ("Forest", [0x3e, 0x8a, 0x4a]),
974 ("Rose", [0xd8, 0x5a, 0x8a]),
975 ("Mango", [0xe0, 0x93, 0x2c]),
976];
977
978/// The name of label `n` (1-based), `None` for no label or one past the palette.
979pub fn label_name(n: u8) -> Option<&'static str> {
980 LABELS.get(usize::from(n).checked_sub(1)?).map(|l| l.0)
981}
982
983/// The label number a name (any case) or a number spells; `Some(0)` for `none`.
984pub fn label_by_name(name: &str) -> Option<u8> {
985 let name = name.trim();
986 if name.eq_ignore_ascii_case("none") || name == "0" {
987 return Some(0);
988 }
989 if let Ok(n) = name.parse::<u8>() {
990 return (n <= LABEL_COUNT).then_some(n);
991 }
992 LABELS.iter().position(|l| l.0.eq_ignore_ascii_case(name)).map(|i| i as u8 + 1)
993}
994
995/// What a clip carries that no render reads but the person editing does -- its colour label --
996/// and the switch that takes it out of the render ([`Clip::mark`]).
997#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
998pub struct ClipMark {
999 /// 0 for none, else 1..=[`LABEL_COUNT`] ([`LABELS`]).
1000 pub label: u8,
1001 /// Switched off: the clip stays on the timeline but is skipped by playback, export and the
1002 /// mix, as if its stretch were a gap.
1003 pub off: bool,
1004}
1005
1006impl ClipMark {
1007 /// Whether this is the default (nothing to write to a file).
1008 pub fn is_default(self) -> bool {
1009 self == ClipMark::default()
1010 }
1011}
1012
1013/// The angle a multicam clip ([`Project::make_multicam`]) shows: `video` picks the picture
1014/// and, unless `audio` is set, the sound too (audio follows video). Angles count from 0.
1015#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1016pub struct Angle {
1017 pub video: u8,
1018 /// The angle the sound is taken from when it does not follow the picture.
1019 pub audio: Option<u8>,
1020}
1021
1022impl Angle {
1023 /// The angle `kind` plays: the picture's own, or the sound's (which follows the picture
1024 /// unless pinned).
1025 pub fn of(self, kind: LaneKind) -> u8 {
1026 match kind {
1027 LaneKind::Audio => self.audio.unwrap_or(self.video),
1028 _ => self.video,
1029 }
1030 }
1031
1032 /// Whether this is the default (nothing to write to a file).
1033 pub fn is_default(self) -> bool {
1034 self == Angle::default()
1035 }
1036}
1037
1038
1039/// How a clip's interlaced source is turned into progressive pictures.
1040#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1041pub enum Deinterlace {
1042 /// One picture per frame (the two fields blended by the deinterlacer).
1043 #[default]
1044 Frame,
1045 /// One picture per field (double rate).
1046 Field,
1047 /// Leave the fields woven as they are.
1048 Off,
1049 /// Remove pulldown when the file shows a stable 3:2 cadence (or states soft
1050 /// pulldown), otherwise deinterlace as `Frame` ([`crate::ivtc`]).
1051 IvtcAuto,
1052 /// Remove pulldown: 23.976p film frames back out of 29.97i, whether or not the
1053 /// cadence is clear ([`crate::ivtc`]).
1054 Ivtc,
1055}
1056
1057impl Deinterlace {
1058 pub const ALL: [Deinterlace; 5] =
1059 [Deinterlace::Frame, Deinterlace::Field, Deinterlace::Off, Deinterlace::IvtcAuto, Deinterlace::Ivtc];
1060
1061 /// The word a file and the MCP use: `frame`, `field`, `off`.
1062 pub fn name(self) -> &'static str {
1063 match self {
1064 Deinterlace::Frame => "frame",
1065 Deinterlace::Field => "field",
1066 Deinterlace::Off => "off",
1067 Deinterlace::IvtcAuto => "ivtc-auto",
1068 Deinterlace::Ivtc => "ivtc",
1069 }
1070 }
1071
1072 pub fn from_name(name: &str) -> Option<Self> {
1073 Self::ALL.into_iter().find(|d| d.name() == name)
1074 }
1075}
1076
1077/// The quietest a clip's own gain can be set, in dB ([`Project::set_clip_gain`]).
1078pub const MIN_CLIP_GAIN_DB: f32 = -60.0;
1079/// The loudest a clip's own gain can be set, in dB ([`Project::set_clip_gain`]).
1080pub const MAX_CLIP_GAIN_DB: f32 = 24.0;
1081
1082/// The widest a clip's pitch shift may be, in semitones either way ([`Clip::pitch`]).
1083pub const MAX_CLIP_PITCH: i8 = 12;
1084/// The lowest a clip's pitch shift may be ([`Clip::pitch`]).
1085pub const MIN_CLIP_PITCH: i8 = -12;
1086/// The most points a clip's gain envelope may hold ([`Clip::gain_keys`]).
1087pub const MAX_GAIN_KEYS: usize = 256;
1088
1089/// One point of a clip's volume envelope ([`Clip::gain_keys`]): `db` at the
1090/// source frame `at`, which is the clip's in/out unit -- media time, counted at
1091/// the timeline's fps. Between points the dB is linear; before the first and
1092/// after the last it holds.
1093#[derive(Clone, Copy, PartialEq, Debug)]
1094pub struct GainKey {
1095 /// Source frame of the point.
1096 pub at: u32,
1097 /// Gain there, in dB, within [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`].
1098 pub db: f32,
1099 /// The easing of the segment that leaves this point ([`KeyEase::Linear`]
1100 /// unless set).
1101 pub ease: KeyEase,
1102}
1103
1104/// Which animation a keyframe button or action is about: the placement
1105/// ([`Clip::transform_keys`]), the opacity ([`Clip::opacity_keys`]) or the grade
1106/// ([`Clip::color_keys`]).
1107#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1108pub enum KeyKind {
1109 Placement,
1110 Opacity,
1111 Color,
1112}
1113
1114impl GainKey {
1115 /// A linear point: `db` at source frame `at`.
1116 pub fn new(at: u32, db: f32) -> Self {
1117 Self { at, db, ease: KeyEase::Linear }
1118 }
1119}
1120
1121/// The envelope's dB at source position `src` (fractional, in source frames)
1122/// over `points`, which are `(position, dB)` pairs sorted by position with no
1123/// two alike. Eased in dB between neighbours by the earlier point's ease
1124/// (linear by default), held flat outside the first and last point, and `0.0` for no points at all. The one interpolation both
1125/// [`Clip::gain_keys`] and the playback [`Fade`] evaluate.
1126fn lerp_db<T>(points: &[T], at: impl Fn(&T) -> (f64, f32, KeyEase), src: f64) -> f32 {
1127 let (Some(first), Some(last)) = (points.first(), points.last()) else {
1128 return 0.0;
1129 };
1130 let (x0, db0, _) = at(first);
1131 if src <= x0 {
1132 return db0;
1133 }
1134 let (xn, dbn, _) = at(last);
1135 if src >= xn {
1136 return dbn;
1137 }
1138 // The first point strictly after `src`: its predecessor is the left end
1139 // of the segment `src` is in, and both exist by the two checks above.
1140 let i = points.partition_point(|p| at(p).0 <= src);
1141 let (xa, dba, ease) = at(&points[i - 1]);
1142 let (xb, dbb, _) = at(&points[i]);
1143 let t = ease_shape(ease, ((src - xa) / (xb - xa)) as f32);
1144 dba + (dbb - dba) * t
1145}
1146
1147/// The placement `clip` shows at timeline `timeline_frame`, given its base
1148/// `base` ([`Clip::transform`] resolved): its [`Clip::transform_keys`] at the
1149/// source frame that frame plays, the same way [`Project::gain_db_at`] reads
1150/// the volume envelope, or `base` with no keys. Timeline frames before the
1151/// clip read as its first frame.
1152pub fn clip_transform_at(clip: &Clip, base: TransformParams, timeline_frame: u32) -> TransformParams {
1153 if clip.transform_keys.is_empty() {
1154 return base;
1155 }
1156 keyed_transform(&base, &clip.transform_keys, key_sample_pos(clip, timeline_frame))
1157}
1158
1159/// The opacity `clip` shows at timeline `timeline_frame`, given the opacity
1160/// `base` its transform gives there: its [`Clip::opacity_keys`] when it has
1161/// any, otherwise `base`. The fades are not in it; they multiply on top.
1162pub fn clip_opacity_at(clip: &Clip, base: f32, timeline_frame: u32) -> f32 {
1163 if clip.opacity_keys.is_empty() {
1164 return base;
1165 }
1166 evaluate_opacity(base, &clip.opacity_keys, key_sample_pos(clip, timeline_frame))
1167}
1168
1169/// The grade `clip` shows at timeline `timeline_frame`, given its constant
1170/// grade `base` ([`Project::color_of`] resolved, identity for none): its
1171/// [`Clip::color_keys`] interpolated at the source frame that frame plays, or
1172/// `base` with no keys.
1173pub fn clip_color_at(clip: &Clip, base: ColorParams, timeline_frame: u32) -> ColorParams {
1174 if clip.color_keys.is_empty() {
1175 return base;
1176 }
1177 evaluate_color(base, &clip.color_keys, key_sample_pos(clip, timeline_frame))
1178}
1179
1180/// Whether `clip` has any animation that changes the picture per frame
1181/// (placement, opacity or colour keys): the clips a layered path composes.
1182pub fn clip_animated(clip: &Clip) -> bool {
1183 !(clip.transform_keys.is_empty() && clip.opacity_keys.is_empty() && clip.color_keys.is_empty())
1184 || crate::effects::active(&clip.effects)
1185 || clip.stabilise.is_some()
1186}
1187
1188/// `c`'s placement keys after a trim that moved its `edge` from the state in
1189/// `old` (see [`keys_within`]). A still's head keeps the keys on the timeline
1190/// ([`keys_after_still_head`]); everything else keeps them on their footage.
1191fn rekey_trimmed(c: &mut Clip, old: &Clip, edge: Edge, still: bool) {
1192 fn rekey<K: Keyed>(old_keys: &[K], oc: &Clip, c: &Clip, edge: Edge, still: bool) -> Vec<K> {
1193 match edge {
1194 Edge::Start if still => keys_after_still_head(
1195 old_keys,
1196 oc.start,
1197 oc.in_frame,
1198 c.start,
1199 c.out_frame,
1200 oc.speed.as_f64(),
1201 ),
1202 _ => keys_within(old_keys, c.in_frame, c.out_frame),
1203 }
1204 }
1205 if !old.transform_keys.is_empty() {
1206 c.transform_keys = rekey(&old.transform_keys, old, c, edge, still);
1207 }
1208 if !old.opacity_keys.is_empty() {
1209 c.opacity_keys = rekey(&old.opacity_keys, old, c, edge, still);
1210 }
1211 if !old.color_keys.is_empty() {
1212 c.color_keys = rekey(&old.color_keys, old, c, edge, still);
1213 }
1214 // An effect's keys follow its stack position: the same effect, rekeyed the same way.
1215 let masks: Vec<Option<Vec<crate::effects::EffectKey>>> = old
1216 .effects
1217 .iter()
1218 .map(|e| (!e.keys.is_empty()).then(|| rekey(&e.keys, old, c, edge, still)))
1219 .collect();
1220 for (e, keys) in c.effects.iter_mut().zip(masks) {
1221 if let Some(keys) = keys {
1222 e.keys = keys;
1223 }
1224 }
1225}
1226
1227/// The split of a clip's placement animation at source frame `cut`: the left
1228/// half keeps the keys before the cut and the right half the keys after it,
1229/// and both get a key at `cut` holding the placement the whole animation gives
1230/// there, so each half still moves exactly as the clip did over its own frames.
1231/// A cut inside an eased segment splits its ease between the two halves
1232/// ([`with_cut_key`]), so the motion keeps its exact shape. Empty in, empty out.
1233pub fn split_transform_keys<K: Keyed>(keys: &[K], cut: u32) -> (Vec<K>, Vec<K>) {
1234 let list = with_cut_key(keys, cut);
1235 let mut left: Vec<K> = list.iter().copied().filter(|k| k.at() <= cut).collect();
1236 let mut right: Vec<K> = list.iter().copied().filter(|k| k.at() >= cut).collect();
1237 // A half that holds every key already holds the cut's value there, so the key the
1238 // cut added to it changes nothing; it is left out, which keeps a half of a full
1239 // animation inside the key cap the file and the setters hold it to.
1240 let added = !keys.iter().any(|k| k.at() == cut);
1241 if added && !keys.is_empty() {
1242 if keys.iter().all(|k| k.at() < cut) {
1243 left.pop();
1244 } else if keys.iter().all(|k| k.at() > cut) {
1245 right.remove(0);
1246 }
1247 }
1248 (left, right)
1249}
1250
1251/// The gain envelope's dB at source frame `src` over `keys`
1252/// ([`Clip::gain_keys`]): linear between points, held outside them, `0.0`
1253/// when there are none. Exact at a point, and the midpoint of two points is
1254/// the midpoint of their dB.
1255pub fn gain_keys_db_at(keys: &[GainKey], src: f64) -> f32 {
1256 lerp_db(keys, |k| (f64::from(k.at), k.db, k.ease), src)
1257}
1258
1259impl Clip {
1260 /// A plain clip of `source` reading `in_frame..out_frame`, at start 0, normal
1261 /// speed and no look: the shape a front-end hands
1262 /// [`Project::edit_from_source`] for one half of a take.
1263 pub fn source_range(source: usize, in_frame: u32, out_frame: u32) -> Clip {
1264 Clip {
1265 speed_keys: Vec::new(),
1266 reversed: false,
1267 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1268 angle: Default::default(),
1269 start: 0,
1270 in_frame,
1271 out_frame,
1272 source,
1273 link: None,
1274 eq: None,
1275 color: None,
1276 transform: None,
1277 transform_keys: Vec::new(),
1278 opacity_keys: Vec::new(),
1279 color_keys: Vec::new(),
1280 effects: Vec::new(),
1281 fit: FitPolicy::default(),
1282 speed: Speed::NORMAL,
1283 fade_in: 0,
1284 fade_out: 0,
1285 transition_out: 0,
1286 transition_kind: Default::default(),
1287 visualizer: 0,
1288 viz_paint: 0,
1289 gain_db: 0.0,
1290 gain_keys: Vec::new(),
1291 pan: 0,
1292 pitch: 0,
1293 }
1294 }
1295
1296 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
1297 /// reads out of its file -- not how long it is on the timeline, which is
1298 /// [`Clip::frames`] and differs the moment it is speeded.
1299 pub fn len(&self) -> u32 {
1300 self.out_frame - self.in_frame
1301 }
1302
1303 /// Always false: a clip reads at least one source frame.
1304 pub fn is_empty(&self) -> bool {
1305 self.len() == 0
1306 }
1307
1308 /// Timeline frames it occupies: its source range at its own speed, never
1309 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
1310 /// what it overlaps, how wide its box is -- is asked of this and not of
1311 /// [`Clip::len`].
1312 pub fn frames(&self) -> u32 {
1313 if self.speed_keys.is_empty() {
1314 self.speed.frames(self.len())
1315 } else {
1316 ramp_frames(&self.speed_keys, self.len())
1317 }
1318 }
1319
1320 /// One past the last timeline frame it covers.
1321 pub fn end(&self) -> u32 {
1322 self.start + self.frames()
1323 }
1324
1325 /// Whether a cut at `frame` lands cleanly on this clip: outside it, or inside at a frame
1326 /// its rate (or ramp) can address. What the razor asks before it offers to cut.
1327 pub fn splits_at(&self, frame: u32) -> bool {
1328 (self.start < frame && frame < self.end()) && split_source(self, frame).is_some()
1329 }
1330
1331 /// Source frames from the clip's in point to the one its `clip_frame`th timeline
1332 /// frame plays: [`Speed::source_at`], or for a ramped clip the ramp's integral
1333 /// floored ([`source_pos`]). What every "which source frame is on screen" asks,
1334 /// at a constant speed or not.
1335 pub fn source_offset(&self, clip_frame: u32) -> u32 {
1336 if self.speed_keys.is_empty() {
1337 self.speed.source_at(clip_frame)
1338 } else {
1339 ramp_source_at(&self.speed_keys, f64::from(clip_frame)).floor() as u32
1340 }
1341 }
1342
1343 /// The inverse of [`source_offset`](Clip::source_offset), ceiled: the first
1344 /// clip-relative timeline frame whose source frame is `source_offset` or past it
1345 /// -- [`Speed::timeline_at`], or the ramp's. Where a source instant that starts
1346 /// something (a word, a speech region) lands.
1347 pub fn timeline_offset(&self, source_offset: u32) -> u32 {
1348 if self.speed_keys.is_empty() {
1349 self.speed.timeline_at(source_offset)
1350 } else {
1351 SpeedRamp::new(&self.speed_keys, 0).timeline_at(source_offset)
1352 }
1353 }
1354
1355 /// [`timeline_offset`](Clip::timeline_offset) floored instead: the rounding an
1356 /// *end* needs, so a region never eats the frame the next thing starts on.
1357 pub fn timeline_offset_floor(&self, source_offset: u32) -> u32 {
1358 if self.speed_keys.is_empty() {
1359 (u64::from(source_offset) * 1000 / u64::from(self.speed.permille())).min(u64::from(u32::MAX))
1360 as u32
1361 } else {
1362 ramp_timeline_at(&self.speed_keys, f64::from(source_offset)).floor() as u32
1363 }
1364 }
1365
1366 /// [`source_offset`](Clip::source_offset) without the floor, for a fractional
1367 /// clip-relative timeline frame: source frames from the in point, continuous.
1368 pub fn source_offset_f(&self, clip_frame: f64) -> f64 {
1369 if self.speed_keys.is_empty() {
1370 clip_frame.max(0.0) * self.speed.as_f64()
1371 } else {
1372 ramp_source_at(&self.speed_keys, clip_frame)
1373 }
1374 }
1375
1376 /// The inverse of [`source_offset_f`](Clip::source_offset_f): the clip-relative
1377 /// timeline frame (fractional) at which the clip has played `source_frames` source
1378 /// frames of itself.
1379 pub fn timeline_offset_f(&self, source_frames: f64) -> f64 {
1380 if self.speed_keys.is_empty() {
1381 source_frames / self.speed.as_f64()
1382 } else {
1383 ramp_timeline_at(&self.speed_keys, source_frames)
1384 }
1385 }
1386
1387 /// The longest source range that fits in `frames` timeline frames at this clip's
1388 /// speed -- [`Speed::fit`], or for a ramped clip the largest length whose ramp
1389 /// footprint ([`ramp_frames`]) fits. `None` when nothing does.
1390 pub fn fit_source(&self, frames: u32) -> Option<u32> {
1391 if self.speed_keys.is_empty() {
1392 return self.speed.fit(frames);
1393 }
1394 if frames == 0 || ramp_frames(&self.speed_keys, 1) > frames {
1395 return None;
1396 }
1397 // The footprint is monotone in the source length, so bisect for the largest
1398 // that still fits. Doubling first bounds the search.
1399 let (mut lo, mut hi) = (1u32, 2u32);
1400 while ramp_frames(&self.speed_keys, hi) <= frames && hi < u32::MAX / 2 {
1401 lo = hi;
1402 hi *= 2;
1403 }
1404 while lo < hi {
1405 let mid = lo + (hi - lo).div_ceil(2);
1406 if ramp_frames(&self.speed_keys, mid) <= frames {
1407 lo = mid;
1408 } else {
1409 hi = mid - 1;
1410 }
1411 }
1412 Some(lo)
1413 }
1414}
1415
1416/// The speed a ramp runs at clip-relative frame `t`, linear between keys and held at
1417/// the ends, rounded to a [`Speed`] (thousandths).
1418pub fn ramp_speed_at(keys: &[SpeedKey], t: u32) -> Speed {
1419 let Some(first) = keys.first() else {
1420 return Speed::NORMAL;
1421 };
1422 if t <= first.at {
1423 return first.speed;
1424 }
1425 for w in keys.windows(2) {
1426 let (a, b) = (w[0], w[1]);
1427 if t <= b.at {
1428 let f = f64::from(t - a.at) / f64::from(b.at - a.at);
1429 let (ra, rb) = (a.speed.as_f64(), b.speed.as_f64());
1430 return Speed::from_permille(((ra + (rb - ra) * f) * 1000.).round() as u16);
1431 }
1432 }
1433 keys[keys.len() - 1].speed
1434}
1435
1436/// The keys of the part of a ramped clip from clip-relative frame `cut` on, rebased so
1437/// that `cut` is frame 0: the speed there first, then the keys after it, shifted.
1438/// What a clip's tail keeps when its head is cut away.
1439pub fn ramp_keys_from(keys: &[SpeedKey], cut: u32) -> Vec<SpeedKey> {
1440 let mut out = vec![SpeedKey {
1441 at: 0,
1442 speed: ramp_speed_at(keys, cut),
1443 }];
1444 out.extend(
1445 keys.iter()
1446 .filter(|k| k.at > cut)
1447 .map(|k| SpeedKey { at: k.at - cut, speed: k.speed }),
1448 );
1449 out
1450}
1451
1452/// A file the timeline plays from, and *which* of its audio streams it plays:
1453/// a file carrying one track per language is several sources, one per stream,
1454/// sharing a path. Two entries differing only in the stream are two sources --
1455/// they are what a clip names, and a clip plays exactly one stream.
1456///
1457/// The path is always canonical ([`Source::new`]), so the same file reached by
1458/// two paths is one source.
1459#[derive(Clone, Debug, Default)]
1460pub struct Source {
1461 pub path: PathBuf,
1462 /// Position among the file's audio tracks in file order, the numbering
1463 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
1464 /// single track, and for a silent one.
1465 pub audio_stream: usize,
1466 /// Starred in the library (v51). Not part of the source's identity.
1467 pub fav: bool,
1468 /// The [`Bin`] this source is filed in (v51); `0` for none, the library's top level.
1469 pub bin: u32,
1470}
1471
1472/// A source is the file and the stream: starring it or filing it in a bin does not make it
1473/// another source.
1474impl PartialEq for Source {
1475 fn eq(&self, other: &Self) -> bool {
1476 self.path == other.path && self.audio_stream == other.audio_stream
1477 }
1478}
1479impl Eq for Source {}
1480
1481/// A named folder in the media library (v51). Ids start at 1 and are never reused in a session.
1482/// `parent` is `0` for a top-level bin, or the id of a top-level bin: one level of nesting.
1483#[derive(Clone, Debug, PartialEq, Eq)]
1484pub struct Bin {
1485 pub id: u32,
1486 pub parent: u32,
1487 pub name: String,
1488}
1489
1490/// The longest bin name.
1491pub const MAX_BIN_NAME_CHARS: usize = 60;
1492/// The most bins a project holds.
1493pub const MAX_BINS: usize = 1_000;
1494
1495/// A bin name as the library keeps it: trimmed, non-empty, short, no control characters.
1496pub fn clean_bin_name(name: &str) -> Result<String, String> {
1497 let name = name.trim();
1498 if name.is_empty() {
1499 return Err("a bin needs a name".into());
1500 }
1501 if name.chars().count() > MAX_BIN_NAME_CHARS {
1502 return Err(format!("a bin name is at most {MAX_BIN_NAME_CHARS} characters"));
1503 }
1504 if name.chars().any(char::is_control) {
1505 return Err("a bin name holds no control characters".into());
1506 }
1507 Ok(name.to_string())
1508}
1509
1510impl Project {
1511 /// The library's bins, in creation order (v51).
1512 pub fn bins(&self) -> &[Bin] {
1513 &self.bins
1514 }
1515
1516 /// The bins a load puts back, with no undo step. Ids are kept; new ones start past the largest.
1517 pub fn with_bins(mut self, bins: Vec<Bin>) -> Self {
1518 self.bin_next = bins.iter().map(|b| b.id).max().unwrap_or(0) + 1;
1519 self.bins = bins;
1520 self
1521 }
1522
1523 fn bin_name_taken(&self, parent: u32, name: &str, except: u32) -> bool {
1524 self.bins.iter().any(|b| b.parent == parent && b.id != except && b.name.eq_ignore_ascii_case(name))
1525 }
1526
1527 /// Makes a bin named `name` inside bin `parent` (`0`: at the top level). Only a top-level bin
1528 /// holds bins, and two bins in one place cannot share a name. One undo step; returns the id.
1529 pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> {
1530 let name = clean_bin_name(name)?;
1531 if parent != 0 {
1532 match self.bins.iter().find(|b| b.id == parent) {
1533 None => return Err(format!("there is no bin {parent}")),
1534 Some(b) if b.parent != 0 => return Err("bins nest one level deep: that bin is already inside another".into()),
1535 Some(_) => {}
1536 }
1537 }
1538 if self.bin_name_taken(parent, &name, 0) {
1539 return Err(format!("there is already a bin named {name} there"));
1540 }
1541 if self.bins.len() >= MAX_BINS {
1542 return Err(format!("a project holds at most {MAX_BINS} bins"));
1543 }
1544 self.snapshot();
1545 let id = self.bin_next;
1546 self.bin_next += 1;
1547 self.bins.push(Bin { id, parent, name });
1548 Ok(id)
1549 }
1550
1551 /// Renames bin `id`. `Ok(false)`, and no undo step, when the name is already that.
1552 pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> {
1553 let name = clean_bin_name(name)?;
1554 let Some(at) = self.bins.iter().position(|b| b.id == id) else {
1555 return Err(format!("there is no bin {id}"));
1556 };
1557 if self.bins[at].name == name {
1558 return Ok(false);
1559 }
1560 if self.bin_name_taken(self.bins[at].parent, &name, id) {
1561 return Err(format!("there is already a bin named {name} there"));
1562 }
1563 self.snapshot();
1564 self.bins[at].name = name;
1565 Ok(true)
1566 }
1567
1568 /// Removes bin `id`. What it held is not lost: its sources go to the bin it was in (the top
1569 /// level for a top-level one) and the bins inside it come out to the top level. Returns how
1570 /// many sources moved. One undo step.
1571 pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> {
1572 let Some(bin) = self.bins.iter().find(|b| b.id == id).cloned() else {
1573 return Err(format!("there is no bin {id}"));
1574 };
1575 self.snapshot();
1576 let mut moved = 0;
1577 for s in self.sources.iter_mut().filter(|s| s.bin == id) {
1578 s.bin = bin.parent;
1579 moved += 1;
1580 }
1581 self.bins.retain(|b| b.id != id);
1582 let children: Vec<u32> = self.bins.iter().filter(|b| b.parent == id).map(|b| b.id).collect();
1583 for c in children {
1584 let at = self.bins.iter().position(|b| b.id == c).expect("listed above");
1585 let mut name = self.bins[at].name.clone();
1586 let mut n = 1;
1587 while self.bin_name_taken(0, &name, c) {
1588 n += 1;
1589 name = format!("{} {n}", self.bins[at].name);
1590 }
1591 self.bins[at].name = name;
1592 self.bins[at].parent = 0;
1593 }
1594 Ok(moved)
1595 }
1596
1597 /// Files sources `srcs` in bin `bin` (`0`: out of every bin, to the top level). Returns how
1598 /// many changed; one undo step, none when nothing changes.
1599 pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> {
1600 if bin != 0 && !self.bins.iter().any(|b| b.id == bin) {
1601 return Err(format!("there is no bin {bin}"));
1602 }
1603 if let Some(bad) = srcs.iter().find(|&&i| i >= self.sources.len()) {
1604 return Err(format!("there is no source {bad}"));
1605 }
1606 let mut todo: Vec<usize> = srcs.iter().copied().filter(|&i| self.sources[i].bin != bin).collect();
1607 todo.sort_unstable();
1608 todo.dedup();
1609 if todo.is_empty() {
1610 return Ok(0);
1611 }
1612 self.snapshot();
1613 for &i in &todo {
1614 self.sources[i].bin = bin;
1615 }
1616 Ok(todo.len())
1617 }
1618
1619 /// Stars or unstars sources `srcs`. Returns how many changed; one undo step, none when
1620 /// nothing changes.
1621 pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> {
1622 if let Some(bad) = srcs.iter().find(|&&i| i >= self.sources.len()) {
1623 return Err(format!("there is no source {bad}"));
1624 }
1625 let mut todo: Vec<usize> = srcs.iter().copied().filter(|&i| self.sources[i].fav != on).collect();
1626 todo.sort_unstable();
1627 todo.dedup();
1628 if todo.is_empty() {
1629 return Ok(0);
1630 }
1631 self.snapshot();
1632 for &i in &todo {
1633 self.sources[i].fav = on;
1634 }
1635 Ok(todo.len())
1636 }
1637}
1638
1639impl Source {
1640 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
1641 Self {
1642 path: canonical(path.as_ref()),
1643 audio_stream,
1644 fav: false,
1645 bin: 0,
1646 }
1647 }
1648}
1649
1650/// Which three-point edit [`Project::edit_from_source`] makes.
1651#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1652pub enum SourceEdit {
1653 /// Opens room: what is at and after the frame moves later.
1654 Insert,
1655 /// Replaces what is there for the take's length; nothing moves.
1656 Overwrite,
1657}
1658
1659/// What a lane carries, which is what a *gap* in it means: black frames on a
1660/// video lane, silence on an audio one, nothing over the picture on a subtitle
1661/// one.
1662#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1663pub enum LaneKind {
1664 Video,
1665 Audio,
1666 /// Words over the picture, placed and trimmed like everything else
1667 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
1668 /// so a caption is dragged, cut, rippled and undone by the machinery every
1669 /// other clip already goes through.
1670 ///
1671 /// It carries no [`Clip`] at all, and that is what keeps the media paths
1672 /// free of it: [`Project::lane`] hands back an empty slice, so every
1673 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
1674 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
1675 /// check it already had, [`Project::composite_span_at`] and
1676 /// [`Project::audio_lanes`] never look at it, and the three doors that
1677 /// could still put a picture on one -- [`Project::from_parts`],
1678 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
1679 Subtitle,
1680}
1681
1682/// Which lane an operation acts on: a kind plus a 0-based position among the
1683/// lanes of that kind, so [`Lane::V1`] is the first video lane and
1684/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
1685///
1686/// A handle, not the lane itself. It stays meaningful while lanes are added,
1687/// and one naming a lane that is not there reads as an empty lane and refuses
1688/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
1689/// bounds check of its own.
1690#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1691pub struct Lane {
1692 pub kind: LaneKind,
1693 pub ord: usize,
1694}
1695
1696impl Lane {
1697 /// The first video lane: what a decoder plays and what an export renders.
1698 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
1699 /// The first audio lane: what the audio worker plays.
1700 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
1701 /// The first subtitle lane -- the one a project has only once something
1702 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
1703 /// alone.
1704 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
1705
1706 pub const fn new(kind: LaneKind, ord: usize) -> Self {
1707 Self { kind, ord }
1708 }
1709
1710 /// `V1`, `A2`: how a lane is written in a header column and named in an
1711 /// error about it.
1712 pub fn label(self) -> String {
1713 let kind = match self.kind {
1714 LaneKind::Video => 'V',
1715 LaneKind::Audio => 'A',
1716 LaneKind::Subtitle => 'S',
1717 };
1718 format!("{kind}{}", self.ord + 1)
1719 }
1720}
1721
1722/// The shortest a cue may be trimmed to, in microseconds.
1723pub const MIN_CUE_US: i64 = 100_000;
1724
1725/// One cue of a caption lane as the timeline shows it: where it lands, which cue of which track it
1726/// is, and the part `window` of the cue's own clock that is shown.
1727#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1728pub struct CueSpan {
1729 pub start_us: i64,
1730 pub end_us: i64,
1731 pub track: usize,
1732 pub cue: usize,
1733 pub window: (i64, i64),
1734}
1735
1736/// One cue's saved word times: `(track, cue, [(start_us, end_us, word)])`.
1737pub type CueWordRow = (usize, usize, Vec<(i64, i64, String)>);
1738
1739/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
1740/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
1741/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
1742/// frames. Never empty at either end.
1743///
1744/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
1745/// actually has, and placed by the same one number: the window is in the
1746/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
1747/// placement is in timeline frames like everything else on a lane. So the lane
1748/// invariant is the lane's ([`subs_sorted_disjoint`] is
1749/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
1750/// else, and only the two calls that change a *duration* -- a trim, and the
1751/// mapping out -- ever need the timeline's rate.
1752///
1753/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
1754/// paste and an undo snapshot are a plain assignment and can never dangle.
1755#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1756pub struct SubClip {
1757 /// Timeline frame its first frame is shown at.
1758 pub start: u32,
1759 /// How many timeline frames it covers; `>= 1`. Held rather than derived
1760 /// from the window because a [`Project`] has no frame rate -- the rate
1761 /// enters at the door of the two calls that need it -- and every placement
1762 /// question (where it ends, what it overlaps) is asked in frames.
1763 pub frames: u32,
1764 /// Index into [`Project::subtitles`]: *which* track's words these are.
1765 pub track: usize,
1766 /// The half-open window of that track it shows, in microseconds from the
1767 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
1768 /// timed in, so no conversion stands between a cue and the window that
1769 /// keeps it.
1770 pub in_us: i64,
1771 pub out_us: i64,
1772 /// Group id: `Some` exactly when a hand put this caption in a group with
1773 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
1774 /// no group, and what a cut cuts apart loses the one it had
1775 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
1776 /// clip is what makes the caption move, trim and delete with it.
1777 pub link: Option<u32>,
1778}
1779
1780impl SubClip {
1781 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
1782 /// what every overlap question is asked of.
1783 pub fn end(&self) -> u32 {
1784 self.start + self.frames
1785 }
1786
1787 /// The whole of caption track `track`, whose last cue ends at `end_us`, as
1788 /// one placement at `fps` -- what a palette row dropped on a subtitle lane
1789 /// carries. The window is the frames' own length, not the track's: a track
1790 /// that ends between two frames (4.750 s on 143 frames) would otherwise be
1791 /// stretched over the frames it occupies, and every cue would show late by
1792 /// that fraction. The frames are the fewest that hold the last cue.
1793 pub fn whole_track(track: usize, end_us: i64, fps: f64) -> SubClip {
1794 let us_of = |f: u32| (f64::from(f) / fps * 1e6).round() as i64;
1795 let mut frames = ((end_us as f64) * fps / 1e6).ceil().clamp(1., f64::from(u32::MAX)) as u32;
1796 // The ceiling is at most one frame short, once the microsecond rounding is counted.
1797 if us_of(frames) < end_us {
1798 frames += 1;
1799 }
1800 let out_us = us_of(frames);
1801 SubClip { start: 0, frames, track, in_us: 0, out_us, link: None }
1802 }
1803
1804 /// How much of its track it shows, in microseconds; `>= 1` by the
1805 /// never-empty invariant, and never more than [`MAX_WINDOW_US`] for one
1806 /// that came through a door.
1807 pub fn window_us(&self) -> i64 {
1808 self.out_us.saturating_sub(self.in_us)
1809 }
1810
1811 /// Where in its window the timeline frame `frame` falls, in microseconds --
1812 /// the cut a split, a ripple and a trim all land on.
1813 ///
1814 /// By proportion and not by the timeline's rate: the window and the frame
1815 /// count measure the same stretch of time, so the fraction of the frames
1816 /// before `frame` is the fraction of the microseconds before it. That is
1817 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
1818 /// without either of them learning an fps.
1819 ///
1820 /// Total arithmetic, and clamped to the window it is cutting: the
1821 /// `saturating_mul` is what a `SubClip` built by a caller rather than a
1822 /// door gets (a hand-built one, a unit test, a future door that forgot the
1823 /// bound) -- a wrapped window would put a caption's clock *before* its own
1824 /// start, and the split that produced it would then hand back two halves
1825 /// whose windows do not meet. The clamp is the never-empty invariant
1826 /// restated: the answer is a point inside `[in_us, out_us]` or nothing.
1827 fn window_at(&self, frame: u32) -> i64 {
1828 let into = i64::from(frame.saturating_sub(self.start));
1829 let window = self.window_us().max(0);
1830 let at = window.saturating_mul(into) / i64::from(self.frames.max(1));
1831 self.in_us.saturating_add(at.min(window))
1832 }
1833}
1834
1835/// One lane: what it is and what it holds. A struct rather than a bare
1836/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
1837/// compositing mode, a name -- and it belongs next to the clips it applies to.
1838#[derive(Clone, Debug, PartialEq)]
1839struct LaneData {
1840 kind: LaneKind,
1841 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
1842 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
1843 /// ever seeing a subtitle: they all read this list.
1844 clips: Vec<Clip>,
1845 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
1846 /// empty on a video or audio one. Beside the clips rather than an enum over
1847 /// them so that everything a lane *is* -- its place in the stack, its
1848 /// label, its undo snapshot, its removal -- stays one code path for all
1849 /// three kinds.
1850 subs: Vec<SubClip>,
1851 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
1852 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
1853 /// makes it a different thing from a clip's equalizer: it moves everything
1854 /// on the track by the same amount, cuts included. Meaningless on a video
1855 /// lane, where it is kept at 0 and asked by nothing.
1856 gain_db: f32,
1857 /// Where this audio lane sits between the speakers, `-1.0..=1.0`, `0.0` the
1858 /// middle ([`Project::lane_pan`]); applied on top of each clip's own pan.
1859 pan: f32,
1860 /// The auto-ducks on this audio lane ([`Project::lane_duck_list`]): each
1861 /// drops the lane while the key lane it names is loud, so a lane can be
1862 /// ducked under several keys at once and the drops multiply. At most one per
1863 /// key, in the order they were set. Empty for every other lane.
1864 ducks: Vec<Duck>,
1865 /// The voice processors of this audio lane ([`Project::lane_voice`]): gate,
1866 /// noise reduction, compressor and de-esser, all off for a lane nobody has
1867 /// cleaned. Default on every other lane.
1868 voice: VoiceFx,
1869 /// Whether a video lane is left out of the picture, or a subtitle lane's
1870 /// words are left out of the screen and the export
1871 /// ([`Project::lane_hidden`]). Kept on the lane, not in a view, so that the
1872 /// editor and an export read one answer.
1873 hidden: bool,
1874 /// Whether an audio lane is silenced in the mix ([`Project::lane_muted`]).
1875 /// Its clips and its volume are untouched, so unmuting restores exactly
1876 /// what was there.
1877 muted: bool,
1878 /// Pure state for the front-end, which refuses edits to a locked lane. The
1879 /// engine's own operations ignore it ([`Project::lane_locked`]).
1880 locked: bool,
1881 /// The display label the user gave this lane ([`Project::lane_name`]); empty
1882 /// for none. The address (V1, A2) is unchanged by it.
1883 name: String,
1884}
1885
1886/// The longest lane name, in characters.
1887pub const MAX_LANE_NAME_CHARS: usize = 40;
1888
1889/// The three per-lane switches a save writes ([`Project::lane_flags`]), as one
1890/// value so that the file and the editor name them the same way.
1891#[derive(Clone, Copy, Debug, Default, PartialEq)]
1892pub struct LaneFlags {
1893 pub hidden: bool,
1894 pub muted: bool,
1895 pub locked: bool,
1896 /// An audio lane's pan ([`Project::lane_pan`]); carried here because it is saved and
1897 /// loaded with the switches.
1898 pub pan: f32,
1899}
1900
1901impl LaneData {
1902 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
1903 Self {
1904 kind,
1905 clips,
1906 subs: Vec::new(),
1907 gain_db: 0.0,
1908 pan: 0.0,
1909 ducks: Vec::new(),
1910 voice: VoiceFx::default(),
1911 hidden: false,
1912 muted: false,
1913 locked: false,
1914 name: String::new(),
1915 }
1916 }
1917
1918 /// The two lanes a project starts with: `V1` then `A1`, in display order.
1919 /// One place, because a freshly opened file is exactly this pair.
1920 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
1921 vec![
1922 LaneData::new(LaneKind::Video, video),
1923 LaneData::new(LaneKind::Audio, audio),
1924 ]
1925 }
1926}
1927
1928/// The placements one group id names, split by the two lists a lane holds:
1929/// what a drag, a trim and a delete each have to walk, now that a group may
1930/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
1931/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
1932/// -- so the pairs are `(lane storage index, index into that lane's list)`.
1933#[derive(Default)]
1934struct Members {
1935 clips: Vec<(usize, usize)>,
1936 subs: Vec<(usize, usize)>,
1937}
1938
1939impl Members {
1940 /// Whether the group is the one placement and no more: what a lift leaves
1941 /// behind, and what every whole-group question answers "not one" for.
1942 fn alone(&self) -> bool {
1943 self.clips.len() + self.subs.len() < 2
1944 }
1945}
1946
1947/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
1948#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1949pub enum Edge {
1950 /// Its first timeline frame; moving it changes where in the source the clip
1951 /// starts reading, so the picture behind the edge slides with it.
1952 Start,
1953 /// One past its last timeline frame; moving it only says how much of the
1954 /// source to keep.
1955 End,
1956}
1957
1958/// The two walls an edge may travel between, `(first, last)` timeline frame
1959/// inclusive, and which of them is the source's own media limit: its head
1960/// (for a start edge) or its tail (for an end edge). The other wall is a
1961/// neighbouring clip, the timeline's first frame, or the clip's own minimum
1962/// length -- never media. `lo_media`/`hi_media` say which, so a front-end can
1963/// tell a trim that ran out of source from one that ran into a clip.
1964#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1965pub struct TrimWalls {
1966 pub lo: u32,
1967 pub hi: u32,
1968 pub lo_media: bool,
1969 pub hi_media: bool,
1970}
1971
1972/// What stops an edge at one of its walls ([`Project::trim_bounds`]): the thing a
1973/// front-end names when a drag or a trim comes to rest there. Wherever a wall is
1974/// the frame a neighbour or the timeline sets, the clip sitting at that wall does
1975/// not say which, so this does.
1976#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1977pub enum WallBound {
1978 /// The source's own limit: its head for a start edge, its tail for an end
1979 /// edge. A clip that has run out of source.
1980 Source,
1981 /// The neighbouring clip on the same lane: the end of the one in front of a
1982 /// start edge, or the start of the one behind an end edge -- at this timeline
1983 /// frame.
1984 Neighbour(u32),
1985 /// The timeline's first frame, with no clip in front of the edge.
1986 Timeline,
1987 /// The clip's own minimum length: one source frame, at its rate.
1988 MinLength,
1989 /// The length a still image is held to -- the table's cap, which is not a
1990 /// source's end (a still has none to run out of).
1991 Cap,
1992}
1993
1994/// The length each source has on each kind of lane, in timeline frames: what a
1995/// trim measures its walls against. A picture and a sound of one file need not
1996/// end on the same frame ([`crate::playback`]'s audio-lane table), and a linked
1997/// take drags both edges together, so a trim of one lane has to hold the other
1998/// to the other's own length.
1999#[derive(Clone, Copy, Debug)]
2000pub struct SourceWalls<'a> {
2001 /// The length on a video lane (and on a subtitle lane, which has none).
2002 pub picture: &'a [u32],
2003 /// The length on an audio lane.
2004 pub sound: &'a [u32],
2005}
2006
2007impl<'a> SourceWalls<'a> {
2008 /// One table for both kinds of lane: for a caller that has only the one.
2009 pub fn same(frames: &'a [u32]) -> Self {
2010 Self {
2011 picture: frames,
2012 sound: frames,
2013 }
2014 }
2015
2016 /// The table a clip on a lane of `kind` is walled by.
2017 fn for_kind(&self, kind: LaneKind) -> &'a [u32] {
2018 if kind == LaneKind::Audio {
2019 self.sound
2020 } else {
2021 self.picture
2022 }
2023 }
2024}
2025
2026/// What a lane holds over one stretch of the timeline: either a placed clip or
2027/// a gap. Returned already trimmed to the position it was asked about, so a
2028/// caller can hand `len` straight to a decoder (or to a black-frame generator).
2029#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2030pub struct Span {
2031 /// Timeline frame the span starts at.
2032 pub start: u32,
2033 /// Frames it covers; `>= 1`.
2034 pub len: u32,
2035 /// `(source index, first source frame)`, or `None` for a gap -- which the
2036 /// engine renders as black frames and as silence.
2037 pub from: Option<(usize, u32)>,
2038 /// The rate the clip this came off plays at ([`Clip::speed`]);
2039 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
2040 /// timeline frames whatever it says -- the speed is how many *source* frames
2041 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
2042 /// come back to the timeline.
2043 pub speed: Speed,
2044 /// The speed ramp of the clip this came off, when it has one ([`Clip::speed_keys`]),
2045 /// based at this span's first frame. A ramped span's [`speed`](Span::speed) is
2046 /// [`Speed::NORMAL`]: a constant rate would be wrong for it, and real time is what
2047 /// a decoder reads every frame at, so every mapping goes through
2048 /// [`source_offset`](Span::source_offset) instead.
2049 pub ramp: Option<SpeedRamp>,
2050 /// Whether the clip this came off plays backwards ([`Clip::reversed`]). Then
2051 /// `from` still names the source frame the span's first timeline frame shows --
2052 /// the highest of the frames it reads -- and every later frame is
2053 /// [`source_offset`](Span::source_offset) *below* it ([`Span::source_at`]); the
2054 /// offsets themselves, [`source_len`](Span::source_len) and
2055 /// [`timeline_at`](Span::timeline_at) count distance walked, as they do forwards.
2056 /// `false` for a gap.
2057 pub reverse: bool,
2058 /// The pitch in semitones of the clip this came off ([`Clip::pitch`]); `0` for a gap.
2059 pub pitch: i8,
2060}
2061
2062impl Span {
2063 /// One past the last timeline frame it covers.
2064 pub fn end(&self) -> u32 {
2065 self.start + self.len
2066 }
2067
2068 /// Source frames from this span's first frame to its `offset`th: the mapping
2069 /// `speed.source_at(offset)` is for a constant rate, and the ramp's integral when
2070 /// the span carries one. Added to the span's `from` source frame it gives the
2071 /// frame the timeline frame at `offset` shows.
2072 pub fn source_offset(&self, offset: u32) -> u32 {
2073 match &self.ramp {
2074 None => self.speed.source_at(offset),
2075 Some(ramp) => ramp.source_offset(offset),
2076 }
2077 }
2078
2079 /// The source frame the timeline frame `offset` into the span shows, given
2080 /// `first`, the span's own first one (`from`'s): up for a span that plays
2081 /// forwards, down for a reversed one.
2082 pub fn source_at(&self, first: u32, offset: u32) -> u32 {
2083 match self.reverse {
2084 false => first + self.source_offset(offset),
2085 true => first.saturating_sub(self.source_offset(offset)),
2086 }
2087 }
2088
2089 /// The half-open range of source frames this span reads, `first..end`, in the
2090 /// order they are numbered in the file whichever way they are played. `None` for
2091 /// a gap. The window a decoder is opened over, and an audio segment's.
2092 pub fn source_window(&self) -> Option<(usize, u32, u32)> {
2093 let (source, first) = self.from?;
2094 let len = self.source_len();
2095 Some(match self.reverse {
2096 false => (source, first, first + len),
2097 true => (source, (first + 1).saturating_sub(len), first + 1),
2098 })
2099 }
2100
2101 /// How many source frames it reads: what a decoder is asked for and how wide
2102 /// an audio window is. `len` at real time, and the one arithmetic both the
2103 /// picture and the sound go through, so they cannot disagree about where a
2104 /// speeded clip ends.
2105 pub fn source_len(&self) -> u32 {
2106 match self.from {
2107 // The last timeline frame's own source frame is the last one needed
2108 // -- never one more, which at a slow rate would read a frame the
2109 // next clip owns and at a fast one would decode a picture nothing
2110 // shows.
2111 Some(_) => self.source_offset(self.len.saturating_sub(1)) + 1,
2112 None => self.len,
2113 }
2114 }
2115
2116 /// Where a source frame of this span lands on the timeline: the stamp
2117 /// playback puts on a decoded frame, through the ceil half of the pair
2118 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
2119 /// frame, so a frame before it stamps at the span's start.
2120 pub fn timeline_at(&self, source_frame: u32) -> u32 {
2121 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
2122 let rel = source_frame.saturating_sub(base);
2123 self.start
2124 + match &self.ramp {
2125 None => self.speed.timeline_at(rel),
2126 Some(ramp) => ramp.timeline_at(rel),
2127 }
2128 }
2129}
2130
2131/// What one speeded audio segment asks of the worker: how many source frames to
2132/// consume per output frame, and how many seconds of timeline it has to fill.
2133/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
2134/// resampling at all.
2135#[derive(Clone, Copy, PartialEq, Debug)]
2136pub struct Stretch {
2137 /// Source frames per output frame -- the speed as a multiplier.
2138 pub step: f64,
2139 /// What the segment owes the timeline, which is what it is padded or
2140 /// trimmed to.
2141 pub timeline_secs: f64,
2142 /// The segment's speed ramp, when it has one: the stretch then follows the ramp's
2143 /// instantaneous rate rather than `step`, which is only the mean it falls back to.
2144 pub ramp: Option<SpeedRamp>,
2145 /// The timeline's frame rate, which the ramp's frames are counted in. The
2146 /// openers do not all know it, so the stretch carries it.
2147 pub fps: f64,
2148 /// Whether the segment's samples are played last to first
2149 /// ([`Clip::reversed`]). Then `step` is `1.0` when only the direction asks for a
2150 /// rate chain at all, and the window the segment names is the one to be reversed.
2151 pub reverse: bool,
2152 /// The pitch in semitones the segment is shifted by ([`Clip::pitch`]), `0` for none.
2153 /// The stretch then runs at `step / 2^(pitch/12)` and the resample at the same ratio
2154 /// up: the pitch moves, the length does not.
2155 pub pitch: i8,
2156}
2157
2158impl Stretch {
2159 /// Whether the segment is only played backwards, at the rate it was recorded:
2160 /// no change of time, so no stretch is built for it.
2161 pub fn is_straight(&self) -> bool {
2162 self.reverse && self.step == 1.0 && self.ramp.is_none() && self.pitch == 0
2163 }
2164
2165 /// The frequency ratio the segment's pitch shift is: `2^(pitch/12)`, `1.0` for none.
2166 pub fn pitch_ratio(&self) -> f64 {
2167 pitch_ratio(self.pitch)
2168 }
2169}
2170
2171/// The frequency ratio of a shift of `semitones`: `2^(semitones/12)`, so `12` is an octave up.
2172pub fn pitch_ratio(semitones: i8) -> f64 {
2173 (f64::from(semitones) / 12.0).exp2()
2174}
2175
2176/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
2177/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
2178/// against where in the *clip* -- not the segment, which may start mid-clip
2179/// on a seek -- this segment's first frame lands.
2180#[derive(Clone, PartialEq, Debug)]
2181pub struct Fade {
2182 /// How many of the clip's own frames already played before this
2183 /// segment's first frame: `0` unless playback started mid-clip.
2184 pub elapsed: u32,
2185 /// The clip's [`Clip::fade_in`].
2186 pub fade_in: u32,
2187 /// The clip's [`Clip::fade_out`].
2188 pub fade_out: u32,
2189 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
2190 /// which this segment may only cover the tail.
2191 pub total: u32,
2192 /// The clip's [`Clip::gain_db`] as a linear multiplier, `1.0` for unity.
2193 /// It rides in the envelope because the envelope is what both the
2194 /// playback feeder and the export are handed, so the two cannot disagree.
2195 pub gain: f32,
2196 /// The left and right multipliers of the clip's pan and its lane's
2197 /// ([`pan_gains`]), `(1.0, 1.0)` for the middle. Only a stereo mix has a
2198 /// side to turn down; any other width plays it as it is.
2199 pub pan: (f32, f32),
2200 /// The clip's [`Clip::gain_keys`] as `(position, dB, ease)` triples, `None` for a
2201 /// clip with none. The position is clip-relative and in this envelope's own
2202 /// unit: timeline frames when [`Project::lane_fades_from`] builds it, audio
2203 /// frames once [`Fade::scaled`] has counted it. Shared, so the envelope
2204 /// stays cheap to hand around.
2205 pub curve: Option<std::sync::Arc<[(f64, f32, KeyEase)]>>,
2206}
2207
2208/// The left and right multipliers of a clip pan and a lane pan, each `-1.0..=1.0`: a
2209/// balance, where the side away from the pan is turned down along a quarter sine
2210/// (`cos(pan * pi/2)`, silent at the far end) and the near side is left alone,
2211/// so the middle is exactly unity.
2212impl Clip {
2213 /// [`Clip::pan`] as `-1.0..=1.0`.
2214 pub fn pan_value(&self) -> f32 {
2215 f32::from(self.pan) / 100.0
2216 }
2217}
2218
2219pub fn pan_gains(clip: f32, lane: f32) -> (f32, f32) {
2220 let side = |p: f32| {
2221 let p = p.clamp(-1.0, 1.0);
2222 (p.max(0.0) * std::f32::consts::FRAC_PI_2, (-p).max(0.0) * std::f32::consts::FRAC_PI_2)
2223 };
2224 let (cl, cr) = side(clip);
2225 let (ll, lr) = side(lane);
2226 // cos(pi/2) is not exactly 0 in f32: the far end is silence, so say so.
2227 let snap = |g: f32| if g < 1e-6 { 0.0 } else { g };
2228 (snap(cl.cos() * ll.cos()), snap(cr.cos() * lr.cos()))
2229}
2230
2231impl Fade {
2232 /// The gain at clip-relative frame `pos`, an equal-power curve on each
2233 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
2234 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
2235 /// ramp, so a fade lands on silence at its very first (or very last)
2236 /// frame and reaches unity smoothly rather than at a constant slope --
2237 /// the same curve [`Project::crossfade`] relies on to keep two clips'
2238 /// sum around one level through the join. Both ramps multiply where a
2239 /// clip is short enough for them to overlap.
2240 fn gain_at(&self, pos: u32) -> f32 {
2241 let mut g = self.gain;
2242 if let Some(curve) = &self.curve {
2243 g *= db_to_linear(lerp_db(curve, |&p| p, f64::from(pos)));
2244 }
2245 if self.fade_in > 0 && pos < self.fade_in {
2246 let t = pos as f32 / self.fade_in as f32;
2247 g *= (t * std::f32::consts::FRAC_PI_2).sin();
2248 }
2249 if self.fade_out > 0 {
2250 let out_start = self.total.saturating_sub(self.fade_out);
2251 if pos >= out_start {
2252 let remaining = self.total.saturating_sub(pos);
2253 let t = remaining as f32 / self.fade_out as f32;
2254 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
2255 }
2256 }
2257 g
2258 }
2259
2260 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
2261 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
2262 pub fn apply(&self, frames: &mut [f32], channels: usize) {
2263 for (i, block) in frames.chunks_mut(channels).enumerate() {
2264 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
2265 for s in block.iter_mut() {
2266 *s *= g;
2267 }
2268 if channels == 2 && block.len() == 2 {
2269 block[0] *= self.pan.0;
2270 block[1] *= self.pan.1;
2271 }
2272 }
2273 }
2274
2275 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
2276 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
2277 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
2278 /// position is in) but [`Self::apply`] multiplies *audio* frames --
2279 /// `channels`-wide sample blocks at whatever rate the mix is running at,
2280 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
2281 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
2282 /// few milliseconds into any clip, so a fade-out silenced the rest of the
2283 /// clip outright and a fade-in finished before a listener's ear caught up
2284 /// -- audible on nothing shorter than a clip a few fps-frames long, which
2285 /// is why 338 green tests never once ran the two curves out of step.
2286 /// `ratio` is `sample_rate / fps`, applied once where the audio session
2287 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
2288 pub fn scaled(self, ratio: f64) -> Fade {
2289 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
2290 Fade {
2291 elapsed: conv(self.elapsed),
2292 fade_in: conv(self.fade_in),
2293 fade_out: conv(self.fade_out),
2294 total: conv(self.total),
2295 gain: self.gain,
2296 pan: self.pan,
2297 curve: self.curve.as_ref().map(|c| {
2298 c.iter()
2299 .map(|&(x, db, ease)| (x * ratio, db, ease))
2300 .collect::<Vec<_>>()
2301 .into()
2302 }),
2303 }
2304 }
2305}
2306
2307/// What a save writes and a load takes back: the sources, every lane in
2308/// display order with its kind, and the equalizer and colour tables their clips
2309/// index into -- [`Project::without_orphan_sources`] out,
2310/// [`Project::from_parts`] in.
2311pub type Parts = (
2312 Vec<Source>,
2313 Vec<(LaneKind, Vec<Clip>)>,
2314 Vec<EqParams>,
2315 Vec<ColorParams>,
2316 Vec<TransformParams>,
2317);
2318
2319/// The next revision id to hand out. Process-wide, so two projects never share
2320/// an id and a revision read from one session means nothing in another.
2321static NEXT_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
2322
2323fn next_revision() -> u64 {
2324 NEXT_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2325}
2326
2327/// How many undo steps a project keeps. One gesture is one step, so 100 is past
2328/// any chain a person walks back by hand, and the oldest step is dropped rather
2329/// than the history growing without end: a snapshot is the whole lane list plus
2330/// the palette and the project's own settings, so on a 1394-clip jumpcut
2331/// timeline this is a bounded ~10 MB instead of a leak that grows for as long
2332/// as the session lasts.
2333const HISTORY_CAP: usize = 100;
2334
2335/// The project's own settings, as one value: the header a `.edith` file carries
2336/// beside the edit list, and what every undo step restores beside the lanes.
2337/// None of it is the media's own -- the scaffolding file's picture and rate
2338/// ([`PlaybackSession::native`]) stay on the session and are never rolled back.
2339#[derive(Clone, Debug, PartialEq)]
2340pub(crate) struct ProjectSettings {
2341 /// The canvas every clip is composed onto: the project resolution, which a
2342 /// clip of another size is placed onto rather than refused for.
2343 pub(crate) resolution: (u32, u32),
2344 /// The rate the timeline is cut at, which every clip and source is
2345 /// conformed to ([`Project::retime`]).
2346 pub(crate) frame_rate: f64,
2347 /// Which encoder an export of this project opens its picture on
2348 /// ([`crate::export::EncoderSeat`]).
2349 pub(crate) encoder_seat: crate::export::EncoderSeat,
2350 /// The rate the mix was picked to run at, or `None` for the one the first
2351 /// audio source derives.
2352 pub(crate) sample_rate: Option<u32>,
2353 /// Whether the picture is decoded from the stand-ins ([`crate::proxy`]).
2354 pub(crate) proxies: bool,
2355 /// Whether a source that wants a stand-in gets one made for it as it
2356 /// arrives ([`crate::proxy::wanted`]).
2357 pub(crate) auto_proxies: bool,
2358 /// Which HDR-to-SDR rendition the picture is watched and exported in.
2359 pub(crate) tone: crate::tonemap::Preset,
2360 /// The master limiter every lane's sound is summed through.
2361 pub(crate) limiter: Limiter,
2362 /// How burned captions animate, the default for `burn_captions`.
2363 pub(crate) caption_style: crate::captionanim::CaptionStyle,
2364 /// The free-text notes the project carries (v52). Empty until somebody writes one.
2365 pub(crate) notes: String,
2366 /// How long a still image is placed for, in seconds (v52).
2367 pub(crate) still_secs: f64,
2368 /// The speech model the transcript and captions run on; `None` picks one (v57).
2369 pub(crate) speech_model: Option<String>,
2370 /// The device the speech model runs on (v57).
2371 pub(crate) speech_device: crate::speech::DeviceChoice,
2372}
2373
2374impl ProjectSettings {
2375 /// What a project built by hand carries before its constructor names the
2376 /// canvas: the defaults every fresh open has -- nobody has picked stand-ins
2377 /// (the films themselves are cut), an encoder or a mix rate, and the
2378 /// rendition and limiter are the reference ones. Every door that builds a
2379 /// session chains [`Project::with_canvas`] straight after, so the zero
2380 /// canvas here is never a project anybody plays from.
2381 fn placeholder() -> Self {
2382 Self {
2383 resolution: (0, 0),
2384 frame_rate: 0.0,
2385 encoder_seat: crate::export::EncoderSeat::default(),
2386 sample_rate: None,
2387 proxies: false,
2388 auto_proxies: false,
2389 tone: crate::tonemap::Preset::default(),
2390 limiter: Limiter::default(),
2391 caption_style: crate::captionanim::CaptionStyle::default(),
2392 notes: String::new(),
2393 still_secs: STILL_DEFAULT_SECS,
2394 speech_model: None,
2395 speech_device: crate::speech::DeviceChoice::Auto,
2396 }
2397 }
2398}
2399
2400/// One undo step: the lanes, the subtitle palette and the project's own
2401/// settings exactly as they were before the edit that pushed it. Whole values
2402/// rather than the lane list alone, so an undo (or a redo) restores all three
2403/// together and no half of one edit can come back without the others -- which
2404/// is what lets a subtitle removal reindex every placement and still undo: the
2405/// restored palette names the very tracks the restored placements index.
2406/// What a freshly pushed undo step displaced: the redo branch its edit cleared
2407/// and, when the cap was full, the oldest step it evicted. Moved, never cloned.
2408#[derive(Clone, Debug)]
2409struct PendingStep {
2410 redo: Vec<Snapshot>,
2411 evicted: Option<Snapshot>,
2412}
2413
2414#[derive(Clone, Debug)]
2415struct Snapshot {
2416 /// The revision of the state this step restores ([`Project::revision`]).
2417 revision: u64,
2418 /// The name of the edit that pushed this step ([`Project::name_step`]): what
2419 /// Undo and Redo say. `None` for a step nobody named, which reads as plain "Undo".
2420 /// It travels with the step, so an undo's redo entry carries the same name.
2421 label: Option<String>,
2422 lanes: Vec<LaneData>,
2423 subtitles: Vec<SubtitleTrack>,
2424 cue_edits: Vec<(usize, usize, String)>,
2425 cue_adds: Vec<AddedCue>,
2426 titles: Vec<Title>,
2427 chapters: Vec<Chapter>,
2428 markers: Vec<Marker>,
2429 settings: ProjectSettings,
2430 /// The files the clips index into, as the step had them: a relink is undone by putting the
2431 /// old path back here. A [`Source`] is a path and a stream index, so a copy is cheap.
2432 sources: Vec<Source>,
2433 /// The library's bins (v51).
2434 bins: Vec<Bin>,
2435 /// The sequence list: which is active, every name, and the parked ones' data.
2436 seq: Seqs,
2437}
2438
2439/// The source list an undo or redo step puts back: the step's own list, and past its end the
2440/// entries the step never knew of (imported after it). No clip in the step names one of those,
2441/// so keeping them leaves every index the step holds valid, and an undone edit leaves an import
2442/// in the library as an import always does.
2443fn restored_sources(step: Vec<Source>, now: &[Source]) -> Vec<Source> {
2444 let mut out = step;
2445 if now.len() > out.len() {
2446 out.extend_from_slice(&now[out.len()..]);
2447 }
2448 out
2449}
2450
2451/// The redo stack moved out by [`Project::take_redo`]: opaque, and only
2452/// [`Project::restore_redo`] reads it back.
2453pub struct RedoCheckpoint(Vec<Snapshot>);
2454
2455/// A cue somebody added to a subtitle track, which no file has: its track, its
2456/// times on the track's own clock and its words. Kept beside the file's cue
2457/// overrides ([`Project::cue_adds`]) because a `(track, cue, text)` override
2458/// names a cue by where the file has it, and an added cue has no such place.
2459#[derive(Clone, Debug, PartialEq, Eq)]
2460pub struct AddedCue {
2461 pub track: usize,
2462 pub start_us: i64,
2463 pub end_us: i64,
2464 pub text: String,
2465}
2466
2467/// One gap a close-all sweep left open, with the frame it still starts on and
2468/// the same refusal a single [`Project::gap_take_scope`] close would have said.
2469#[derive(Clone, Debug, PartialEq, Eq)]
2470pub struct GapSkip {
2471 pub start: u32,
2472 pub reason: String,
2473}
2474
2475/// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits,
2476/// skipped gaps are the take-safety refusals the sweep did not hide.
2477#[derive(Clone, Debug, Default, PartialEq, Eq)]
2478pub struct GapSweep {
2479 pub closed: usize,
2480 pub skipped: Vec<GapSkip>,
2481}
2482
2483/// A chapter marker: a named frame on the timeline, the point a viewer's chapter
2484/// list jumps to. Sorted by frame, at most one per frame ([`Project::chapters`]).
2485/// Saved as `chapter` lines ([`crate::edith`]).
2486#[derive(Clone, Debug, PartialEq, Eq)]
2487pub struct Chapter {
2488 /// The timeline frame the chapter starts on.
2489 pub frame: u32,
2490 /// What the chapter is called in the list.
2491 pub title: String,
2492}
2493
2494/// The longest chapter name, in characters: the most a video platform's chapter
2495/// list shows.
2496pub const MAX_CHAPTER_CHARS: usize = 100;
2497
2498/// Whether `chapter` is a chapter the project may hold: the checks
2499/// [`Project::add_chapter`] makes and the `.edith` loader makes of every `chapter` line.
2500pub fn check_chapter(chapter: &Chapter) -> crate::Result<()> {
2501 if chapter.title.trim().is_empty() {
2502 return Err("a chapter needs a name".into());
2503 }
2504 if chapter.title.chars().count() > MAX_CHAPTER_CHARS {
2505 return Err(format!("a chapter name holds at most {MAX_CHAPTER_CHARS} characters").into());
2506 }
2507 Ok(())
2508}
2509
2510/// A marker's colour: the small fixed palette an editor's marker strip draws.
2511#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2512pub enum MarkerColor {
2513 Red,
2514 Orange,
2515 Yellow,
2516 Green,
2517 #[default]
2518 Blue,
2519 Purple,
2520}
2521
2522impl MarkerColor {
2523 /// Every colour, in palette order.
2524 pub const ALL: [MarkerColor; 6] = [
2525 MarkerColor::Red,
2526 MarkerColor::Orange,
2527 MarkerColor::Yellow,
2528 MarkerColor::Green,
2529 MarkerColor::Blue,
2530 MarkerColor::Purple,
2531 ];
2532
2533 /// The name the `.edith` file and the MCP tools use.
2534 pub fn name(self) -> &'static str {
2535 match self {
2536 MarkerColor::Red => "red",
2537 MarkerColor::Orange => "orange",
2538 MarkerColor::Yellow => "yellow",
2539 MarkerColor::Green => "green",
2540 MarkerColor::Blue => "blue",
2541 MarkerColor::Purple => "purple",
2542 }
2543 }
2544
2545 /// The colour called `name` (any case), if it is one of the palette.
2546 pub fn from_name(name: &str) -> Option<MarkerColor> {
2547 MarkerColor::ALL.into_iter().find(|c| c.name().eq_ignore_ascii_case(name.trim()))
2548 }
2549
2550 /// The colour after this one in the palette, wrapping: what the GUI's "next colour" steps through.
2551 pub fn next(self) -> MarkerColor {
2552 let i = MarkerColor::ALL.iter().position(|c| *c == self).unwrap_or(0);
2553 MarkerColor::ALL[(i + 1) % MarkerColor::ALL.len()]
2554 }
2555}
2556
2557/// A comment marker: a named, coloured point on the timeline with an optional note, or a
2558/// range when `length` is not 0. Separate from a [`Chapter`]; it moves with the picture the
2559/// same way. Sorted by frame; several may share a frame ([`Project::markers`]). Saved as
2560/// `marker` lines ([`crate::edith`]).
2561#[derive(Clone, Debug, PartialEq, Eq)]
2562pub struct Marker {
2563 /// The timeline frame the marker starts on.
2564 pub frame: u32,
2565 /// How many frames it spans; 0 is a point.
2566 pub length: u32,
2567 pub name: String,
2568 /// A free-text note; may be empty.
2569 pub note: String,
2570 pub color: MarkerColor,
2571}
2572
2573impl Marker {
2574 /// The frame a range marker ends on (exclusive); its start for a point.
2575 pub fn end(&self) -> u32 {
2576 self.frame.saturating_add(self.length)
2577 }
2578}
2579
2580/// The longest marker name, in characters.
2581pub const MAX_MARKER_NAME_CHARS: usize = 100;
2582/// The longest marker note, in characters.
2583pub const MAX_MARKER_NOTE_CHARS: usize = 2000;
2584
2585/// Whether `marker` is a marker the project may hold: the checks [`Project::add_marker`]
2586/// makes and the `.edith` loader makes of every `marker` line.
2587pub fn check_marker(marker: &Marker) -> crate::Result<()> {
2588 if marker.name.trim().is_empty() {
2589 return Err("a marker needs a name".into());
2590 }
2591 if marker.name.chars().count() > MAX_MARKER_NAME_CHARS {
2592 return Err(format!("a marker name holds at most {MAX_MARKER_NAME_CHARS} characters").into());
2593 }
2594 if marker.note.chars().count() > MAX_MARKER_NOTE_CHARS {
2595 return Err(format!("a marker note holds at most {MAX_MARKER_NOTE_CHARS} characters").into());
2596 }
2597 if marker.frame.checked_add(marker.length).is_none_or(|e| e > MAX_TITLE_END) {
2598 return Err("a marker runs past the last frame there is".into());
2599 }
2600 Ok(())
2601}
2602
2603/// The longest text a title can hold, in characters.
2604pub const MAX_TITLE_CHARS: usize = 500;
2605
2606/// The furthest frame a title may end on. Far past any timeline anyone cuts,
2607/// and far below `u32::MAX`, so `start + frames` cannot wrap.
2608pub const MAX_TITLE_END: u32 = 100_000_000;
2609
2610/// A text overlay on the timeline: a title card over black, or a caption such
2611/// as a lower third over the picture. Titles are a project-level list, not a
2612/// lane: they are drawn over the composed picture (black where no clip plays),
2613/// in list order, so a later title sits on top of an earlier one. Saved as
2614/// `title` lines ([`crate::edith`]).
2615#[derive(Clone, Debug, PartialEq)]
2616pub struct Title {
2617 /// The first timeline frame the title shows on.
2618 pub start: u32,
2619 /// How many frames it shows for; `>= 1`.
2620 pub frames: u32,
2621 /// The words, with `\n` as a line break. Non-empty, at most
2622 /// [`MAX_TITLE_CHARS`] characters.
2623 pub text: String,
2624 /// How the words are set. Its size is kept inside [`SIZE_RANGE`].
2625 pub style: TextStyle,
2626 /// Frames the title takes to come up from nothing: the first frame shows
2627 /// `1 / (fade_in + 1)` of it. `0` for no fade-in.
2628 pub fade_in: u32,
2629 /// Frames the title takes to go back to nothing, counted off the end.
2630 /// `0` for no fade-out.
2631 pub fade_out: u32,
2632 /// The animation it comes in with ([`crate::titleanim`]); `None` for none.
2633 pub in_anim: TitleAnim,
2634 /// The animation it goes out with; the reverse of `in_anim`'s motion.
2635 pub out_anim: TitleAnim,
2636 /// How many frames each animation takes; `>= 1` when either is set and at most `frames`.
2637 pub anim_frames: u32,
2638 /// The title's own keyframe animation, counted from its first frame: sorted by `at`, no two
2639 /// at one frame, at most [`MAX_TRANSFORM_KEYS`]. Empty for a title without one.
2640 pub keys: Vec<TitleKey>,
2641}
2642
2643impl Title {
2644 /// One past the last frame the title covers.
2645 pub fn end(&self) -> u32 {
2646 self.start.saturating_add(self.frames)
2647 }
2648
2649 /// How much of the title shows on timeline frame `frame`, 0 to 255: its
2650 /// fades and animations ramp it up and down, and a frame outside the title shows none.
2651 pub fn alpha_at(&self, frame: u32) -> u8 {
2652 self.motion_at(frame).map_or(0, |m| m.alpha)
2653 }
2654}
2655
2656/// A one-click look for a title. The app's title card and MCP's `preset` argument both
2657/// apply these, so the two never disagree on what "lower third" means.
2658#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2659pub enum TitlePreset {
2660 LowerThird,
2661 Centered,
2662 CaptionBar,
2663}
2664
2665impl TitlePreset {
2666 /// Every preset, in the order the app lists them.
2667 pub const ALL: [TitlePreset; 3] = [TitlePreset::LowerThird, TitlePreset::Centered, TitlePreset::CaptionBar];
2668
2669 /// The word that names the preset in MCP: `lower_third`, `centered` or `caption_bar`.
2670 pub fn key(self) -> &'static str {
2671 match self {
2672 TitlePreset::LowerThird => "lower_third",
2673 TitlePreset::Centered => "centered",
2674 TitlePreset::CaptionBar => "caption_bar",
2675 }
2676 }
2677
2678 /// The preset a word names, if it names one.
2679 pub fn from_key(word: &str) -> Option<TitlePreset> {
2680 TitlePreset::ALL.into_iter().find(|p| p.key() == word)
2681 }
2682
2683 /// The style and the fade length in seconds (in and out).
2684 pub fn look(self) -> (TextStyle, f64) {
2685 let base = TextStyle::default();
2686 match self {
2687 TitlePreset::LowerThird => (
2688 TextStyle {
2689 size: 45,
2690 outline: Outline::None,
2691 boxed: true,
2692 place: Place::Bottom,
2693 hplace: HPlace::Left,
2694 align: Align::Left,
2695 weight: Weight::Bold,
2696 ..base
2697 },
2698 0.5,
2699 ),
2700 TitlePreset::Centered => (TextStyle { size: 100, outline: Outline::Thin, boxed: false, place: Place::Centre, ..base }, 0.5),
2701 TitlePreset::CaptionBar => (TextStyle { size: 40, outline: Outline::None, boxed: true, place: Place::Bottom, ..base }, 0.0),
2702 }
2703 }
2704}
2705
2706impl Title {
2707 /// `self` in `preset`'s look. The words and timing stay; fades are held to half the
2708 /// title's length, so in and out never cross.
2709 pub fn apply_preset(&mut self, preset: TitlePreset, fps: f64) {
2710 let (style, fade) = preset.look();
2711 let fade = ((fade * fps).round() as u32).min(self.frames / 2);
2712 self.style = style;
2713 self.fade_in = fade;
2714 self.fade_out = fade;
2715 }
2716}
2717
2718/// Whether `title` is a title the project may hold: the checks [`Project::add_title`]
2719/// makes and the `.edith` loader makes of every `title` line.
2720pub fn check_title(title: &Title) -> crate::Result<()> {
2721 if title.frames == 0 {
2722 return Err("a title must show for at least one frame".into());
2723 }
2724 if title.text.trim().is_empty() {
2725 return Err("a title needs some text".into());
2726 }
2727 if title.text.chars().count() > MAX_TITLE_CHARS {
2728 return Err(format!("a title holds at most {MAX_TITLE_CHARS} characters").into());
2729 }
2730 if title.end() > MAX_TITLE_END {
2731 return Err(format!("a title ends past frame {MAX_TITLE_END}").into());
2732 }
2733 if title.fade_in > title.frames || title.fade_out > title.frames {
2734 return Err("a title's fades are no longer than the title".into());
2735 }
2736 let animated = title.in_anim != TitleAnim::None || title.out_anim != TitleAnim::None;
2737 if animated && (title.anim_frames == 0 || title.anim_frames > title.frames) {
2738 return Err("a title's animations last at least one frame and no longer than the title".into());
2739 }
2740 if !(SIZE_RANGE.0..=SIZE_RANGE.1).contains(&title.style.size) {
2741 return Err(format!(
2742 "a title's size is {}..={} permille of the frame height",
2743 SIZE_RANGE.0, SIZE_RANGE.1
2744 )
2745 .into());
2746 }
2747 if title.keys.len() > MAX_TRANSFORM_KEYS {
2748 return Err(format!("a title holds at most {MAX_TRANSFORM_KEYS} keys").into());
2749 }
2750 for (i, k) in title.keys.iter().enumerate() {
2751 // A NaN fails every range check, so it is refused along with the out-of-range values.
2752 let in_range = (-1.0..=1.0).contains(&k.x)
2753 && (-1.0..=1.0).contains(&k.y)
2754 && (KEY_SCALE_RANGE.0..=KEY_SCALE_RANGE.1).contains(&k.scale)
2755 && (0.0..=1.0).contains(&k.opacity);
2756 if !in_range {
2757 return Err("a title key's x and y are -1..=1, its scale 0.05..=10 and its opacity 0..=1".into());
2758 }
2759 if i > 0 && title.keys[i - 1].at >= k.at {
2760 return Err("a title's keys are in frame order, with no two at one frame".into());
2761 }
2762 }
2763 Ok(())
2764}
2765
2766/// One clip [`Project::clamp_to_walls`] shortened: its lane, its source, and its
2767/// out-point before (`from`) and after (`to`), in source frames.
2768#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2769pub struct WallClamp {
2770 pub lane: Lane,
2771 pub source: usize,
2772 pub from: u32,
2773 pub to: u32,
2774}
2775
2776/// The edit list plus its undo history.
2777#[derive(Clone, Debug)]
2778pub struct Project {
2779 /// Append-only: never popped, never reordered. See the module docs.
2780 sources: Vec<Source>,
2781 /// In display order, which is the order [`Lane::ord`] counts in: the nth
2782 /// lane of a kind here is that kind's `ord` n. Never empty.
2783 lanes: Vec<LaneData>,
2784 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
2785 eq: Vec<EqParams>,
2786 /// The same, for [`Clip::color`].
2787 color: Vec<ColorParams>,
2788 /// The same, for [`Clip::transform`].
2789 transform: Vec<TransformParams>,
2790 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
2791 /// whole lane list, the subtitle palette and the project's own settings,
2792 /// so adding a lane undoes as well and so does picking a resolution. Bounded
2793 /// by [`HISTORY_CAP`]: at the cap the oldest step goes.
2794 history: Vec<Snapshot>,
2795 /// Snapshots `undo` has stepped past; `redo` pops one. Cleared by
2796 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
2797 /// the undone steps came from. Not saved to `.edith`, matching `history`.
2798 redo: Vec<Snapshot>,
2799 /// Every snapshot pushed since the project was made, evicted ones included:
2800 /// [`Project::snapshot`] bumps it on each push. A caller that measures a
2801 /// batch by the history's length cannot, once the cap holds that length at
2802 /// [`HISTORY_CAP`]; this count keeps rising, so a batch's pushes are the
2803 /// difference of two reads. Not saved to `.edith`, and an undo never rolls
2804 /// it back.
2805 pushes: u64,
2806 /// Which state the project is in, as an id no other state of any project
2807 /// has ([`Project::revision`]). Every edit takes a fresh one and every undo
2808 /// or redo puts back the one its step carries, so a caller that saved at one
2809 /// revision knows whether a later undo has walked back to it.
2810 revision: u64,
2811 /// Set by [`Project::begin_batch`]: while it holds, the first snapshot of the
2812 /// batch is the only one kept, so the batch is one undo step however many edits it makes.
2813 batching: bool,
2814 /// Whether the open batch has pushed its one snapshot yet. An undo or redo clears it,
2815 /// since the state it protects is then not the one the batch started from.
2816 batch_snapped: bool,
2817 /// What the newest step pushed took out of the way, so [`Project::settle`]
2818 /// can put it back should that step turn out to have changed nothing. `None`
2819 /// before any step and after an undo or redo.
2820 pending: Option<PendingStep>,
2821 /// Set by [`Project::hold_history`]: while it holds, a snapshot keeps every step
2822 /// (the history may run past [`HISTORY_CAP`]) so a trial batch that is rolled
2823 /// back takes its own steps off again and drops nothing.
2824 hold_cap: bool,
2825 /// Never rolled back by an undo: an id retired by an undone split must not
2826 /// come back and group two clips that were never together.
2827 next_link: u32,
2828 /// The subtitle tracks this timeline shows, in the order they were added.
2829 /// Saved as a *reference* to the file the cues came out of
2830 /// ([`crate::subtitle`]). In the history snapshots since the widened
2831 /// [`Snapshot`]: a placement names a track by index into this list, so a
2832 /// removal that reindexes the placements can only undo together with the
2833 /// palette it removed the row from.
2834 subtitles: Vec<SubtitleTrack>,
2835 /// The cue overrides: `(track, cue, text)`, the track by its position in
2836 /// `subtitles` and the cue by its position in that track. Saved as `cue`
2837 /// lines ([`crate::edith`]) and in every snapshot, so an undo takes a retype
2838 /// back with the words it changed.
2839 cue_edits: Vec<(usize, usize, String)>,
2840 /// The cues added to a track ([`AddedCue`]), in the order they were added.
2841 /// Each sits in its track's cue list at its own start, and a save writes
2842 /// them as `cueadd` lines. In every snapshot, as the overrides are.
2843 cue_adds: Vec<AddedCue>,
2844 /// The title cards and text overlays, in draw order: sorted by start, and
2845 /// overlaps allowed. In every snapshot, as the subtitle palette is.
2846 titles: Vec<Title>,
2847 chapters: Vec<Chapter>,
2848 /// The comment markers, sorted by frame ([`Marker`]). In every snapshot, as the
2849 /// chapters are.
2850 markers: Vec<Marker>,
2851 /// The project's own settings ([`ProjectSettings`]) -- the canvas, the
2852 /// rate, the proxies switches, the encoder seat, the mix rate, the
2853 /// rendition and the limiter. In every snapshot, so each of them undoes
2854 /// like a lane edit: they are the header of the project's own `.edith`
2855 /// file, not this machine's, and a pick a ctrl+z could not take back
2856 /// would be the one setting with no way out.
2857 settings: ProjectSettings,
2858 /// The sequences ([`sequence`]): the active one is the fields above, the rest are parked here.
2859 seq: Seqs,
2860 /// The library's bins (v51), in creation order. In every snapshot.
2861 bins: Vec<Bin>,
2862 /// The next bin id; never rolled back, so an id is never reused.
2863 bin_next: u32,
2864 /// The next sequence id; never rolled back, so an id is never reused.
2865 seq_next: u32,
2866 /// The expanded copy of the active sequence playback reads ([`Project::render_view`]).
2867 flat: FlatCache,
2868}
2869
2870impl Project {
2871 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
2872 /// grouped -- the state of a freshly opened video, where the timeline is the
2873 /// source. `frame_count` of 0 would break the never-empty invariant, so it
2874 /// is clamped to one frame.
2875 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
2876 let clip = Clip {
2877 speed_keys: Vec::new(),
2878 reversed: false,
2879 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
2880 angle: Default::default(),
2881 fade_in: 0,
2882 fade_out: 0,
2883 transition_out: 0,
2884 transition_kind: Default::default(),
2885 visualizer: 0,
2886 viz_paint: 0,
2887 gain_db: 0.0,
2888 gain_keys: Vec::new(),
2889 pan: 0,
2890 pitch: 0,
2891 transform_keys: Vec::new(),
2892 opacity_keys: Vec::new(),
2893 color_keys: Vec::new(),
2894 effects: Vec::new(),
2895 start: 0,
2896 in_frame: 0,
2897 out_frame: frame_count.max(1),
2898 source: 0,
2899 link: Some(0),
2900 eq: None,
2901 color: None,
2902 transform: None,
2903 fit: FitPolicy::default(),
2904 speed: Speed::NORMAL,
2905 };
2906 Self {
2907 // A file is opened on its first audio stream: nothing has picked
2908 // one yet, and every file with audio at all has that one.
2909 sources: vec![Source::new(path, 0)],
2910 lanes: LaneData::two_lanes(vec![clip.clone()], vec![clip]),
2911 eq: Vec::new(),
2912 color: Vec::new(),
2913 transform: Vec::new(),
2914 history: Vec::new(),
2915 redo: Vec::new(),
2916 pushes: 0,
2917 revision: next_revision(),
2918 batching: false,
2919 batch_snapped: false,
2920 pending: None,
2921 hold_cap: false,
2922 next_link: 1,
2923 subtitles: Vec::new(),
2924 cue_edits: Vec::new(),
2925 cue_adds: Vec::new(),
2926 titles: Vec::new(),
2927 chapters: Vec::new(),
2928 markers: Vec::new(),
2929 settings: ProjectSettings::placeholder(),
2930 seq: Seqs::single(),
2931 bins: Vec::new(),
2932 bin_next: 1,
2933 seq_next: 1,
2934 flat: FlatCache::default(),
2935 }
2936 }
2937
2938 /// A project rebuilt from a saved edit list -- the load half of
2939 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
2940 /// an `ord` is a lane's position among the lanes of that kind, exactly as
2941 /// [`Project::lanes`] hands them back. History is *not* saved, so
2942 /// [`Project::undo`] is `false` until the first edit of the new session.
2943 /// This is the one door untrusted parts come in through, so every invariant
2944 /// every other constructor keeps is checked here, by name and in release:
2945 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
2946 /// or a colour) that is not there, a clip whose end overflows, a lane that is
2947 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
2948 /// below.
2949 ///
2950 /// A project whose lanes are all *empty* is not among them: an emptied
2951 /// timeline is a project like any other -- it plays black and silent, it
2952 /// saves, and it loads back. What a project cannot be is laneless, because
2953 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
2954 /// handle indexes into.
2955 pub fn from_parts(
2956 sources: Vec<Source>,
2957 lanes: Vec<(LaneKind, Vec<Clip>)>,
2958 eq: Vec<EqParams>,
2959 color: Vec<ColorParams>,
2960 transform: Vec<TransformParams>,
2961 ) -> crate::Result<Self> {
2962 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
2963 return Err(format!("eq {bad} holds a band that is not a finite number").into());
2964 }
2965 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
2966 return Err(format!("color {bad} holds a value that is not a finite number").into());
2967 }
2968 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
2969 return Err(format!(
2970 "transform {bad} holds a value that is not a finite number in its range"
2971 )
2972 .into());
2973 }
2974 if lanes.is_empty() {
2975 return Err("no lanes at all: that is not a project".into());
2976 }
2977 let lanes: Vec<LaneData> = lanes
2978 .into_iter()
2979 .map(|(kind, clips)| LaneData::new(kind, clips))
2980 .collect();
2981 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
2982 let name = lane.label();
2983 // A subtitle lane carries words and never a picture
2984 // ([`LaneKind::Subtitle`]); a file that puts one there names a
2985 // source on a lane that has nothing to play it with, and every
2986 // media path below would then read a clip off a lane it does not
2987 // know about.
2988 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
2989 return Err(format!(
2990 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
2991 data.clips.len()
2992 )
2993 .into());
2994 }
2995 for c in &data.clips {
2996 // The setters' own rules, which the file loader enforces too: a
2997 // picture has no volume of its own and only a picture is placed
2998 // by keys, and a clip gain outside its range is refused on the way
2999 // back in. A clip that breaks one would save a file that will not
3000 // load.
3001 if data.kind == LaneKind::Video && c.gain_db != 0.0 {
3002 return Err(format!(
3003 "{name} clip at {} has a gain: a picture has no volume of its own",
3004 c.start
3005 )
3006 .into());
3007 }
3008 if data.kind == LaneKind::Audio && !(c.opacity_keys.is_empty() && c.color_keys.is_empty()) {
3009 return Err(format!(
3010 "{name} clip at {} has opacity or colour keys: only a picture is animated by them",
3011 c.start
3012 )
3013 .into());
3014 }
3015 if data.kind == LaneKind::Audio && !c.transform_keys.is_empty() {
3016 return Err(format!(
3017 "{name} clip at {} has placement keys: only a picture is placed by them",
3018 c.start
3019 )
3020 .into());
3021 }
3022 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&c.gain_db) {
3023 return Err(format!(
3024 "{name} clip at {} has a gain of {} dB, outside its range",
3025 c.start, c.gain_db
3026 )
3027 .into());
3028 }
3029 if c.out_frame <= c.in_frame {
3030 return Err(format!(
3031 "{name} clip at {} plays the empty range [{}, {})",
3032 c.start, c.in_frame, c.out_frame
3033 )
3034 .into());
3035 }
3036 if c.source >= sources.len() && !is_sequence_source(c.source) {
3037 return Err(format!(
3038 "{name} clip at {} names source {} of {}",
3039 c.start,
3040 c.source,
3041 sources.len()
3042 )
3043 .into());
3044 }
3045 if c.start.checked_add(c.frames()).is_none() {
3046 return Err(format!(
3047 "{name} clip at {} runs past the last frame there is",
3048 c.start
3049 )
3050 .into());
3051 }
3052 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
3053 return Err(format!(
3054 "{name} clip at {} names eq {} of {}",
3055 c.start,
3056 c.eq.unwrap_or_default(),
3057 eq.len()
3058 )
3059 .into());
3060 }
3061 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
3062 return Err(format!(
3063 "{name} clip at {} names color {} of {}",
3064 c.start,
3065 c.color.unwrap_or_default(),
3066 color.len()
3067 )
3068 .into());
3069 }
3070 if c.transform
3071 .is_some_and(|i| usize::from(i) >= transform.len())
3072 {
3073 return Err(format!(
3074 "{name} clip at {} names transform {} of {}",
3075 c.start,
3076 c.transform.unwrap_or_default(),
3077 transform.len()
3078 )
3079 .into());
3080 }
3081 }
3082 if !sorted_disjoint(&data.clips) {
3083 return Err(format!("the {name} lane is out of order or overlaps itself").into());
3084 }
3085 }
3086 links_are_consistent(&lanes)?;
3087 // The counter sits past every id the file names, on either of a lane's
3088 // lists: a v16 caption may carry the highest link there is, and a
3089 // re-issued id would silently group it with the next placement that
3090 // asks for one -- the loader refusing a save the editor just wrote.
3091 let next_link = lanes
3092 .iter()
3093 .flat_map(|l| {
3094 let clips = l.clips.iter().filter_map(|c| c.link);
3095 let subs = l.subs.iter().filter_map(|s| s.link);
3096 clips.chain(subs)
3097 })
3098 .max()
3099 // Saturating so a crafted file cannot make the counter wrap: at the
3100 // ceiling ids stop being fresh, which loses grouping, not memory.
3101 .map_or(0, |m| m.saturating_add(1));
3102 Ok(Self {
3103 sources: sources
3104 .iter()
3105 .map(|s| Source { fav: s.fav, bin: s.bin, ..Source::new(&s.path, s.audio_stream) })
3106 .collect(),
3107 lanes,
3108 eq,
3109 color,
3110 transform,
3111 history: Vec::new(),
3112 redo: Vec::new(),
3113 pushes: 0,
3114 revision: next_revision(),
3115 batching: false,
3116 batch_snapped: false,
3117 pending: None,
3118 hold_cap: false,
3119 next_link,
3120 subtitles: Vec::new(),
3121 cue_edits: Vec::new(),
3122 cue_adds: Vec::new(),
3123 titles: Vec::new(),
3124 chapters: Vec::new(),
3125 markers: Vec::new(),
3126 settings: ProjectSettings::placeholder(),
3127 seq: Seqs::single(),
3128 bins: Vec::new(),
3129 bin_next: 1,
3130 seq_next: 1,
3131 flat: FlatCache::default(),
3132 })
3133 }
3134
3135 /// The first video lane -- what an export renders and what a single-lane
3136 /// caller still means by "the clips".
3137 pub fn clips(&self) -> &[Clip] {
3138 self.lane(Lane::V1)
3139 }
3140
3141 /// The clips of `lane`, or nothing at all for a lane that is not there.
3142 pub fn lane(&self, lane: Lane) -> &[Clip] {
3143 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
3144 }
3145
3146 /// Shortens every clip whose out-point runs past its source's wall: `picture` is
3147 /// the wall of a video lane's clip and `sound` of an audio lane's, per source (the
3148 /// tables a playback session holds each lane to). Each lane is held to its own
3149 /// wall, as the load check holds it. Returns what was shortened, so a save can say
3150 /// so. Sequence sources and walls of zero are left alone.
3151 pub fn clamp_to_walls(&mut self, picture: &[u32], sound: &[u32]) -> Vec<WallClamp> {
3152 let wall = |kind: LaneKind, source: usize| -> Option<u32> {
3153 let table = if kind == LaneKind::Audio { sound } else { picture };
3154 table.get(source).copied().filter(|&w| w > 0)
3155 };
3156 let mut clamps = Vec::new();
3157 for (lane, data) in handles(&self.lanes).into_iter().zip(self.lanes.iter_mut()) {
3158 for c in data.clips.iter_mut().filter(|c| !is_sequence_source(c.source)) {
3159 let Some(cap) = wall(data.kind, c.source) else { continue };
3160 if c.out_frame > cap {
3161 clamps.push(WallClamp { lane, source: c.source, from: c.out_frame, to: cap });
3162 c.out_frame = cap;
3163 }
3164 }
3165 }
3166 clamps
3167 }
3168
3169 /// Every lane's handle, in display order -- what a walk over "all lanes"
3170 /// iterates, and what a front-end lays out top to bottom.
3171 pub fn lanes(&self) -> Vec<Lane> {
3172 handles(&self.lanes)
3173 }
3174
3175 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
3176 /// for every `ord` below it, and none at or above it.
3177 pub fn lane_count(&self, kind: LaneKind) -> usize {
3178 self.lanes.iter().filter(|l| l.kind == kind).count()
3179 }
3180
3181 /// Appends an empty lane of `kind` and hands back its handle. One undo
3182 /// step, because the lane list is state a front-end shows: an added lane
3183 /// that could not be taken back would be the one edit with no way out.
3184 /// Nothing plays differently until something is placed on it.
3185 ///
3186 /// An empty lane is a lane like any other -- so is a whole project of them
3187 /// ([`Project::from_parts`]); nothing plays until something is placed.
3188 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
3189 self.snapshot();
3190 self.lanes.push(LaneData::new(kind, Vec::new()));
3191 Lane::new(kind, self.lane_count(kind) - 1)
3192 }
3193
3194 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
3195 /// one undo step like it, which restores the lane where it stood.
3196 ///
3197 /// Refused, changing nothing, while the lane holds anything: the refusal
3198 /// names the clips (file and first frame), because a track removal that
3199 /// deleted takes with it would be the one edit nobody sees coming. Refused
3200 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
3201 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
3202 /// kind and *skips* a kind that is not there), so a project without one
3203 /// would swallow half of every file dropped on it, silently.
3204 ///
3205 /// The lanes below it move up one `ord`, so a handle a caller was holding
3206 /// (a selection, an open card) names the lane after it from here on -- the
3207 /// one thing a front-end owes this call.
3208 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
3209 let Some(i) = self.index(lane) else {
3210 return Err(format!("there is no {} to remove", lane.label()).into());
3211 };
3212 // A subtitle lane is not in that rule: nothing lands on one by itself
3213 // -- a project starts without any and one is added when a caption is --
3214 // so the last of them comes off like any other empty track.
3215 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
3216 return Err(format!(
3217 "{} is the only {} track: every import lands on it",
3218 lane.label(),
3219 match lane.kind {
3220 LaneKind::Video => "video",
3221 LaneKind::Audio => "audio",
3222 // Unreachable while the guard above lets the last subtitle
3223 // lane go, and its own word here so the sentence stays true
3224 // if that rule is ever relaxed.
3225 LaneKind::Subtitle => "subtitle",
3226 }
3227 )
3228 .into());
3229 }
3230 if !self.lanes[i].subs.is_empty() {
3231 // Three names and a count, exactly as the clips below get: the way
3232 // out of the refusal is the drag, so the words say so.
3233 let named: Vec<String> = self.lanes[i]
3234 .subs
3235 .iter()
3236 .take(3)
3237 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
3238 .collect();
3239 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
3240 0 => String::new(),
3241 n => format!(" and {n} more"),
3242 };
3243 return Err(format!(
3244 "{} still holds {}{rest}: delete those captions (or drag them to \
3245 another track) first",
3246 lane.label(),
3247 named.join(", ")
3248 )
3249 .into());
3250 }
3251 let clips = &self.lanes[i].clips;
3252 if !clips.is_empty() {
3253 // Three names and a count: a lane can hold forty clips and a
3254 // refusal nobody reads to the end says nothing at all.
3255 let named: Vec<String> = clips
3256 .iter()
3257 .take(3)
3258 .map(|c| {
3259 let name = self.sources.get(c.source).map_or_else(
3260 || format!("source {}", c.source),
3261 |s| s.path.display().to_string(),
3262 );
3263 format!("{name} at frame {}", c.start)
3264 })
3265 .collect();
3266 let rest = match clips.len().saturating_sub(named.len()) {
3267 0 => String::new(),
3268 n => format!(" and {n} more"),
3269 };
3270 return Err(format!(
3271 "{} still holds {}{rest}: delete those clips (or drag them to \
3272 another track) first",
3273 lane.label(),
3274 named.join(", ")
3275 )
3276 .into());
3277 }
3278 self.snapshot();
3279 self.lanes.remove(i);
3280 Ok(())
3281 }
3282
3283 /// Moves `lane` to display position `to` -- an index into
3284 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
3285 /// the handle it answers to from now on. `None`, changing nothing and
3286 /// snapshotting nothing, for a lane that is not there, a position that is
3287 /// not, and a lane already standing in it.
3288 ///
3289 /// The whole track travels: its clips, its gain, its kind. Nothing is
3290 /// remapped, so no take changes lane and no group is broken -- this is the
3291 /// *order* of the lanes and nothing else, which is why one call is one undo
3292 /// step like an add or a removal.
3293 ///
3294 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
3295 /// last video lane covering a frame, so moving one video lane past another
3296 /// changes which picture wins, in the preview and in an export alike. The
3297 /// audio lanes are summed and their sum does not care about order, so an
3298 /// audio track moved among the video ones is a rearrangement of the screen
3299 /// alone.
3300 ///
3301 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
3302 /// position among the lanes of that kind), so a lane that crosses one of
3303 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
3304 /// `V1`, clips and all -- while one that crosses only lanes of the other
3305 /// kind keeps its name. That is the returned handle: unchanged means every
3306 /// handle a caller holds still names the track it named before.
3307 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
3308 let i = self.index(lane)?;
3309 if to >= self.lanes.len() || to == i {
3310 return None;
3311 }
3312 self.snapshot();
3313 let data = self.lanes.remove(i);
3314 self.lanes.insert(to, data);
3315 Some(handles(&self.lanes)[to])
3316 }
3317
3318 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
3319 /// not there. The one place a handle becomes a position.
3320 fn index(&self, lane: Lane) -> Option<usize> {
3321 self.lanes
3322 .iter()
3323 .enumerate()
3324 .filter(|(_, l)| l.kind == lane.kind)
3325 .map(|(i, _)| i)
3326 .nth(lane.ord)
3327 }
3328
3329 /// For an export of `range` only: drops the clips that lie wholly outside it and read a file
3330 /// `present` says is not there, so a range that never touches a missing source can be written
3331 /// without opening it. Nothing is dropped when that would shorten the timeline below what the
3332 /// range needs (the length of the file would change). A snapshot's edit, never the project's.
3333 pub fn drop_offline_outside(&mut self, range: (u32, u32), present: impl Fn(&Path) -> bool) {
3334 let gone: Vec<bool> = self.sources.iter().map(|s| !present(&s.path)).collect();
3335 if !gone.iter().any(|g| *g) {
3336 return;
3337 }
3338 let keep_len = self.timeline_frames().min(range.1);
3339 let saved: Vec<Vec<Clip>> = self.lanes.iter().map(|l| l.clips.clone()).collect();
3340 for lane in self.lanes.iter_mut().filter(|l| l.kind != LaneKind::Subtitle) {
3341 lane.clips.retain(|c| {
3342 let outside = c.end() <= range.0 || c.start >= range.1;
3343 !(outside && gone.get(c.source).copied().unwrap_or(false))
3344 });
3345 }
3346 if self.timeline_frames() < keep_len {
3347 for (lane, clips) in self.lanes.iter_mut().zip(saved) {
3348 lane.clips = clips;
3349 }
3350 }
3351 }
3352
3353 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
3354 let i = self.index(lane)?;
3355 Some(&mut self.lanes[i].clips)
3356 }
3357
3358 /// The files the clips index into, in import order; index 0 is the file the
3359 /// project was opened with.
3360 pub fn sources(&self) -> &[Source] {
3361 &self.sources
3362 }
3363
3364 /// Points source `idx` at `path`, a file the caller has already checked is
3365 /// the same material. No clip changes; a source's index is its identity.
3366 /// One undo step, which puts the old path back ([`Snapshot::sources`]); a
3367 /// relink to the path the source already has is no change and no step.
3368 pub fn relink_source(&mut self, idx: usize, path: &Path) -> crate::Result<()> {
3369 let Some(source) = self.sources.get(idx) else {
3370 return Err(format!("there is no source {idx}").into());
3371 };
3372 let to = canonical(path);
3373 if source.path == to {
3374 return Ok(());
3375 }
3376 self.snapshot();
3377 self.sources[idx].path = to;
3378 Ok(())
3379 }
3380
3381 /// Points several sources at new files in one undo step ([`Self::relink_source`] for each,
3382 /// unchecked: the caller has copies of the same material). Sources already there and indexes
3383 /// that name nothing are left alone; no step when nothing moves. Returns how many moved.
3384 pub fn relink_sources(&mut self, pairs: &[(usize, PathBuf)]) -> usize {
3385 let moves: Vec<(usize, PathBuf)> = pairs
3386 .iter()
3387 .filter(|(i, to)| self.sources.get(*i).is_some_and(|s| s.path != canonical(to)))
3388 .map(|(i, to)| (*i, canonical(to)))
3389 .collect();
3390 if moves.is_empty() {
3391 return 0;
3392 }
3393 self.snapshot();
3394 for (i, to) in &moves {
3395 self.sources[*i].path = to.clone();
3396 }
3397 moves.len()
3398 }
3399
3400 /// Takes `other`'s timeline over as one undo step: what this project was
3401 /// before the call is one step back, and it is what a recovery does with an
3402 /// autosave once the saved project is open. The lanes, the subtitle palette,
3403 /// the cue edits and adds, the titles, the chapters, the markers, the settings
3404 /// and the sources all come from `other`. Its clip effect tables (equalizer, colour, transform) are
3405 /// appended to this project's own and its clips re-pointed at them, so the
3406 /// indexes a step in the history holds stay valid; the link counter is raised
3407 /// past `other`'s links, so a new split never reuses one. `false`, with
3408 /// nothing changed, when the appended tables would not fit a clip's `u16`.
3409 pub fn adopt_as_step(&mut self, other: &Project) -> bool {
3410 let fits = |have: usize, add: usize| have + add <= usize::from(u16::MAX);
3411 if !fits(self.eq.len(), other.eq.len())
3412 || !fits(self.color.len(), other.color.len())
3413 || !fits(self.transform.len(), other.transform.len())
3414 {
3415 return false;
3416 }
3417 let (eq_at, color_at, transform_at) = (self.eq.len(), self.color.len(), self.transform.len());
3418 // A `u16` index shifted past the appended table: the fit check above keeps it in range.
3419 let shift = |i: u16, by: usize| (usize::from(i) + by) as u16;
3420 let mut lanes = other.lanes.clone();
3421 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
3422 c.eq = c.eq.map(|i| shift(i, eq_at));
3423 c.color = c.color.map(|i| shift(i, color_at));
3424 c.transform = c.transform.map(|i| shift(i, transform_at));
3425 }
3426 self.snapshot();
3427 self.eq.extend(other.eq.iter().cloned());
3428 self.color.extend(other.color.iter().cloned());
3429 self.transform.extend(other.transform.iter().cloned());
3430 let mut parked = other.seq.parked.clone();
3431 for c in parked.iter_mut().flat_map(|(_, d)| d.lanes.iter_mut()).flat_map(|l| &mut l.clips) {
3432 c.eq = c.eq.map(|i| shift(i, eq_at));
3433 c.color = c.color.map(|i| shift(i, color_at));
3434 c.transform = c.transform.map(|i| shift(i, transform_at));
3435 }
3436 self.seq = Seqs { active: other.seq.active, names: other.seq.names.clone(), parked, mcam: other.seq.mcam.clone(), nested: Vec::new() };
3437 self.seq_next = self.seq_next.max(other.seq_next);
3438 self.flat.clear();
3439 self.lanes = lanes;
3440 self.subtitles = other.subtitles.clone();
3441 self.cue_edits = other.cue_edits.clone();
3442 self.cue_adds = other.cue_adds.clone();
3443 self.titles = other.titles.clone();
3444 // The active sequence's chapters and markers are the other timeline's too: left
3445 // out, a recovery drops them and undo cannot bring them back.
3446 self.chapters = other.chapters.clone();
3447 self.markers = other.markers.clone();
3448 self.settings = other.settings.clone();
3449 self.sources = other.sources.clone();
3450 self.bins = other.bins.clone();
3451 self.bin_next = self.bin_next.max(other.bin_next);
3452 self.next_link = self.next_link.max(other.next_link);
3453 true
3454 }
3455
3456 /// The same list in the `(path, stream)` shape the audio engine indexes
3457 /// into -- [`crate::AudioSession::open_multi_streams`] and
3458 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
3459 /// was placed with is the stream that plays *and* the stream that exports.
3460 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
3461 self.sources
3462 .iter()
3463 .map(|s| (s.path.clone(), s.audio_stream))
3464 .collect()
3465 }
3466
3467 /// Index for `path` played on `audio_stream`, appending it if it is new.
3468 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
3469 /// by two paths imports once and two streams of one file are two sources.
3470 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
3471 /// no history: a source entry alone changes nothing playable.
3472 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
3473 let source = Source::new(path, audio_stream);
3474 match self.sources.iter().position(|s| *s == source) {
3475 Some(idx) => idx,
3476 None => {
3477 self.sources.push(source);
3478 self.sources.len() - 1
3479 }
3480 }
3481 }
3482
3483 /// Append a whole-file clip of `source` to the end of every *media* lane,
3484 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
3485 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
3486 /// come in through [`Project::add_subtitles`], which is the palette.
3487 ///
3488 /// One history snapshot, so an import is one undo step, and undoing it
3489 /// leaves the (harmless) source entry behind, because indexes are forever.
3490 /// Refused for an unknown source index.
3491 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
3492 if source >= self.sources.len() {
3493 return false;
3494 }
3495 self.snapshot();
3496 let start = self.timeline_frames();
3497 let clip = Clip {
3498 speed_keys: Vec::new(),
3499 reversed: false,
3500 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
3501 angle: Default::default(),
3502 fade_in: 0,
3503 fade_out: 0,
3504 transition_out: 0,
3505 transition_kind: Default::default(),
3506 visualizer: 0,
3507 viz_paint: 0,
3508 gain_db: 0.0,
3509 gain_keys: Vec::new(),
3510 pan: 0,
3511 pitch: 0,
3512 transform_keys: Vec::new(),
3513 opacity_keys: Vec::new(),
3514 color_keys: Vec::new(),
3515 effects: Vec::new(),
3516 start,
3517 in_frame: 0,
3518 out_frame: frame_count.max(1),
3519 source,
3520 link: Some(self.new_link()),
3521 eq: None,
3522 color: None,
3523 transform: None,
3524 fit: FitPolicy::default(),
3525 speed: Speed::NORMAL,
3526 };
3527 for data in self
3528 .lanes
3529 .iter_mut()
3530 .filter(|l| l.kind != LaneKind::Subtitle)
3531 {
3532 data.clips.push(clip.clone());
3533 }
3534 true
3535 }
3536
3537 /// Drops a source entry -- the file a library row *is* -- and renumbers
3538 /// every clip that indexed past it, which is why this is more than a
3539 /// `Vec::remove`.
3540 ///
3541 /// Refused, changing nothing, while any clip still plays from it: the
3542 /// refusal names the lanes and how many clips each holds, so a caller can
3543 /// say what has to be deleted first. The *last* entry goes like any other
3544 /// -- a project may name no file at all, which is an empty library over an
3545 /// empty timeline (nothing can play, since a clip would have refused the
3546 /// removal). What a front-end does with that is its own decision: `edith`'s
3547 /// window goes back to the empty state it launches in, and
3548 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
3549 /// refuses to write a project that names nothing, because no such file
3550 /// could be opened again.
3551 ///
3552 /// Every index past `idx` moves down by one, so a caller holding a *raw*
3553 /// source index of its own -- a clipboard, which is the one thing outside
3554 /// this type that does -- has to fix it up or drop it, or a paste plays a
3555 /// different file. [`PlaybackSession::remove_source`] hands back the index
3556 /// that went for exactly that.
3557 ///
3558 /// corner-cut: this retires the undo stack. `history` holds the lanes, the
3559 /// subtitle palette and the project's own settings -- no source list -- so a
3560 /// snapshot older than the removal can name the very source being removed
3561 /// (delete a file's clips, then remove the file) and restoring it would
3562 /// point a clip at an entry that is gone. The upgrade path is snapshotting
3563 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
3564 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
3565 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
3566 /// exists) currently rules out.
3567 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
3568 let Some(source) = self.sources.get(idx) else {
3569 return Err(format!("there is no source {idx} to remove").into());
3570 };
3571 let name = source.path.display().to_string();
3572 let used: Vec<String> = handles(&self.lanes)
3573 .into_iter()
3574 .zip(&self.lanes)
3575 .filter_map(|(lane, data)| {
3576 match data.clips.iter().filter(|c| c.source == idx).count() {
3577 0 => None,
3578 1 => Some(format!("{} (1 clip)", lane.label())),
3579 n => Some(format!("{} ({n} clips)", lane.label())),
3580 }
3581 })
3582 .collect();
3583 if !used.is_empty() {
3584 return Err(format!("{name} still plays on {}", used.join(", ")).into());
3585 }
3586 if let Some((id, _)) = self
3587 .seq
3588 .parked
3589 .iter()
3590 .find(|(_, d)| d.lanes.iter().any(|l| l.clips.iter().any(|c| c.source == idx)))
3591 {
3592 let who = self.sequence_name(*id).unwrap_or("another sequence").to_string();
3593 return Err(format!("{name} still plays in the sequence \"{who}\"").into());
3594 }
3595 self.sources.remove(idx);
3596 let all = self
3597 .lanes
3598 .iter_mut()
3599 .chain(self.seq.parked.iter_mut().flat_map(|(_, d)| d.lanes.iter_mut()));
3600 for c in all.flat_map(|l| &mut l.clips) {
3601 if c.source > idx && !is_sequence_source(c.source) {
3602 c.source -= 1;
3603 }
3604 }
3605 self.flat.clear();
3606 // The redo steps renumber nothing and name the old indexes: they go with the history.
3607 self.history.clear();
3608 self.redo.clear();
3609 Ok(())
3610 }
3611
3612 /// Drops the **last** source, if nothing names it, and leaves the undo
3613 /// history exactly as it was. The narrow door behind a rollback: a source
3614 /// imported by a batch that then failed is the newest entry and nothing on
3615 /// the timeline plays it, so taking it back out renumbers nothing and
3616 /// invalidates no step.
3617 ///
3618 /// Refused, with the source left in place, when it is not the last entry (a
3619 /// removal below it would renumber every index above, which is what
3620 /// [`remove_source`](Project::remove_source) does and why that one clears
3621 /// history), or when a clip plays it or an undo or redo step does. The steps
3622 /// that held the entry past the new end are cut to the list that is left, so
3623 /// no restore brings it back.
3624 pub fn remove_unused_source(&mut self, idx: usize) -> crate::Result<()> {
3625 if idx >= self.sources.len() {
3626 return Err(format!("there is no source {idx} to remove").into());
3627 }
3628 let name = self.sources[idx].path.display().to_string();
3629 if idx + 1 != self.sources.len() {
3630 return Err(format!(
3631 "{name} is not the last source, so removing it would renumber the sources after it"
3632 )
3633 .into());
3634 }
3635 let named = |lanes: &[LaneData]| {
3636 lanes.iter().any(|l| l.clips.iter().any(|c| c.source == idx))
3637 };
3638 let parked = |seq: &Seqs| seq.parked.iter().any(|(_, d)| named(&d.lanes));
3639 if named(&self.lanes)
3640 || parked(&self.seq)
3641 || self.history.iter().any(|s| named(&s.lanes) || parked(&s.seq))
3642 || self.redo.iter().any(|s| named(&s.lanes) || parked(&s.seq))
3643 {
3644 return Err(format!("{name} is still played by a clip or an undo step").into());
3645 }
3646 self.sources.pop();
3647 // The steps that hold the entry past the new end (none of them names it) are cut to the
3648 // list that is left, so an undo does not bring the removed entry back.
3649 for step in self.history.iter_mut().chain(self.redo.iter_mut()) {
3650 step.sources.truncate(idx);
3651 }
3652 Ok(())
3653 }
3654
3655 /// The sources, equalizer and colour tables, and transform table a save
3656 /// writes, with the clips reindexed onto their pruned copies. Every
3657 /// imported source is kept, in session order, so a source's index in the
3658 /// file is the index it had in the session and stays put across save and
3659 /// open. Equalizer, colour and transform entries nothing names are still
3660 /// pruned: an undone `set_eq`/`set_color` leaves a setting nothing plays
3661 /// behind, and those indexes are re-assigned by first use -- lane by lane,
3662 /// in display order -- so the same project always emits the same bytes.
3663 ///
3664 /// Every lane comes out, in display order and with its kind: that is what a
3665 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
3666 /// takes back.
3667 ///
3668 /// The equalizer and colour tables are pruned the same way and for the same
3669 /// reason: an undone [`set_eq`](Project::set_eq) or
3670 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
3671 /// and this is the one moment they can go -- the indexes that survive it are
3672 /// only the ones a clip names.
3673 ///
3674 /// Keeping every source (rather than only the ones a clip names) means an
3675 /// emptied timeline still has the file it is scaffolded from on reopen --
3676 /// the frame rate is written nowhere else -- and a source a clip no longer
3677 /// plays stays a library entry at the index a reload expects. Source 0 is
3678 /// whatever was imported first, which may be a still or a song;
3679 /// `PlaybackSession::open_project` picks its rate and its audio reference by
3680 /// what a source *is*, never by where it sits.
3681 pub fn without_orphan_sources(&self) -> Parts {
3682 // Every source comes out, in session order: an import is not an undo
3683 // step, so a source nothing plays is a deliberate library entry, and
3684 // its index is the one a reload must find it at again.
3685 let sources = self.sources.clone();
3686 let mut moved_eq = vec![None; self.eq.len()];
3687 let mut eq = Vec::new();
3688 let mut moved_color = vec![None; self.color.len()];
3689 let mut color = Vec::new();
3690 let mut moved_transform = vec![None; self.transform.len()];
3691 let mut transform = Vec::new();
3692 let mut lanes = self.lanes.clone();
3693 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
3694 if let Some(old) = c.eq.map(usize::from) {
3695 c.eq = Some(match moved_eq[old] {
3696 Some(new) => new,
3697 None => {
3698 eq.push(self.eq[old].clone());
3699 let new = (eq.len() - 1) as u16;
3700 moved_eq[old] = Some(new);
3701 new
3702 }
3703 });
3704 }
3705 if let Some(old) = c.color.map(usize::from) {
3706 c.color = Some(match moved_color[old] {
3707 Some(new) => new,
3708 None => {
3709 color.push(self.color[old]);
3710 let new = (color.len() - 1) as u16;
3711 moved_color[old] = Some(new);
3712 new
3713 }
3714 });
3715 }
3716 if let Some(old) = c.transform.map(usize::from) {
3717 c.transform = Some(match moved_transform[old] {
3718 Some(new) => new,
3719 None => {
3720 transform.push(self.transform[old]);
3721 let new = (transform.len() - 1) as u16;
3722 moved_transform[old] = Some(new);
3723 new
3724 }
3725 });
3726 }
3727 }
3728 (
3729 sources,
3730 // Every lane, subtitle ones included: they hold no [`Clip`], so what
3731 // comes out for one is an empty list, and its *place* in the display
3732 // order is what a save writes it for. What is on it travels beside
3733 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
3734 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
3735 eq,
3736 color,
3737 transform,
3738 )
3739 }
3740
3741 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
3742 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
3743 /// track moves by it, which is what makes it a different control from a
3744 /// clip's equalizer (one frequency range of one take) and from the master
3745 /// volume (what this machine monitors at, which no file carries).
3746 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
3747 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
3748 }
3749
3750 /// The first auto-duck on `lane`, if it has one: the one
3751 /// [`lane_duck_list`](Project::lane_duck_list) starts with. `None` for a lane
3752 /// without one and for a lane that is not there. A lane with several ducks
3753 /// has them all in `lane_duck_list`; this names only the first.
3754 pub fn lane_duck(&self, lane: Lane) -> Option<Duck> {
3755 self.lane_duck_list(lane).first().copied()
3756 }
3757
3758 /// Every auto-duck on `lane`, one per key lane, in the order they were set.
3759 /// Empty for a lane without one and for a lane that is not there.
3760 pub fn lane_duck_list(&self, lane: Lane) -> Vec<Duck> {
3761 self.index(lane)
3762 .map_or_else(Vec::new, |i| self.lanes[i].ducks.clone())
3763 }
3764
3765 /// Sets an auto-duck on an audio lane: while the key lane `duck.under` is
3766 /// loud, this lane drops by `depth_db` ([`crate::duck`]). A lane can be
3767 /// ducked under several keys at once: a duck under a key this lane already
3768 /// has replaces that one, and a duck under a new key is added beside the
3769 /// rest. `None` clears every duck on the lane. One undo step, like a volume.
3770 ///
3771 /// `false`, and no history, for a lane that is not an audio lane or is not
3772 /// there, for a key that is not another audio lane of this project (`under`
3773 /// is the key's [`Lane::ord`]), for a number that is not finite, and for a
3774 /// duck already set exactly so. The numbers are clamped as the duck's own
3775 /// ranges clamp them.
3776 pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<Duck>) -> bool {
3777 let Some(i) = self.index(lane) else {
3778 return false;
3779 };
3780 if lane.kind != LaneKind::Audio {
3781 return false;
3782 }
3783 let next = match duck {
3784 Some(d) => {
3785 let Some(d) = d.clamped() else {
3786 return false;
3787 };
3788 let key = Lane::new(LaneKind::Audio, d.under);
3789 if key == lane || self.index(key).is_none() {
3790 return false;
3791 }
3792 let mut ducks = self.lanes[i].ducks.clone();
3793 match ducks.iter_mut().find(|x| x.under == d.under) {
3794 Some(slot) if *slot == d => return false,
3795 Some(slot) => *slot = d,
3796 None => ducks.push(d),
3797 }
3798 ducks
3799 }
3800 None => {
3801 if self.lanes[i].ducks.is_empty() {
3802 return false;
3803 }
3804 Vec::new()
3805 }
3806 };
3807 self.snapshot();
3808 self.lanes[i].ducks = next;
3809 true
3810 }
3811
3812 /// Removes the duck `lane` has under the key `under` (the key's
3813 /// [`Lane::ord`]), leaving its other ducks. One undo step. `false`, and no
3814 /// history, for a lane with no duck under that key.
3815 pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool {
3816 let Some(i) = self.index(lane) else {
3817 return false;
3818 };
3819 if !self.lanes[i].ducks.iter().any(|d| d.under == under) {
3820 return false;
3821 }
3822 self.snapshot();
3823 self.lanes[i].ducks.retain(|d| d.under != under);
3824 true
3825 }
3826
3827 /// The voice processors of `lane` ([`crate::voice`]): all off, and the
3828 /// default, for a lane that has none, is not an audio lane or is not there.
3829 pub fn lane_voice(&self, lane: Lane) -> VoiceFx {
3830 self.index(lane)
3831 .map_or_else(VoiceFx::default, |i| self.lanes[i].voice.clone())
3832 }
3833
3834 /// Sets the voice processors of an audio lane. One undo step. The numbers are
3835 /// clamped to their ranges. `false`, and no history, for a lane that is not an
3836 /// audio lane or is not there, for a number that is not finite, for a noise
3837 /// reduction switched on without a profile to subtract, and for a setting the
3838 /// lane already has.
3839 pub fn set_lane_voice(&mut self, lane: Lane, voice: VoiceFx) -> bool {
3840 let Some(i) = self.index(lane) else {
3841 return false;
3842 };
3843 if lane.kind != LaneKind::Audio {
3844 return false;
3845 }
3846 let Some(voice) = voice.clamped() else {
3847 return false;
3848 };
3849 if voice.nr.on && voice.nr.profile.is_empty() {
3850 return false;
3851 }
3852 if self.lanes[i].voice == voice {
3853 return false;
3854 }
3855 self.snapshot();
3856 self.lanes[i].voice = voice;
3857 true
3858 }
3859
3860 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
3861 /// One undo step like every other edit -- it is in the lane list, so an
3862 /// undo restores it with the rest. `false`, and no history, for a lane that
3863 /// is not there, for a value that is not finite, and for one already set.
3864 ///
3865 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
3866 /// a value nobody reads: words have no loudness, so a slider that appeared
3867 /// to move one would be a control with no effect. (A video lane's gain is
3868 /// meaningless in the same way but is kept settable: it is the pair `A1`
3869 /// carries for a take, and mixing reads it off the audio lane alone.)
3870 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
3871 let Some(i) = self.index(lane) else {
3872 return false;
3873 };
3874 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
3875 return false;
3876 }
3877 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
3878 if self.lanes[i].gain_db == db {
3879 return false;
3880 }
3881 self.snapshot();
3882 self.lanes[i].gain_db = db;
3883 true
3884 }
3885
3886 /// The pan of an audio lane ([`Self::set_lane_pan`]), `0.0` for the middle and for a lane
3887 /// that is not there.
3888 pub fn lane_pan(&self, lane: Lane) -> f32 {
3889 self.index(lane).map_or(0.0, |i| self.lanes[i].pan)
3890 }
3891
3892 /// Give an audio lane this pan, clamped to `-1.0..=1.0`. One undo step; `false` for a lane
3893 /// that is not there or not audio, a value that is not finite, or one already set.
3894 pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool {
3895 let Some(i) = self.index(lane) else {
3896 return false;
3897 };
3898 if !pan.is_finite() || lane.kind != LaneKind::Audio {
3899 return false;
3900 }
3901 let pan = pan.clamp(-1.0, 1.0);
3902 if self.lanes[i].pan == pan {
3903 return false;
3904 }
3905 self.snapshot();
3906 self.lanes[i].pan = pan;
3907 true
3908 }
3909
3910 /// Whether `lane` is hidden: a video lane left out of the picture, or a
3911 /// subtitle lane whose words are left off the screen and the export. `false`
3912 /// for a lane that is not there.
3913 pub fn lane_hidden(&self, lane: Lane) -> bool {
3914 self.index(lane).is_some_and(|i| self.lanes[i].hidden)
3915 }
3916
3917 /// Whether `lane` is muted: an audio lane silenced in the mix
3918 /// ([`audio_gains`](Project::audio_gains) reads it as 0). `false` for a lane
3919 /// that is not there.
3920 pub fn lane_muted(&self, lane: Lane) -> bool {
3921 self.index(lane).is_some_and(|i| self.lanes[i].muted)
3922 }
3923
3924 /// Whether `lane` is locked. The engine does not look at it: an edit to a
3925 /// locked lane is refused by the front-end, which is where the toast that
3926 /// offers Unlock lives.
3927 pub fn lane_locked(&self, lane: Lane) -> bool {
3928 self.index(lane).is_some_and(|i| self.lanes[i].locked)
3929 }
3930
3931 /// The name the user gave `lane`, `None` when it has none (or is not there).
3932 pub fn lane_name(&self, lane: Lane) -> Option<&str> {
3933 self.index(lane).map(|i| self.lanes[i].name.as_str()).filter(|n| !n.is_empty())
3934 }
3935
3936 /// What a header shows for `lane`: its name, else its address (`V1`).
3937 pub fn lane_title(&self, lane: Lane) -> String {
3938 self.lane_name(lane).map_or_else(|| lane.label(), str::to_string)
3939 }
3940
3941 /// Names `lane`; an empty (or all-blank) name clears it. One undo step.
3942 /// `Ok(false)`, and no history, for a lane that is not there or no change.
3943 /// Refused: more than [`MAX_LANE_NAME_CHARS`] characters, control characters.
3944 pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> {
3945 let name = name.trim();
3946 if name.chars().count() > MAX_LANE_NAME_CHARS {
3947 return Err(format!("a lane name is at most {MAX_LANE_NAME_CHARS} characters"));
3948 }
3949 if name.chars().any(char::is_control) {
3950 return Err("a lane name holds no control characters".into());
3951 }
3952 let Some(i) = self.index(lane) else {
3953 return Ok(false);
3954 };
3955 if self.lanes[i].name == name {
3956 return Ok(false);
3957 }
3958 self.snapshot();
3959 self.lanes[i].name = name.to_string();
3960 Ok(true)
3961 }
3962
3963 /// Every lane's name (empty for none), in display order and in step with
3964 /// [`lane_gains`](Project::lane_gains) -- what a save writes.
3965 pub fn lane_names(&self) -> Vec<String> {
3966 self.lanes.iter().map(|l| l.name.clone()).collect()
3967 }
3968
3969 /// The names a *load* puts back, with no undo step (as
3970 /// [`with_voices`](Project::with_voices)).
3971 pub fn with_lane_names(mut self, names: &[String]) -> Self {
3972 for (data, name) in self.lanes.iter_mut().zip(names) {
3973 data.name = name.clone();
3974 }
3975 self
3976 }
3977
3978 /// Hides or shows a lane. One undo step. `false`, and no history, for a lane
3979 /// that is not there, for one already in that state, and for an audio lane:
3980 /// there is no picture or caption on one to leave out (the mute is its
3981 /// switch), so a hide on it would be a control with no effect.
3982 pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool {
3983 self.set_flag(lane, hidden, |k| k != LaneKind::Audio, |l| &mut l.hidden)
3984 }
3985
3986 /// Mutes or unmutes an audio lane. One undo step. `false`, and no history,
3987 /// for a lane that is not there, for one already in that state, and for any
3988 /// lane but an audio one -- the video lane's sound is never mixed.
3989 pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool {
3990 self.set_flag(lane, muted, |k| k == LaneKind::Audio, |l| &mut l.muted)
3991 }
3992
3993 /// Locks or unlocks a lane. One undo step. `false`, and no history, for a
3994 /// lane that is not there and for one already in that state. The engine
3995 /// accepts edits on a locked lane all the same; see
3996 /// [`lane_locked`](Project::lane_locked).
3997 pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool {
3998 self.set_flag(lane, locked, |_| true, |l| &mut l.locked)
3999 }
4000
4001 /// The one door the three switches go through: refuse what the lane kind
4002 /// cannot have, refuse a no-op, otherwise snapshot and set.
4003 fn set_flag(
4004 &mut self,
4005 lane: Lane,
4006 on: bool,
4007 allowed: fn(LaneKind) -> bool,
4008 field: fn(&mut LaneData) -> &mut bool,
4009 ) -> bool {
4010 let Some(i) = self.index(lane) else {
4011 return false;
4012 };
4013 if !allowed(lane.kind) || *field(&mut self.lanes[i]) == on {
4014 return false;
4015 }
4016 self.snapshot();
4017 *field(&mut self.lanes[i]) = on;
4018 true
4019 }
4020
4021 /// Every lane's switches, in display order and in step with
4022 /// [`lane_gains`](Project::lane_gains) -- what a save writes beside them.
4023 pub fn lane_flags(&self) -> Vec<LaneFlags> {
4024 self.lanes
4025 .iter()
4026 .map(|l| LaneFlags {
4027 hidden: l.hidden,
4028 muted: l.muted,
4029 locked: l.locked,
4030 pan: l.pan,
4031 })
4032 .collect()
4033 }
4034
4035 /// The switches a *load* puts back, beside [`with_mix`](Project::with_mix)
4036 /// and for the same reason: no undo step. A short list leaves the rest
4037 /// clear, which is what a file from before the switches means.
4038 pub fn with_lane_flags(mut self, flags: &[LaneFlags]) -> Self {
4039 for (data, f) in self.lanes.iter_mut().zip(flags) {
4040 data.hidden = f.hidden;
4041 data.muted = f.muted;
4042 data.locked = f.locked;
4043 data.pan = f.pan;
4044 }
4045 self
4046 }
4047
4048 /// Every lane's volume in dB, in display order -- what a save writes,
4049 /// beside the lanes [`Project::without_orphan_sources`] hands back.
4050 ///
4051 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
4052 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
4053 /// one): a save zips the two lists, so a lane that is in one and not the
4054 /// other would hand every track below it the volume of the track above.
4055 pub fn lane_gains(&self) -> Vec<f32> {
4056 self.lanes.iter().map(|l| l.gain_db).collect()
4057 }
4058
4059 /// Every lane's ducks, in step with [`lane_gains`](Project::lane_gains) --
4060 /// what a save writes beside them. Empty for every lane but an audio lane
4061 /// with a duck.
4062 pub fn lane_ducks(&self) -> Vec<Vec<Duck>> {
4063 self.lanes.iter().map(|l| l.ducks.clone()).collect()
4064 }
4065
4066 /// Every lane's voice processors, in step with [`lane_gains`](Project::lane_gains)
4067 /// -- what a save writes beside them.
4068 pub fn lane_voices(&self) -> Vec<VoiceFx> {
4069 self.lanes.iter().map(|l| l.voice.clone()).collect()
4070 }
4071
4072 /// What is placed on every lane, in display order and in step with
4073 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
4074 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
4075 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
4076 ///
4077 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
4078 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
4079 /// clip's source there is no orphan to prune and no index to move.
4080 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
4081 self.lanes.iter().map(|l| l.subs.clone()).collect()
4082 }
4083
4084 /// The placements a *load* puts back, one list per lane in display order --
4085 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
4086 /// same reason. Called *after*
4087 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
4088 /// names.
4089 ///
4090 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
4091 /// like it, by name and in release, because it is the same untrusted file:
4092 /// a placement on a lane that is not a subtitle lane, an empty span or an
4093 /// empty window, a track the palette does not have, a span running past the
4094 /// last frame there is, and a lane that is out of order or overlaps itself
4095 /// ([`place_sub`] refuses every one of those on the live timeline).
4096 ///
4097 /// [`place_sub`]: Project::place_sub
4098 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
4099 let names = handles(&self.lanes);
4100 let palette = self.subtitles.len();
4101 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
4102 let name = lane.label();
4103 if list.is_empty() {
4104 continue;
4105 }
4106 if data.kind != LaneKind::Subtitle {
4107 return Err(format!(
4108 "{name} is not a subtitle track and holds {} caption(s): words go on a \
4109 subtitle track",
4110 list.len()
4111 )
4112 .into());
4113 }
4114 for s in &list {
4115 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
4116 return Err(format!(
4117 "{name} caption at {} is empty: {} frames of [{}, {})",
4118 s.start, s.frames, s.in_us, s.out_us
4119 )
4120 .into());
4121 }
4122 // The width of that window, which the check above cannot see:
4123 // [`edith`](crate::edith) asks the same question at the parse
4124 // and this repeats it, because `with_subs` is the door a
4125 // hand-built `Project` comes through and a caller is not more
4126 // trustworthy than a file.
4127 if s.out_us - s.in_us > MAX_WINDOW_US {
4128 return Err(format!(
4129 "{name} caption at {} is a {}us window, past the {}us a caption can hold",
4130 s.start,
4131 s.out_us - s.in_us,
4132 MAX_WINDOW_US
4133 )
4134 .into());
4135 }
4136 if s.track >= palette {
4137 return Err(format!(
4138 "{name} caption at {} names subtitle track {} of {palette}",
4139 s.start, s.track
4140 )
4141 .into());
4142 }
4143 if s.start.checked_add(s.frames).is_none() {
4144 return Err(format!(
4145 "{name} caption at {} runs past the last frame there is",
4146 s.start
4147 )
4148 .into());
4149 }
4150 }
4151 if !subs_sorted_disjoint(&list) {
4152 return Err(format!("the {name} lane is out of order or overlaps itself").into());
4153 }
4154 data.subs = list;
4155 // The counter also has to clear the ids these captions carry: this
4156 // is the door a load's placements come through, *after*
4157 // [`from_parts`](Project::from_parts) seeded it from the clips, and
4158 // a hand-grouped caption may carry the highest id in the file.
4159 self.next_link = self.next_link.max(
4160 data.subs
4161 .iter()
4162 .filter_map(|s| s.link)
4163 .max()
4164 .map_or(0, |m| m.saturating_add(1)),
4165 );
4166 }
4167 Ok(self)
4168 }
4169
4170 /// The mix settings a *load* puts back: lane volumes in display order (a
4171 /// short list leaves the rest at unity) and the master limiter, both
4172 /// clamped as their setters clamp them.
4173 ///
4174 /// The load's own door, beside [`from_parts`](Project::from_parts): the
4175 /// setters push an undo step, and a project that arrives one undo away from
4176 /// a state it was never in is a project whose first ctrl+z is a surprise.
4177 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
4178 for (data, &db) in self.lanes.iter_mut().zip(gains) {
4179 if db.is_finite() {
4180 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
4181 }
4182 }
4183 self.settings.limiter = limiter.with_ceiling(limiter.ceiling_db);
4184 self
4185 }
4186
4187 /// The ducks a *load* puts back, in display order and beside
4188 /// [`with_mix`](Project::with_mix), with no undo step for the same reason.
4189 /// A short list leaves the rest without one; a duck the file named is
4190 /// already validated by [`crate::edith`].
4191 pub fn with_ducks(mut self, ducks: &[Vec<Duck>]) -> Self {
4192 for (data, lane_ducks) in self.lanes.iter_mut().zip(ducks) {
4193 data.ducks = lane_ducks.clone();
4194 }
4195 self
4196 }
4197
4198 /// The voice processors a *load* puts back, in display order, with no undo
4199 /// step for the reason [`with_mix`](Project::with_mix) gives. A short list
4200 /// leaves the rest with none.
4201 pub fn with_voices(mut self, voices: &[VoiceFx]) -> Self {
4202 for (data, voice) in self.lanes.iter_mut().zip(voices) {
4203 data.voice = voice.clone();
4204 }
4205 self
4206 }
4207
4208 /// The HDR rendition a *load* puts back -- the same door
4209 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
4210 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
4211 self.settings.tone = preset;
4212 self
4213 }
4214
4215 /// The canvas and rate a *load* or a fresh open names -- the project
4216 /// resolution and the rate every clip is counted in. The same door
4217 /// [`with_mix`](Project::with_mix) is, and no undo step for the same
4218 /// reason: a project that arrives one undo away from a state it was never
4219 /// in is a project whose first ctrl+z is a surprise.
4220 pub fn with_canvas(mut self, width: u32, height: u32, frame_rate: f64) -> Self {
4221 self.settings.resolution = (width, height);
4222 self.settings.frame_rate = frame_rate;
4223 self
4224 }
4225
4226 /// The saved switches a *load* puts back: whether the picture is cut on
4227 /// the stand-ins, whether new ones are made on arrival, which encoder an
4228 /// export opens, and the rate the mix was picked to run at. The load half
4229 /// of [`set_proxies`](Project::set_proxies) and its siblings, and no undo
4230 /// step for [`with_mix`](Project::with_mix)'s reason.
4231 pub fn with_switches(
4232 mut self,
4233 proxies: bool,
4234 auto_proxies: bool,
4235 encoder_seat: crate::export::EncoderSeat,
4236 sample_rate: Option<u32>,
4237 ) -> Self {
4238 self.settings.proxies = proxies;
4239 self.settings.auto_proxies = auto_proxies;
4240 self.settings.encoder_seat = encoder_seat;
4241 self.settings.sample_rate = sample_rate;
4242 self
4243 }
4244
4245 /// The word times a *load* puts back, `(track, cue, words)`, after the cue edits and
4246 /// additions have made the cue list they index. No undo step, as [`with_tone`](Project::with_tone).
4247 pub(crate) fn with_cue_words(mut self, rows: &[CueWordRow]) -> Self {
4248 for (track, cue, words) in rows {
4249 if let Some(c) = self.subtitles.get_mut(*track).and_then(|t| t.cues.get_mut(*cue)) {
4250 c.words = words.clone();
4251 }
4252 }
4253 self
4254 }
4255
4256 /// Gives the cues of `track` the word times of `timed`, the cues they were written from:
4257 /// each track cue takes the next timed cue with the same text that starts within a
4258 /// millisecond of it (an SRT keeps milliseconds). A cue none matches keeps none. Not an undo
4259 /// step of its own: it completes the import that made the track.
4260 pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) {
4261 let Some(t) = self.subtitles.get_mut(track) else {
4262 return;
4263 };
4264 let norm = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
4265 let mut from = 0;
4266 for cue in &mut t.cues {
4267 let hit = timed[from..]
4268 .iter()
4269 .position(|w| (w.start_us - cue.start_us).abs() <= 1000 && norm(&w.text) == norm(&cue.text));
4270 if let Some(k) = hit {
4271 cue.words = timed[from + k].words.clone();
4272 from += k + 1;
4273 }
4274 }
4275 }
4276
4277 /// How burned captions animate in this project ([`crate::captionanim`]).
4278 pub fn caption_style(&self) -> crate::captionanim::CaptionStyle {
4279 self.settings.caption_style
4280 }
4281
4282 /// Sets it (clamped). `false` for the style already in force; otherwise one undo step.
4283 pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool {
4284 let style = style.clamped();
4285 if self.settings.caption_style == style {
4286 return false;
4287 }
4288 self.snapshot();
4289 self.settings.caption_style = style;
4290 true
4291 }
4292
4293 /// The caption style a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4294 pub(crate) fn with_caption_style(mut self, style: crate::captionanim::CaptionStyle) -> Self {
4295 self.settings.caption_style = style.clamped();
4296 self
4297 }
4298
4299 /// Which HDR-to-SDR rendition this project is watched and exported in. A
4300 /// project setting, not a clip's: one picture, one look
4301 /// ([`crate::tonemap::Preset`]).
4302 pub fn tone(&self) -> crate::tonemap::Preset {
4303 self.settings.tone
4304 }
4305
4306 /// The project's notes: free text, several lines allowed, empty until one is written.
4307 pub fn notes(&self) -> &str {
4308 &self.settings.notes
4309 }
4310
4311 /// Sets the notes. `false` for the text already in force; otherwise one undo step.
4312 pub fn set_notes(&mut self, notes: &str) -> bool {
4313 if self.settings.notes == notes {
4314 return false;
4315 }
4316 self.snapshot();
4317 self.settings.notes = notes.to_string();
4318 true
4319 }
4320
4321 /// The notes a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4322 pub(crate) fn with_notes(mut self, notes: String) -> Self {
4323 self.settings.notes = notes;
4324 self
4325 }
4326
4327 /// How long a still image is placed for, in seconds: [`STILL_DEFAULT_SECS`] until the
4328 /// project picks another length.
4329 pub fn still_secs(&self) -> f64 {
4330 self.settings.still_secs
4331 }
4332
4333 /// Sets it, clamped to [`STILL_MIN_SECS`]..[`STILL_MAX_SECS`]. `false` for the length already
4334 /// in force; otherwise one undo step. Only stills placed after this change take the new length.
4335 pub fn set_still_secs(&mut self, secs: f64) -> bool {
4336 let secs = if secs.is_finite() { secs.clamp(STILL_MIN_SECS, STILL_MAX_SECS) } else { STILL_DEFAULT_SECS };
4337 if self.settings.still_secs == secs {
4338 return false;
4339 }
4340 self.snapshot();
4341 self.settings.still_secs = secs;
4342 true
4343 }
4344
4345 /// The still length a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4346 pub(crate) fn with_still_secs(mut self, secs: Option<f64>) -> Self {
4347 self.settings.still_secs = secs.map_or(STILL_DEFAULT_SECS, |s| s.clamp(STILL_MIN_SECS, STILL_MAX_SECS));
4348 self
4349 }
4350
4351 /// The speech model the project names, or `None` for the one picked.
4352 pub fn speech_model(&self) -> Option<&str> {
4353 self.settings.speech_model.as_deref()
4354 }
4355
4356 /// Sets it (`None` picks one). `false` for the one already in force; otherwise one undo step.
4357 pub fn set_speech_model(&mut self, model: Option<&str>) -> bool {
4358 if self.settings.speech_model.as_deref() == model {
4359 return false;
4360 }
4361 self.snapshot();
4362 self.settings.speech_model = model.map(str::to_string);
4363 true
4364 }
4365
4366 /// The device the speech model runs on.
4367 pub fn speech_device(&self) -> crate::speech::DeviceChoice {
4368 self.settings.speech_device
4369 }
4370
4371 /// Sets it. `false` for the one already in force; otherwise one undo step.
4372 pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool {
4373 if self.settings.speech_device == device {
4374 return false;
4375 }
4376 self.snapshot();
4377 self.settings.speech_device = device;
4378 true
4379 }
4380
4381 /// The speech choices a *load* puts back: no undo step, as [`with_still_secs`](Project::with_still_secs).
4382 pub(crate) fn with_speech(mut self, model: Option<String>, device: crate::speech::DeviceChoice) -> Self {
4383 self.settings.speech_model = model;
4384 self.settings.speech_device = device;
4385 self
4386 }
4387
4388 /// Sets it. `false` for the one already in force, which is what keeps a
4389 /// re-pick of the current rendition from costing a reseek. One undo step
4390 /// like every other project-setting pick.
4391 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
4392 if self.settings.tone == preset {
4393 return false;
4394 }
4395 self.snapshot();
4396 self.settings.tone = preset;
4397 true
4398 }
4399
4400 /// The subtitle tracks a *load* puts back, in the order they were saved --
4401 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
4402 /// the same reason.
4403 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
4404 self.subtitles = tracks;
4405 self
4406 }
4407
4408 /// The languages a *load* puts back over the palette ([`with_subtitles`](
4409 /// Project::with_subtitles) must come first): `(track, code)` pairs, the
4410 /// track by its position in the palette, as the `sublang` lines name it.
4411 /// No undo step, as with the palette itself. A pair naming no row is
4412 /// ignored; the reader has already refused a line that names one.
4413 pub fn with_sub_langs(mut self, langs: &[(usize, String)]) -> Self {
4414 for (track, code) in langs {
4415 if let Some(t) = self.subtitles.get_mut(*track) {
4416 crate::subtitle::set_language(t, code);
4417 }
4418 }
4419 self
4420 }
4421
4422 /// Names the language of subtitle track `track`: an ISO 639-2 code as
4423 /// [`crate::subtitle::language_code`] gives it, or `und`. One undo step, and
4424 /// `false` (no step) for a track that is not there or already reads that.
4425 /// Kept in the project file (`sublang` lines), and an export writes it as
4426 /// the track's language.
4427 pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool {
4428 match self.subtitles.get(track) {
4429 Some(t) if t.language != code => {}
4430 _ => return false,
4431 }
4432 self.snapshot();
4433 crate::subtitle::set_language(&mut self.subtitles[track], code);
4434 true
4435 }
4436
4437 /// The title cards and text overlays, in draw order: sorted by start, and
4438 /// where two share a start, in the order they were added.
4439 pub fn titles(&self) -> &[Title] {
4440 &self.titles
4441 }
4442
4443 /// Adds a title and returns its index in [`titles`](Project::titles). It is
4444 /// kept sorted by start, so a title lands after the ones that start no
4445 /// later than it. Overlaps are allowed; the later one draws over the earlier.
4446 ///
4447 /// Refused, changing nothing and taking no undo step, when [`check_title`]
4448 /// refuses the title. A title may start past the last clip: the timeline
4449 /// runs on to cover it, over black where no clip plays.
4450 pub fn add_title(&mut self, title: Title) -> crate::Result<usize> {
4451 check_title(&title)?;
4452 self.snapshot();
4453 let idx = self.titles.partition_point(|t| t.start <= title.start);
4454 self.titles.insert(idx, title);
4455 Ok(idx)
4456 }
4457
4458 /// Replaces the title at `idx` with `title`, then re-sorts the list by start
4459 /// -- so the title may move, and a caller that holds its index looks it up
4460 /// again. `false`, changing nothing, for an index that is not there, a title
4461 /// [`check_title`] refuses, or a title the same as the one it replaces.
4462 pub fn set_title(&mut self, idx: usize, title: Title) -> bool {
4463 if idx >= self.titles.len() || check_title(&title).is_err() || self.titles[idx] == title {
4464 return false;
4465 }
4466 self.snapshot();
4467 self.titles[idx] = title;
4468 self.titles.sort_by_key(|t| t.start);
4469 true
4470 }
4471
4472 /// Takes the title at `idx` off the list. `false`, changing nothing, for an
4473 /// index that is not there.
4474 pub fn remove_title(&mut self, idx: usize) -> bool {
4475 if idx >= self.titles.len() {
4476 return false;
4477 }
4478 self.snapshot();
4479 self.titles.remove(idx);
4480 true
4481 }
4482
4483 /// The frame the last title ends on, or 0 with none: what the timeline
4484 /// runs on to, past its media.
4485 fn title_end(&self) -> u32 {
4486 self.titles.iter().map(Title::end).max().unwrap_or(0)
4487 }
4488
4489 /// The chapter markers, sorted by frame, at most one per frame.
4490 pub fn chapters(&self) -> &[Chapter] {
4491 &self.chapters
4492 }
4493
4494 /// Adds a chapter and returns its index in [`chapters`](Project::chapters).
4495 /// Refused, changing nothing and taking no undo step, when [`check_chapter`]
4496 /// refuses it or another chapter already sits on its frame.
4497 pub fn add_chapter(&mut self, chapter: Chapter) -> crate::Result<usize> {
4498 check_chapter(&chapter)?;
4499 if let Some(other) = self.chapters.iter().find(|c| c.frame == chapter.frame) {
4500 return Err(format!("chapter {:?} already starts at frame {}", other.title, other.frame).into());
4501 }
4502 self.snapshot();
4503 let idx = self.chapters.partition_point(|c| c.frame < chapter.frame);
4504 self.chapters.insert(idx, chapter);
4505 Ok(idx)
4506 }
4507
4508 /// Takes the chapter at `idx` off the list. `false`, changing nothing, for an
4509 /// index that is not there.
4510 pub fn remove_chapter(&mut self, idx: usize) -> bool {
4511 if idx >= self.chapters.len() {
4512 return false;
4513 }
4514 self.snapshot();
4515 self.chapters.remove(idx);
4516 true
4517 }
4518
4519 /// Renames the chapter at `idx`. `false`, changing nothing, for an index that
4520 /// is not there, a name [`check_chapter`] refuses, or the name it already has.
4521 pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool {
4522 let Some(current) = self.chapters.get(idx) else {
4523 return false;
4524 };
4525 let renamed = Chapter { frame: current.frame, title: title.to_string() };
4526 if current.title == title || check_chapter(&renamed).is_err() {
4527 return false;
4528 }
4529 self.snapshot();
4530 self.chapters[idx] = renamed;
4531 true
4532 }
4533
4534 /// Moves the chapter at `idx` to `frame`, and returns its new index. Refused,
4535 /// changing nothing, for an index that is not there or a frame another chapter
4536 /// already holds; a move to the frame it is on is a no-op that takes no step.
4537 pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> {
4538 let Some(current) = self.chapters.get(idx) else {
4539 return Err("no chapter there to move".into());
4540 };
4541 if current.frame == frame {
4542 return Ok(idx);
4543 }
4544 if let Some(other) = self.chapters.iter().find(|c| c.frame == frame) {
4545 return Err(format!("chapter {:?} already starts at frame {frame}", other.title).into());
4546 }
4547 self.snapshot();
4548 let mut chapter = self.chapters.remove(idx);
4549 chapter.frame = frame;
4550 let at = self.chapters.partition_point(|c| c.frame < frame);
4551 self.chapters.insert(at, chapter);
4552 Ok(at)
4553 }
4554
4555 /// Maps every chapter's frame through `map` in one undo step, for an edit that
4556 /// moves time: a cut, a ripple, a rate change. Two chapters that land on one
4557 /// frame keep the first in the list and drop the other, which is why the
4558 /// count of chapters dropped is returned. `0`, changing nothing and taking no
4559 /// step, when no frame moves.
4560 pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize {
4561 let before = self.chapters.len();
4562 let mut mapped: Vec<Chapter> = self
4563 .chapters
4564 .iter()
4565 .map(|c| Chapter { frame: map(c.frame), title: c.title.clone() })
4566 .collect();
4567 if mapped == self.chapters {
4568 return 0;
4569 }
4570 self.snapshot();
4571 // Stable sort keeps list order among chapters on one frame, so the first
4572 // one written keeps its frame.
4573 mapped.sort_by_key(|c| c.frame);
4574 mapped.dedup_by_key(|c| c.frame);
4575 let dropped = before - mapped.len();
4576 self.chapters = mapped;
4577 dropped
4578 }
4579
4580 /// Sets the whole chapter list at once, for a loader: sorted by frame, a
4581 /// second chapter on a frame dropped. Not an edit, so no undo step.
4582 pub(crate) fn with_chapters(mut self, mut chapters: Vec<Chapter>) -> Self {
4583 chapters.sort_by_key(|c| c.frame);
4584 chapters.dedup_by_key(|c| c.frame);
4585 self.chapters = chapters;
4586 self
4587 }
4588
4589 /// The comment markers, sorted by frame (several may share one).
4590 pub fn markers(&self) -> &[Marker] {
4591 &self.markers
4592 }
4593
4594 /// Adds a marker and returns its index in [`markers`](Project::markers); after any
4595 /// marker already on its frame. Refused, changing nothing and taking no undo step,
4596 /// when [`check_marker`] refuses it.
4597 pub fn add_marker(&mut self, marker: Marker) -> crate::Result<usize> {
4598 check_marker(&marker)?;
4599 self.snapshot();
4600 let idx = self.markers.partition_point(|m| m.frame <= marker.frame);
4601 self.markers.insert(idx, marker);
4602 Ok(idx)
4603 }
4604
4605 /// Takes the marker at `idx` off. `false`, changing nothing, for an index that is not there.
4606 pub fn remove_marker(&mut self, idx: usize) -> bool {
4607 if idx >= self.markers.len() {
4608 return false;
4609 }
4610 self.snapshot();
4611 self.markers.remove(idx);
4612 true
4613 }
4614
4615 /// Replaces the marker at `idx` and returns its new index (it re-sorts when its frame
4616 /// moves). Refused, changing nothing, for an index that is not there, a marker
4617 /// [`check_marker`] refuses, or one equal to what is there.
4618 pub fn set_marker(&mut self, idx: usize, marker: Marker) -> crate::Result<usize> {
4619 let Some(current) = self.markers.get(idx) else {
4620 return Err("no marker there to change".into());
4621 };
4622 check_marker(&marker)?;
4623 if *current == marker {
4624 return Err("the marker is already so".into());
4625 }
4626 self.snapshot();
4627 if self.markers[idx].frame == marker.frame {
4628 self.markers[idx] = marker;
4629 return Ok(idx);
4630 }
4631 self.markers.remove(idx);
4632 let at = self.markers.partition_point(|m| m.frame <= marker.frame);
4633 self.markers.insert(at, marker);
4634 Ok(at)
4635 }
4636
4637 /// Maps every marker's start and end through `map` in one undo step, for an edit that
4638 /// moves time, as [`remap_chapters`](Project::remap_chapters) does. A range keeps at
4639 /// least a point of itself; markers never merge, so none is lost. `false`, changing
4640 /// nothing and taking no step, when nothing moves.
4641 pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool {
4642 let mut mapped: Vec<Marker> = self
4643 .markers
4644 .iter()
4645 .map(|m| {
4646 let frame = map(m.frame);
4647 let length = if m.length == 0 { 0 } else { map(m.end()).saturating_sub(frame) };
4648 Marker { frame, length, ..m.clone() }
4649 })
4650 .collect();
4651 if mapped == self.markers {
4652 return false;
4653 }
4654 self.snapshot();
4655 mapped.sort_by_key(|m| m.frame);
4656 self.markers = mapped;
4657 true
4658 }
4659
4660 /// Sets the whole marker list at once, for a loader: sorted by frame. Not an edit, so no undo step.
4661 pub(crate) fn with_markers(mut self, mut markers: Vec<Marker>) -> Self {
4662 markers.sort_by_key(|m| m.frame);
4663 self.markers = markers;
4664 self
4665 }
4666
4667 /// Sets the whole title list at once, for a loader: the file's own order is
4668 /// kept, sorted by start as [`add_title`](Project::add_title) keeps it. Not an
4669 /// edit, so no undo step.
4670 pub(crate) fn with_titles(mut self, mut titles: Vec<Title>) -> Self {
4671 titles.sort_by_key(|t| t.start);
4672 self.titles = titles;
4673 self
4674 }
4675
4676 /// What this timeline shows over the picture, in the order they were added:
4677 /// what a front-end lists and what a save writes.
4678 pub fn subtitles(&self) -> &[SubtitleTrack] {
4679 &self.subtitles
4680 }
4681
4682 /// Adds a track, unless the very same one -- same file, same track number
4683 /// inside it -- is already on the list. `false` for that repeat: importing
4684 /// the same `.srt` twice is one subtitle track, not two identical ones.
4685 /// Adds every track of an import that is not already on the list, as one undo
4686 /// step: a failed batch that imported a track rolls the import back with it.
4687 /// Returns how many were added (none, and no step, when every one is a repeat).
4688 pub fn add_subtitles_all(&mut self, tracks: &[SubtitleTrack]) -> usize {
4689 let fresh: Vec<&SubtitleTrack> = tracks
4690 .iter()
4691 .filter(|t| !self.subtitles.iter().any(|o| o.path == t.path && o.track == t.track))
4692 .collect();
4693 if fresh.is_empty() {
4694 return 0;
4695 }
4696 self.snapshot();
4697 let n = fresh.len();
4698 self.subtitles.extend(fresh.into_iter().cloned());
4699 n
4700 }
4701
4702 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
4703 if self
4704 .subtitles
4705 .iter()
4706 .any(|t| t.path == track.path && t.track == track.track)
4707 {
4708 return false;
4709 }
4710 self.subtitles.push(track.clone());
4711 true
4712 }
4713
4714 /// Takes the track at `idx` off the list -- what a row's own remove goes
4715 /// through, so whatever an import added can be taken back out. Refused by
4716 /// name for a row this project does not have, rather than a silent no-op:
4717 /// a front-end holding a stale index has picked the wrong row and needs to
4718 /// hear it.
4719 ///
4720 /// Every index past `idx` moves down by one, as [`remove_source`](
4721 /// Project::remove_source)'s do: a caller holding a picked row (an export's
4722 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
4723 /// it, or it names a different track afterwards. The placements on the
4724 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
4725 /// index into this very list, so every one past `idx` is walked down with
4726 /// it here -- the reindex [`remove_source`](Project::remove_source) does
4727 /// for its clips, for its reason.
4728 ///
4729 /// Refused, changing nothing, while anything placed on a subtitle lane
4730 /// plays *this* row: the placement would have to be deleted or retargeted,
4731 /// and either one is an edit nobody asked for. The refusal names the lane
4732 /// and the frame it is at, up to three of them --
4733 /// [`remove_source`](Project::remove_source) refuses the same way for the
4734 /// same silent corruption.
4735 ///
4736 /// One undo step, and the reindex with it: every placement names a track
4737 /// by index into the palette ([`crate::subtitle`]), so a removal that
4738 /// renumbers them can only come back together with the palette it took
4739 /// the row from -- which is what the history entry holds, beside the
4740 /// lanes it also carries ([`Snapshot`]). The inverse, for a caller that
4741 /// wants the file's tracks back, is [`crate::PlaybackSession::import_subtitles`]
4742 /// -- the panel's own door, which reads the subtitles of a file and
4743 /// nothing else.
4744 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
4745 if idx >= self.subtitles.len() {
4746 return Err(format!("there is no subtitle track {idx} to remove").into());
4747 }
4748 let placed: Vec<String> = handles(&self.lanes)
4749 .into_iter()
4750 .zip(&self.lanes)
4751 .flat_map(|(lane, data)| {
4752 data.subs
4753 .iter()
4754 .filter(move |s| s.track == idx)
4755 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
4756 })
4757 .take(3)
4758 .collect();
4759 if !placed.is_empty() {
4760 return Err(format!(
4761 "{} is on the timeline ({}): delete those clips first",
4762 self.track_name(idx),
4763 placed.join(", ")
4764 )
4765 .into());
4766 }
4767 self.snapshot();
4768 self.subtitles.remove(idx);
4769 // The overrides follow their tracks down, as the placements do, and the
4770 // removed row's own go with it: a row added again later is a new read of
4771 // the file, and its words are the file's.
4772 self.cue_edits.retain(|(t, _, _)| *t != idx);
4773 for (t, _, _) in &mut self.cue_edits {
4774 if *t > idx {
4775 *t -= 1;
4776 }
4777 }
4778 self.cue_adds.retain(|a| a.track != idx);
4779 for a in &mut self.cue_adds {
4780 if a.track > idx {
4781 a.track -= 1;
4782 }
4783 }
4784 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
4785 if s.track > idx {
4786 s.track -= 1;
4787 }
4788 }
4789 Ok(())
4790 }
4791
4792 /// What a refusal calls a palette row: the name the panel shows, and the
4793 /// index alone for a row that is not there.
4794 fn track_name(&self, track: usize) -> String {
4795 self.subtitles
4796 .get(track)
4797 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
4798 }
4799
4800 /// The subtitle lanes in display order -- what a front-end lays out and
4801 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
4802 /// [`audio_lanes`](Project::audio_lanes).
4803 pub fn subtitle_lanes(&self) -> Vec<Lane> {
4804 self.lanes()
4805 .into_iter()
4806 .filter(|l| l.kind == LaneKind::Subtitle)
4807 .collect()
4808 }
4809
4810 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
4811 /// for a subtitle track, and empty for every other lane and for one that is
4812 /// not there.
4813 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
4814 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
4815 }
4816
4817 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
4818 /// twin, with one deliberate difference: it **refuses** an overlap instead
4819 /// of overwriting what it lands on.
4820 ///
4821 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
4822 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
4823 /// carries is a *window of a track* and where the hand let go, and the
4824 /// second of those is the argument. So a caller builds the placement once
4825 /// (from the palette row it dragged) and drops it at as many frames as it
4826 /// likes without rewriting the field each time.
4827 ///
4828 /// A picture placed over a picture hides it and the hidden one is still
4829 /// there to drag back out; two captions in one frame are two lines nobody
4830 /// asked to stack, and the words that lost are gone from the screen with
4831 /// nothing to show for it. So the refusal names the placement in the way,
4832 /// and the caller picks another frame or another lane -- which is what a
4833 /// second subtitle lane is for.
4834 ///
4835 /// One undo step on success, and none on any refusal: an empty window or an
4836 /// empty span, a track the palette does not have
4837 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
4838 /// subtitle lane, a span that would run past the last frame there is, and
4839 /// the overlap above.
4840 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
4841 if lane.kind != LaneKind::Subtitle {
4842 return Err(format!(
4843 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
4844 the others",
4845 lane.label()
4846 )
4847 .into());
4848 }
4849 let Some(i) = self.index(lane) else {
4850 return Err(format!("there is no {} to place on", lane.label()).into());
4851 };
4852 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
4853 return Err(format!(
4854 "that placement is empty: {} frames of [{}, {})",
4855 sub.frames, sub.in_us, sub.out_us
4856 )
4857 .into());
4858 }
4859 // The width of that window, which the check above cannot see: the same
4860 // bound the two file doors hold a placement to
4861 // ([`edith`](crate::edith)'s parse and [`with_subs`]), asked here
4862 // because this is the door a *dragged* caption comes through and the
4863 // hand that dragged it builds the `SubClip` itself.
4864 if sub.out_us - sub.in_us > MAX_WINDOW_US {
4865 return Err(format!(
4866 "that placement is a {}us window, past the {}us a caption can hold",
4867 sub.out_us - sub.in_us,
4868 MAX_WINDOW_US
4869 )
4870 .into());
4871 }
4872 if sub.track >= self.subtitles.len() {
4873 return Err(format!(
4874 "it names subtitle track {} of {}",
4875 sub.track,
4876 self.subtitles.len()
4877 )
4878 .into());
4879 }
4880 // The placement belongs to no group, for [`place`]'s reason: a caption
4881 // dragged out of the palette arrives alone, and grouping it with what
4882 // is under it is a hand's decision ([`Project::group_all`]).
4883 let sub = SubClip {
4884 start: at,
4885 link: None,
4886 ..sub
4887 };
4888 if at.checked_add(sub.frames).is_none() {
4889 return Err(
4890 format!("a placement at frame {at} runs past the last frame there is").into(),
4891 );
4892 }
4893 if let Some(other) = self.lanes[i]
4894 .subs
4895 .iter()
4896 .find(|o| o.end() > sub.start && o.start < sub.end())
4897 {
4898 return Err(format!(
4899 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
4900 on another subtitle track",
4901 lane.label(),
4902 other.start,
4903 other.start,
4904 other.end()
4905 )
4906 .into());
4907 }
4908 self.snapshot();
4909 let subs = &mut self.lanes[i].subs;
4910 let idx = subs.partition_point(|o| o.start < sub.start);
4911 subs.insert(idx, sub);
4912 debug_assert!(subs_sorted_disjoint(subs));
4913 Ok(())
4914 }
4915
4916 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
4917 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
4918 /// refused an overlap where that one clamps to it, for
4919 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
4920 /// still and no picture under it that a landing would hide, so "as far as
4921 /// it goes" would silently be a frame nobody named.
4922 ///
4923 /// A caption *in* a group drags the group: one delta for every member --
4924 /// its clips and its other captions -- clamped to the room each of them
4925 /// has, exactly as a clip's drag always has. That is the point of putting
4926 /// a caption in a group: the words go where the picture goes.
4927 ///
4928 /// The window travels untouched: a caption dragged later says the same
4929 /// words later, exactly as a clip dragged later plays the same pictures
4930 /// later.
4931 ///
4932 /// One undo step on success; nothing changed and no step on a refusal --
4933 /// an index that is not there, a lane that is not a subtitle lane or is not
4934 /// there, and (for a caption in no group) an overlap. A drop that changes
4935 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
4936 /// up and put it back has done nothing wrong, and a front-end showing every
4937 /// `Err` would say so.
4938 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
4939 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
4940 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
4941 };
4942 if to.kind != LaneKind::Subtitle {
4943 return Err(format!(
4944 "{} is not a subtitle track: a caption cannot play on it",
4945 to.label()
4946 )
4947 .into());
4948 }
4949 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
4950 return Err(format!("there is no {} to move onto", to.label()).into());
4951 };
4952 if (here, start) == (dest, sub.start) {
4953 // A pick-up-put-back: the drag ended where it began, which is not a
4954 // mistake to name -- `Ok`, and no undo step, because nothing
4955 // changed. A refusal here would toast a hand that did nothing.
4956 return Ok(());
4957 }
4958 if start.checked_add(sub.frames).is_none() {
4959 return Err(
4960 format!("a placement at frame {start} runs past the last frame there is").into(),
4961 );
4962 }
4963 // A grouped caption carries its group, clamped to the room the whole
4964 // group has rather than refused ([`Project::move_room]) -- one drag, one
4965 // delta, one undo step.
4966 let members = self.group_of(from, idx).expect("the subtitle was found");
4967 if !members.alone() {
4968 if members
4969 .subs
4970 .iter()
4971 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
4972 {
4973 return Err(format!(
4974 "a group is one caption per track: {} already carries this group",
4975 to.label()
4976 )
4977 .into());
4978 }
4979 let want = i64::from(start) - i64::from(sub.start);
4980 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start)), None) else {
4981 return Err(format!(
4982 "another placement already covers those frames on {}",
4983 to.label()
4984 )
4985 .into());
4986 };
4987 let delta = want.clamp(lo, hi);
4988 self.snapshot();
4989 for &(l, i) in &members.clips {
4990 let c = &mut self.lanes[l].clips[i];
4991 c.start = (i64::from(c.start) + delta) as u32;
4992 }
4993 for &(l, i) in &members.subs {
4994 let s = &mut self.lanes[l].subs[i];
4995 s.start = (i64::from(s.start) + delta) as u32;
4996 }
4997 let moved = self.lanes[here].subs.remove(idx);
4998 let subs = &mut self.lanes[dest].subs;
4999 let at = subs.partition_point(|o| o.start < moved.start);
5000 subs.insert(at, moved);
5001 debug_assert!(subs_sorted_disjoint(subs));
5002 debug_assert!(
5003 members
5004 .clips
5005 .iter()
5006 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips))
5007 );
5008 return Ok(());
5009 }
5010 let moved = SubClip { start, ..sub };
5011 if let Some(other) = self.lanes[dest]
5012 .subs
5013 .iter()
5014 .enumerate()
5015 .find(|&(j, o)| {
5016 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
5017 })
5018 .map(|(_, o)| *o)
5019 {
5020 return Err(format!(
5021 "the {} subtitle at frame {} already covers [{}, {})",
5022 to.label(),
5023 other.start,
5024 other.start,
5025 other.end()
5026 )
5027 .into());
5028 }
5029 self.snapshot();
5030 self.lanes[here].subs.remove(idx);
5031 let subs = &mut self.lanes[dest].subs;
5032 let at = subs.partition_point(|o| o.start < moved.start);
5033 subs.insert(at, moved);
5034 debug_assert!(subs_sorted_disjoint(subs));
5035 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
5036 Ok(())
5037 }
5038
5039 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
5040 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
5041 /// pulling an edge past what is legal means "as far as it goes".
5042 ///
5043 /// The window follows the edge, in the seconds the frames are worth at
5044 /// `fps`: a head pulled in starts the caption later *in its track* (the
5045 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
5046 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
5047 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
5048 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
5049 /// needed here and nowhere else in this file, because a trim is the only
5050 /// edit that changes a *duration*.
5051 ///
5052 /// The walls: one frame always survives, an edge never crosses the
5053 /// neighbouring subtitle on its own lane, a head never walks back past the
5054 /// track's own start (`in_us` of 0), and a tail never runs past the last
5055 /// cue the track has -- which is the source length a media trim needs a
5056 /// caller's table for, and which this one can simply read.
5057 ///
5058 /// `Err`, with nothing changed and no undo step, for an index that is not
5059 /// there and an unusable `fps`. An edge that ends up where it already was
5060 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
5061 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
5062 /// reason: a drag that stops at a wall is not a mistake to report.
5063 pub fn trim_sub(
5064 &mut self,
5065 lane: Lane,
5066 idx: usize,
5067 edge: Edge,
5068 to: u32,
5069 fps: f64,
5070 ) -> crate::Result<()> {
5071 if !(fps.is_finite() && fps > 0.0) {
5072 return Err(format!("{fps} is not a frame rate to trim against").into());
5073 }
5074 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
5075 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
5076 };
5077 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
5078 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
5079 };
5080 let to = to.clamp(lo, hi);
5081 let at = match edge {
5082 Edge::Start => sub.start,
5083 Edge::End => sub.end(),
5084 };
5085 if to == at {
5086 // The edge is where it was asked to go -- either the hand did not
5087 // move it, or the clamp above stopped it at a wall it was already
5088 // standing against. Both are a drag that changed nothing: `Ok`, no
5089 // undo step, and no toast for a box that simply stopped moving.
5090 return Ok(());
5091 }
5092 self.snapshot();
5093 let members = self.group_of(lane, idx).expect("the subtitle was found");
5094 let i = self.index(lane).expect("the subtitle was found on it");
5095 let s = &mut self.lanes[i].subs[idx];
5096 match edge {
5097 // The words that stay are the words that were there, so the window
5098 // moves with the head -- a trim, not a slip.
5099 Edge::Start => {
5100 // The head moves and the words that stay are the words that
5101 // were there, so `in_us` follows it -- a trim, not a slip.
5102 // Falling `in_us` makes the window *wider* (the ceiling bounds
5103 // a difference), which is the half of this nothing here can
5104 // see: `set_window` is what puts the width back inside.
5105 set_window(
5106 s,
5107 s.in_us
5108 .saturating_add(us_of(i64::from(to) - i64::from(s.start), fps)),
5109 s.out_us,
5110 );
5111 s.frames = s.end() - to;
5112 s.start = to;
5113 }
5114 Edge::End => {
5115 // ...and the tail, for [`set_window`]'s reason: the End room
5116 // is walled at the ceiling, but `set_window` is what holds it
5117 // for every other composer too, including this one when a
5118 // caller hands `trim_sub` a `to` past its own room.
5119 set_window(
5120 s,
5121 s.in_us,
5122 s.out_us
5123 .saturating_add(us_of(i64::from(to) - i64::from(s.end()), fps)),
5124 );
5125 s.frames = to - s.start;
5126 }
5127 }
5128 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5129 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
5130 // A caption in a group drags its group's edge with it, exactly as a
5131 // clip's trim does: one delta, each member clamped to its own room.
5132 // No source table to grow by, which only tightens how far a member may
5133 // follow -- never whether it may.
5134 self.follow_group(
5135 &members,
5136 &(i, idx),
5137 edge,
5138 i64::from(to) - i64::from(at),
5139 SourceWalls::same(&[]),
5140 );
5141 Ok(())
5142 }
5143
5144 /// How far that edge may travel, `(first, last)` timeline frame inclusive
5145 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
5146 /// drawing the box during a drag asks. `None` for an index that is not
5147 /// there.
5148 pub fn trim_sub_room(
5149 &self,
5150 lane: Lane,
5151 idx: usize,
5152 edge: Edge,
5153 fps: f64,
5154 ) -> Option<(u32, u32)> {
5155 let subs = self.sub_lane(lane);
5156 let s = *subs.get(idx)?;
5157 // How many timeline frames a stretch of the track is worth, which is
5158 // what turns its two walls -- its own start, and its last cue -- into
5159 // frames. A rate that is not a rate leaves the window where it is.
5160 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
5161 true => ((us as f64) * fps / 1e6)
5162 .round()
5163 .max(0.0)
5164 .min(f64::from(u32::MAX)) as u32,
5165 false => 0,
5166 };
5167 Some(match edge {
5168 Edge::Start => (
5169 s.start
5170 .saturating_sub(frames_of(s.in_us))
5171 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
5172 s.end() - 1,
5173 ),
5174 Edge::End => {
5175 // Out to the end of the track it reads, and never over the
5176 // subtitle behind it. A track the palette no longer has (or one
5177 // with no cues at all) may not grow, exactly as a source with no
5178 // entry in a media trim's table may not.
5179 let track_end = self
5180 .subtitles
5181 .get(s.track)
5182 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
5183 .unwrap_or(s.out_us);
5184 // ...and never past [`grow_window`]'s ceiling, which is the
5185 // wall that matters here: a front-end asks this to draw the
5186 // drag, then trims to whatever it is told. An engine that
5187 // offers room its own trim would refuse is a drag that snaps
5188 // back at the end of the gesture -- so the room stops where
5189 // the window stops, and the two agree by construction.
5190 let wall_us = track_end.min(s.in_us.saturating_add(MAX_WINDOW_US));
5191 (
5192 s.start + 1,
5193 s.start
5194 .saturating_add(frames_of((wall_us - s.in_us).max(1)))
5195 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5196 )
5197 }
5198 })
5199 }
5200
5201 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
5202 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
5203 /// `false` for an index that is not there (which a lane that is not a
5204 /// subtitle lane always is).
5205 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
5206 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
5207 return false;
5208 };
5209 self.snapshot();
5210 self.lanes[i].subs.remove(idx);
5211 true
5212 }
5213
5214 /// Retypes one cue's words: cue `cue` of subtitle track `track`. The words
5215 /// belong to the **track**, not to one placement, so every placement of that
5216 /// track shows the new text -- a subtitle file's line is one line however
5217 /// many times the film plays it, and that is why this is a palette edit and
5218 /// not a placement one.
5219 ///
5220 /// `false`, changing nothing and taking no undo step, for a row or a cue
5221 /// that is not there, for a picture cue (a display set has no words), and
5222 /// for text the cue already has. Empty text is not a blank cue: it deletes
5223 /// the cue ([`delete_cue`](Project::delete_cue)), which is the one way a cue
5224 /// leaves a track. The edit is kept in [`cue_edits`](Project::cue_edits),
5225 /// which a save writes and a reopen puts back over the file's own words
5226 /// ([`with_cue_edits`](Project::with_cue_edits)).
5227 pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool {
5228 if text.is_empty() {
5229 return self.delete_cue(track, cue);
5230 }
5231 let Some(c) = self.subtitles.get(track).and_then(|t| t.cues.get(cue)) else {
5232 return false;
5233 };
5234 if c.image.is_some() || c.text == text {
5235 return false;
5236 }
5237 let added = self.added_index(track, cue);
5238 let orig = if added.is_none() { self.original_cue_index(track, cue) } else { 0 };
5239 self.snapshot();
5240 self.subtitles[track].cues[cue].text = text.to_string();
5241 match added {
5242 Some(i) => self.cue_adds[i].text = text.to_string(),
5243 None => self.record_cue_edit(track, orig, text),
5244 }
5245 true
5246 }
5247
5248 /// Removes one cue from subtitle track `track`, as [`set_cue_text`](Project::set_cue_text)
5249 /// names it. The track is the palette every placement of it shows, so the
5250 /// cue is gone from each of them; no placement moves, since a cue's place is
5251 /// its own time in the file, and the cues after it keep theirs. One undo step.
5252 ///
5253 /// `false` for a track or cue that is not there. A picture cue can go too.
5254 /// The removal is kept in [`cue_edits`](Project::cue_edits) as an empty text
5255 /// on the cue's file index, so a reopen takes the same cue out again.
5256 pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool {
5257 if self.subtitles.get(track).is_none_or(|t| cue >= t.cues.len()) {
5258 return false;
5259 }
5260 self.snapshot();
5261 self.drop_cue(track, cue);
5262 true
5263 }
5264
5265 /// Adds a cue to subtitle track `track`, on the track's own clock: `start_us`
5266 /// to `end_us` in microseconds, with `text` (`\n` between lines). It is kept
5267 /// in the track's cue list at its start, shows in every placement of the
5268 /// track, and is written by a save as a [`AddedCue`]. Returns its index in
5269 /// the track.
5270 ///
5271 /// Refused, changing nothing and taking no undo step, for a track that is
5272 /// not there, empty text, an end that is not after the start, a picture
5273 /// track, and a cue that overlaps one already there -- unless `overwrite`,
5274 /// which removes every overlapped cue first. Both the add and those removals
5275 /// are one undo step.
5276 pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> {
5277 let Some(t) = self.subtitles.get(track) else {
5278 return Err(format!("there is no subtitle track {track}").into());
5279 };
5280 if text.is_empty() {
5281 return Err("a cue needs words: empty text adds no cue".into());
5282 }
5283 if end_us <= start_us {
5284 return Err(format!("a cue must end after it starts ({start_us} µs to {end_us} µs)").into());
5285 }
5286 if t.cues.iter().any(|c| c.image.is_some()) {
5287 return Err(format!("track {track} is pictures, not text: a text cue cannot be added to it").into());
5288 }
5289 let clash: Vec<usize> = t
5290 .cues
5291 .iter()
5292 .enumerate()
5293 .filter(|(_, c)| c.start_us < end_us && start_us < c.end_us)
5294 .map(|(i, _)| i)
5295 .collect();
5296 if let (false, Some(&first)) = (overwrite, clash.first()) {
5297 return Err(format!("track {track} cue {first} overlaps the new cue: pass overwrite to replace it").into());
5298 }
5299 self.snapshot();
5300 // Highest first, so each position still names the cue it named.
5301 for &i in clash.iter().rev() {
5302 self.drop_cue(track, i);
5303 }
5304 let at = self.subtitles[track].cues.partition_point(|c| c.start_us <= start_us);
5305 self.subtitles[track].cues.insert(
5306 at,
5307 crate::subtitle::Cue { start_us, end_us, text: text.to_string(), image: None, words: Vec::new(), karaoke: Vec::new() },
5308 );
5309 self.cue_adds.push(AddedCue { track, start_us, end_us, text: text.to_string() });
5310 Ok(at)
5311 }
5312
5313 /// Divides every text cue of track `track` that straddles `t_us` (on the
5314 /// track's own clock) into two cues at `t_us`, one undo step. Each cue's
5315 /// words are shared out at the word boundary nearest the proportional point
5316 /// ([`split_words`]), so a window edge that falls inside a sentence leaves
5317 /// each side only the words it covers, and a piece with no words is dropped.
5318 ///
5319 /// `false`, changing nothing and taking no undo step, when no cue straddles
5320 /// `t_us`. A picture cue is never split.
5321 pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool {
5322 let straddles = self
5323 .subtitles
5324 .get(track)
5325 .is_some_and(|t| {
5326 t.cues
5327 .iter()
5328 .any(|c| c.image.is_none() && c.start_us < t_us && t_us < c.end_us && split_words(c, t_us).is_some())
5329 });
5330 if !straddles {
5331 return false;
5332 }
5333 self.snapshot();
5334 self.split_cue_raw(track, t_us, false);
5335 true
5336 }
5337
5338 /// The room cue `cue` of track `track` has to move or trim in, on the track's
5339 /// own clock: from the end of the cue before it (or 0) to the start of the cue
5340 /// after it (or the end of time). `None` for a cue that is not there.
5341 pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> {
5342 let t = self.subtitles.get(track)?;
5343 let c = t.cues.get(cue)?;
5344 let lo = cue.checked_sub(1).map_or(0, |p| t.cues[p].end_us.min(c.start_us));
5345 let hi = t.cues.get(cue + 1).map_or(i64::MAX, |n| n.start_us.max(c.end_us));
5346 Some((lo, hi))
5347 }
5348
5349 /// Where timeline time `tl_us` falls on the track's own clock, through the
5350 /// placement on `lane` that shows cue `cue` of `track` (extrapolated when it is
5351 /// outside the cue's shown part). `None` when no placement on `lane` shows it.
5352 pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64, fps: f64) -> Option<i64> {
5353 let s = self.sub_lane_cue_spans(lane, fps).into_iter().find(|s| s.track == track && s.cue == cue)?;
5354 let (shown, window) = ((s.end_us - s.start_us).max(1) as f64, (s.window.1 - s.window.0) as f64);
5355 Some(s.window.0 + ((tl_us - s.start_us) as f64 * window / shown).round() as i64)
5356 }
5357
5358 /// Gives cue `cue` of `track` new times and words, kept the way a cue add keeps
5359 /// them: an added cue's entry is updated, a file cue is removed as
5360 /// [`drop_cue`](Project::drop_cue) does and re-added with its new times. The cue
5361 /// keeps its place in the track. No undo step of its own.
5362 fn rewrite_cue_raw(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64, text: &str) {
5363 match self.added_index(track, cue) {
5364 Some(i) => {
5365 let a = &mut self.cue_adds[i];
5366 (a.start_us, a.end_us, a.text) = (start_us, end_us, text.to_string());
5367 }
5368 None => {
5369 let orig = self.original_cue_index(track, cue);
5370 self.cue_edits.retain(|(t, c, _)| !(*t == track && *c == orig));
5371 self.cue_edits.push((track, orig, String::new()));
5372 self.cue_adds.push(AddedCue { track, start_us, end_us, text: text.to_string() });
5373 }
5374 }
5375 let c = &mut self.subtitles[track].cues[cue];
5376 (c.start_us, c.end_us, c.text) = (start_us, end_us, text.to_string());
5377 }
5378
5379 /// Moves or trims one cue: new `start_us` and `end_us` on the track's own clock,
5380 /// kept inside its neighbours ([`cue_room`](Project::cue_room)) and at least
5381 /// [`MIN_CUE_US`] long. One undo step. `Ok(false)`, with none, when the times are
5382 /// the cue's own; `Err` for a cue that is not there, a picture cue, or times
5383 /// that break those rules.
5384 pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> {
5385 let Some((lo, hi)) = self.cue_room(track, cue) else {
5386 return Err(format!("track {track} has no cue {cue}").into());
5387 };
5388 let c = &self.subtitles[track].cues[cue];
5389 if c.image.is_some() {
5390 return Err("a picture cue has no times to set".into());
5391 }
5392 if (c.start_us, c.end_us) == (start_us, end_us) {
5393 return Ok(false);
5394 }
5395 if end_us - start_us < MIN_CUE_US {
5396 return Err(format!("a cue is at least {} ms long", MIN_CUE_US / 1000).into());
5397 }
5398 if start_us < lo || end_us > hi {
5399 return Err("the cue would run into its neighbour".into());
5400 }
5401 let text = c.text.clone();
5402 self.snapshot();
5403 self.rewrite_cue_raw(track, cue, start_us, end_us, &text);
5404 Ok(true)
5405 }
5406
5407 /// Joins cue `cue` of `track` with the one after it: one cue from the first's
5408 /// start to the second's end, the words one after the other (a space between),
5409 /// whatever lay between them now inside it. One undo step. `Err`, changing
5410 /// nothing, for a cue with none after it or a picture cue.
5411 pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> {
5412 let Some(t) = self.subtitles.get(track) else {
5413 return Err(format!("there is no subtitle track {track}").into());
5414 };
5415 let (Some(a), Some(b)) = (t.cues.get(cue), t.cues.get(cue + 1)) else {
5416 return Err("there is no cue after it to merge with".into());
5417 };
5418 if a.image.is_some() || b.image.is_some() {
5419 return Err("a picture cue cannot be merged".into());
5420 }
5421 let text = format!("{} {}", a.text.trim_end(), b.text.trim_start());
5422 let (start_us, end_us) = (a.start_us, b.end_us.max(a.end_us));
5423 let (words, karaoke) = (b.words.clone(), b.karaoke.clone());
5424 self.snapshot();
5425 self.drop_cue(track, cue + 1);
5426 self.rewrite_cue_raw(track, cue, start_us, end_us, &text);
5427 let c = &mut self.subtitles[track].cues[cue];
5428 c.words.extend(words);
5429 c.karaoke.extend(karaoke);
5430 Ok(())
5431 }
5432
5433 /// Splits the cues of every subtitle lane in `on` at the window edges a cut
5434 /// at each of `frames` would make: a placement that strictly straddles a
5435 /// frame gets its window's point there ([`SubClip::window_at`]), and each
5436 /// cue crossing that point is divided. No undo step of its own; the caller
5437 /// has taken its snapshot. Called before the lanes move, so the windows are
5438 /// the ones the cut will split.
5439 ///
5440 /// `both_sides` keeps a one-word cue on both sides of a point
5441 /// ([`cut_pieces`]), for a cut: which side the cut leaves in a window is
5442 /// only known after the ripple, so the caller drops the other one with
5443 /// [`drop_unplaced`](Project::drop_unplaced). A split (`false`) keeps the
5444 /// word on one side only. Returns the pieces made, `(track, start_us, end_us)`.
5445 fn split_cues_across(&mut self, on: &[usize], frames: &[u32], both_sides: bool) -> Vec<(usize, i64, i64)> {
5446 let mut points: Vec<(usize, i64)> = Vec::new();
5447 // A placement that both edges of a cut fall inside: its track and the two window points.
5448 let mut spans: Vec<(usize, i64, i64)> = Vec::new();
5449 for &i in on {
5450 for s in &self.lanes[i].subs {
5451 let inside: Vec<i64> = frames
5452 .iter()
5453 .filter(|&&f| s.start < f && f < s.end())
5454 .map(|&f| s.window_at(f))
5455 .collect();
5456 points.extend(inside.iter().map(|&t| (s.track, t)));
5457 if let [a, b] = inside[..] {
5458 spans.push((s.track, a, b));
5459 }
5460 }
5461 }
5462 let mut pieces = Vec::new();
5463 for (track, a, b) in spans {
5464 pieces.extend(self.keep_one_word_outside(track, a, b));
5465 }
5466 for (track, t) in points {
5467 pieces.extend(self.split_cue_raw(track, t, both_sides));
5468 }
5469 pieces
5470 }
5471
5472 /// A cut from `a` to `b` through the middle of a one-word cue: the word is
5473 /// kept on whichever side the cut leaves longer (ties: the side before), and
5474 /// the removed middle and the other side are dropped, as [`split_words`]
5475 /// does for a single edge. A cue with more words is left for
5476 /// [`split_cue_raw`](Project::split_cue_raw) to divide at each edge.
5477 fn keep_one_word_outside(&mut self, track: usize, a: i64, b: i64) -> Vec<(usize, i64, i64)> {
5478 let Some(t) = self.subtitles.get(track) else {
5479 return Vec::new();
5480 };
5481 let crossing: Vec<usize> = t
5482 .cues
5483 .iter()
5484 .enumerate()
5485 .filter(|(_, c)| {
5486 c.image.is_none() && c.start_us < a && b < c.end_us && c.text.split_whitespace().count() == 1
5487 })
5488 .map(|(i, _)| i)
5489 .collect();
5490 let mut pieces = Vec::new();
5491 for &i in crossing.iter().rev() {
5492 let cue = self.subtitles[track].cues[i].clone();
5493 let text = cue.text.trim().to_string();
5494 let (start_us, end_us) = if a - cue.start_us >= cue.end_us - b {
5495 (cue.start_us, a)
5496 } else {
5497 (b, cue.end_us)
5498 };
5499 self.drop_cue(track, i);
5500 self.add_piece(track, start_us, end_us, text);
5501 pieces.push((track, start_us, end_us));
5502 }
5503 pieces
5504 }
5505
5506 /// Puts one piece of a divided cue into `track` at its start time, and keeps
5507 /// it the way a cue add keeps it (an [`AddedCue`]), so a save and a reopen
5508 /// give back the same cues.
5509 fn add_piece(&mut self, track: usize, start_us: i64, end_us: i64, text: String) {
5510 let at = self.subtitles[track].cues.partition_point(|c| c.start_us <= start_us);
5511 self.subtitles[track]
5512 .cues
5513 .insert(at, crate::subtitle::Cue { start_us, end_us, text: text.clone(), image: None, words: Vec::new(), karaoke: Vec::new() });
5514 self.cue_adds.push(AddedCue { track, start_us, end_us, text });
5515 }
5516
5517 /// [`split_cues_at`](Project::split_cues_at) with no snapshot and no check:
5518 /// each cue of `track` straddling `t_us` is replaced by its pieces, cut by
5519 /// [`cut_pieces`] with `both_sides`. The pieces are kept the way a cue add
5520 /// keeps them -- the file's cue is removed as [`drop_cue`](Project::drop_cue)
5521 /// does and each piece is an [`AddedCue`] -- so a save and a reopen give back
5522 /// the same cues. Returns the pieces made, `(track, start_us, end_us)`.
5523 fn split_cue_raw(&mut self, track: usize, t_us: i64, both_sides: bool) -> Vec<(usize, i64, i64)> {
5524 let Some(t) = self.subtitles.get(track) else {
5525 return Vec::new();
5526 };
5527 let crossing: Vec<usize> = t
5528 .cues
5529 .iter()
5530 .enumerate()
5531 .filter(|(_, c)| c.image.is_none() && c.start_us < t_us && t_us < c.end_us)
5532 .map(|(i, _)| i)
5533 .collect();
5534 let mut made = Vec::new();
5535 // Highest first, so each index still names the cue it named.
5536 for &i in crossing.iter().rev() {
5537 let cue = self.subtitles[track].cues[i].clone();
5538 let Some(pieces) = cut_pieces(&cue, t_us, both_sides) else {
5539 continue;
5540 };
5541 self.drop_cue(track, i);
5542 for (start_us, end_us, text) in pieces {
5543 self.add_piece(track, start_us, end_us, text);
5544 made.push((track, start_us, end_us));
5545 }
5546 }
5547 made
5548 }
5549
5550 /// The tracks a cut over the lanes `on` can change the windows of: the
5551 /// tracks their placements show, each once.
5552 fn caption_tracks_on(&self, on: &[usize]) -> Vec<usize> {
5553 let mut tracks: Vec<usize> = on.iter().flat_map(|&i| self.lanes[i].subs.iter().map(|s| s.track)).collect();
5554 tracks.sort_unstable();
5555 tracks.dedup();
5556 tracks
5557 }
5558
5559 /// Every placement window of every lane, as `(track, in_us, out_us)`.
5560 fn windows(&self) -> Vec<(usize, i64, i64)> {
5561 self.lanes
5562 .iter()
5563 .flat_map(|l| l.subs.iter())
5564 .map(|s| (s.track, s.in_us, s.out_us))
5565 .collect()
5566 }
5567
5568 /// The cues of `tracks` that some placement window covers now (overlaps
5569 /// it), as `(track, start_us, end_us)`.
5570 fn placed_cues(&self, tracks: &[usize]) -> Vec<(usize, i64, i64)> {
5571 let windows = self.windows();
5572 let mut out = Vec::new();
5573 for &t in tracks {
5574 let Some(track) = self.subtitles.get(t) else {
5575 continue;
5576 };
5577 for c in &track.cues {
5578 if windows.iter().any(|&(w, a, b)| w == t && c.start_us < b && a < c.end_us) {
5579 out.push((t, c.start_us, c.end_us));
5580 }
5581 }
5582 }
5583 out
5584 }
5585
5586 /// After a cut, drops the track cues it left outside every placement window
5587 /// of their track. A cue is dropped only if it is one the cut touched:
5588 /// `placed` is the cues a window covered before the cut, and `pieces` the
5589 /// ones the cut made ([`split_cues_across`](Project::split_cues_across)). A
5590 /// cue no placement ever covered (a caption placed over a part of its track,
5591 /// say) is not the cut's to remove, so it stays for a later placement.
5592 ///
5593 /// The cut leaves the words it removed, or the side of a divided cue it
5594 /// cut away, outside every window -- those are the orphans this drops. The
5595 /// piece a window still covers stays, with its words.
5596 fn drop_unplaced(&mut self, tracks: &[usize], placed: &[(usize, i64, i64)], pieces: &[(usize, i64, i64)]) {
5597 let windows = self.windows();
5598 for &t in tracks {
5599 let Some(mut i) = self.subtitles.get(t).map(|tr| tr.cues.len()) else {
5600 continue;
5601 };
5602 // Last first, so dropping one leaves the indices before it true.
5603 while i > 0 {
5604 i -= 1;
5605 let Some(c) = self.subtitles.get(t).and_then(|tr| tr.cues.get(i)) else {
5606 continue;
5607 };
5608 let key = (t, c.start_us, c.end_us);
5609 let touched = placed.contains(&key) || pieces.contains(&key);
5610 let covered = windows.iter().any(|&(w, a, b)| w == t && c.start_us < b && a < c.end_us);
5611 if touched && !covered {
5612 self.drop_cue(t, i);
5613 }
5614 }
5615 }
5616 }
5617
5618 /// Takes cue `cue` out of track `track` with no undo step of its own. An
5619 /// added cue leaves the added list; a file cue's removal is kept as an
5620 /// empty override on its file index.
5621 fn drop_cue(&mut self, track: usize, cue: usize) {
5622 match self.added_index(track, cue) {
5623 Some(i) => {
5624 self.cue_adds.remove(i);
5625 }
5626 None => {
5627 let orig = self.original_cue_index(track, cue);
5628 self.cue_edits.retain(|(t, c, _)| !(*t == track && *c == orig));
5629 self.cue_edits.push((track, orig, String::new()));
5630 }
5631 }
5632 self.subtitles[track].cues.remove(cue);
5633 }
5634
5635 /// Which entry of [`cue_adds`](Project::cue_adds) cue `cue` of track `track`
5636 /// is, if it was added rather than read from the file. An added cue is found
5637 /// by its times: no file cue overlaps one, since adding it refused that.
5638 fn added_index(&self, track: usize, cue: usize) -> Option<usize> {
5639 let c = self.subtitles.get(track)?.cues.get(cue)?;
5640 self.cue_adds
5641 .iter()
5642 .position(|a| a.track == track && a.start_us == c.start_us && a.end_us == c.end_us)
5643 }
5644
5645 /// The file's index of cue `cue` of track `track`, which is not an added
5646 /// one. The cue overrides name cues by where the file has them, so a cue
5647 /// after a removed one keeps its index there while its position in the
5648 /// track moves down: this counts the file's cues before `cue` in the track
5649 /// (added ones have no file index), then walks the file past the removed
5650 /// ones to that survivor.
5651 fn original_cue_index(&self, track: usize, cue: usize) -> usize {
5652 let removed: Vec<usize> = self
5653 .cue_edits
5654 .iter()
5655 .filter(|(t, _, text)| *t == track && text.is_empty())
5656 .map(|(_, c, _)| *c)
5657 .collect();
5658 let before = self.subtitles[track]
5659 .cues
5660 .iter()
5661 .take(cue)
5662 .filter(|c| !self.cue_adds.iter().any(|a| a.track == track && a.start_us == c.start_us && a.end_us == c.end_us))
5663 .count();
5664 let (mut orig, mut seen) = (0usize, 0usize);
5665 loop {
5666 if !removed.contains(&orig) {
5667 if seen == before {
5668 return orig;
5669 }
5670 seen += 1;
5671 }
5672 orig += 1;
5673 }
5674 }
5675
5676 /// Keeps one override in the save list, replacing an earlier one for the
5677 /// same cue so a cue is written once however often it was retyped. `cue` is
5678 /// the file's index ([`original_cue_index`](Project::original_cue_index)).
5679 fn record_cue_edit(&mut self, track: usize, cue: usize, text: &str) {
5680 match self
5681 .cue_edits
5682 .iter_mut()
5683 .find(|(t, c, _)| *t == track && *c == cue)
5684 {
5685 Some(edit) => edit.2 = text.to_string(),
5686 None => self.cue_edits.push((track, cue, text.to_string())),
5687 }
5688 }
5689
5690 /// The cue overrides a save writes, `(track, cue, text)` each, the cue by
5691 /// its index in the file it came from; empty text is a cue removed -- see
5692 /// [`set_cue_text`](Project::set_cue_text) and [`delete_cue`](Project::delete_cue).
5693 pub fn cue_edits(&self) -> &[(usize, usize, String)] {
5694 &self.cue_edits
5695 }
5696
5697 /// The cues added to tracks ([`AddedCue`]), in the order they were added: what
5698 /// a save writes after [`cue_edits`](Project::cue_edits).
5699 pub fn cue_adds(&self) -> &[AddedCue] {
5700 &self.cue_adds
5701 }
5702
5703 /// Puts saved added cues back into their tracks, after the file's cues and
5704 /// the overrides ([`with_cue_edits`](Project::with_cue_edits)), each at its
5705 /// start. An added cue naming a track the file no longer has is kept, so a
5706 /// re-save does not lose it, and is not shown.
5707 pub fn with_cue_adds(mut self, adds: &[AddedCue]) -> Self {
5708 for a in adds {
5709 if let Some(t) = self.subtitles.get_mut(a.track) {
5710 let at = t.cues.partition_point(|c| c.start_us <= a.start_us);
5711 t.cues.insert(
5712 at,
5713 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() },
5714 );
5715 }
5716 self.cue_adds.push(a.clone());
5717 }
5718 self
5719 }
5720
5721 /// Puts saved cue overrides back over the tracks a load read -- the door a
5722 /// load uses, like [`with_subtitles`](Project::with_subtitles), and no undo
5723 /// step for the same reason. Retyped words go on first, then the removed
5724 /// cues come out, last index first, so each still names the file's cue. An
5725 /// override naming a track or cue the file no longer has is kept, so a
5726 /// re-save does not lose it, and changes nothing.
5727 pub fn with_cue_edits(mut self, edits: &[(usize, usize, String)]) -> Self {
5728 let mut removed: Vec<(usize, usize)> = Vec::new();
5729 for (track, cue, text) in edits {
5730 if text.is_empty() {
5731 removed.push((*track, *cue));
5732 } else if let Some(c) = self
5733 .subtitles
5734 .get_mut(*track)
5735 .and_then(|t| t.cues.get_mut(*cue))
5736 .filter(|c| c.image.is_none())
5737 {
5738 c.text = text.clone();
5739 }
5740 self.record_cue_edit(*track, *cue, text);
5741 }
5742 removed.sort_unstable_by(|a, b| b.cmp(a));
5743 removed.dedup();
5744 for (track, cue) in removed {
5745 if let Some(t) = self.subtitles.get_mut(track).filter(|t| cue < t.cues.len()) {
5746 t.cues.remove(cue);
5747 }
5748 }
5749 self
5750 }
5751
5752 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
5753 /// window of its track, clipped to that window and shifted to where the
5754 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
5755 /// carried through the picture's spans -- this is its twin for a track that
5756 /// is placed on a lane of its own, and it is what a preview draws and what
5757 /// an export of the lane would write.
5758 ///
5759 /// Cut, not stretched: a cue half inside the window keeps the half that is
5760 /// inside, and a cue wholly outside it is gone -- the same rule the media
5761 /// spans follow. `fps` is the timeline's rate, needed here because a
5762 /// placement's *position* is in frames while its words are in microseconds.
5763 ///
5764 /// Pure and cheap enough to ask per repaint (a walk of the placements and
5765 /// of their cues, no file opened), which is how a front-end asks it.
5766 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
5767 self.sub_lane_cue_spans(lane, fps)
5768 .into_iter()
5769 .filter_map(|s| {
5770 let cue = self.subtitles.get(s.track)?.cues.get(s.cue)?;
5771 Some(SubtitleCue {
5772 start_us: s.start_us,
5773 end_us: s.end_us,
5774 text: cue.text.clone(),
5775 image: cue.image.clone(),
5776 words: crate::subtitle::map_words(&cue.words, s.window, (s.start_us, s.end_us)),
5777 karaoke: crate::subtitle::map_karaoke(&cue.karaoke, s.window, (s.start_us, s.end_us)),
5778 })
5779 })
5780 .collect()
5781 }
5782
5783 /// [`sub_lane_cues`](Project::sub_lane_cues) with the cue each entry is: the
5784 /// same entries in the same order, as `(start_us, end_us, track, cue)`, so a
5785 /// front-end can hit-test a drawn cue and name the words it would edit
5786 /// ([`set_cue_text`](Project::set_cue_text)). Built by the same walk, so the
5787 /// two cannot disagree about which cue is where.
5788 pub fn sub_lane_cue_refs(&self, lane: Lane, fps: f64) -> Vec<(i64, i64, usize, usize)> {
5789 self.sub_lane_cue_spans(lane, fps)
5790 .into_iter()
5791 .map(|s| (s.start_us, s.end_us, s.track, s.cue))
5792 .collect()
5793 }
5794
5795 /// [`sub_lane_cue_refs`](Project::sub_lane_cue_refs) with the stretch of the cue's own clock
5796 /// each entry shows, which is what its words are moved by ([`crate::subtitle::map_words`]).
5797 pub fn sub_lane_cue_spans(&self, lane: Lane, fps: f64) -> Vec<CueSpan> {
5798 // A hidden lane has no cues at all: the screen draws none and the
5799 // export writes no track for it (its empty cue list is what drops it).
5800 if !(fps.is_finite() && fps > 0.0) || self.lane_hidden(lane) {
5801 return Vec::new();
5802 }
5803 let mut out = Vec::new();
5804 for s in self.sub_lane(lane) {
5805 let Some(track) = self.subtitles.get(s.track) else {
5806 // A placement whose track was taken off the palette
5807 // ([`Project::remove_subtitles`]) shows nothing rather than
5808 // showing another track's words.
5809 continue;
5810 };
5811 // Where the placement's own first microsecond lands on the
5812 // timeline, and how many microseconds of timeline one microsecond
5813 // of the window is worth: the placement's own proportion, which a
5814 // group's re-rate changes (the frames compress, the window does
5815 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
5816 // every cue lands where it always did; at 2x the words cross the
5817 // screen in half the time, cue for cue.
5818 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
5819 let onto = |t: i64| {
5820 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
5821 };
5822 for (i, cue) in track.cues.iter().enumerate() {
5823 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
5824 if b <= a {
5825 continue; // wholly outside the window this placement keeps
5826 }
5827 let (from, to) = (onto(a), onto(b));
5828 // Frames the cue keeps on the timeline (the +1 is the microsecond
5829 // rounding gives back).
5830 let kept = ((to - from) as f64 + 1.0) * fps / 1e6;
5831 // Shorter than one timeline frame: a timeline cannot show it. A
5832 // cue a window edge shortened (a cut met it, or a trim) is also
5833 // a sliver under [`CUT_SLIVER_FRAMES`]: the words a cut leaves
5834 // at the very edge of a cue flash past too quickly to read, so
5835 // they are not a cue. A cue short in the file itself keeps the
5836 // one-frame floor, as it always had.
5837 let clipped = a != cue.start_us || b != cue.end_us;
5838 if kept < 1.0 || (clipped && kept < CUT_SLIVER_FRAMES) {
5839 continue;
5840 }
5841 out.push(CueSpan { start_us: from, end_us: to, track: s.track, cue: i, window: (a, b) });
5842 }
5843 }
5844 // The placements come in timeline order, but two lanes' worth (or a
5845 // track whose cues a window reordered) do not.
5846 out.sort_by_key(|c| c.start_us);
5847 out
5848 }
5849
5850 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
5851 /// lanes is multiplied by on its way into the mix: the same lanes in the
5852 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
5853 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
5854 /// the bit-exact path.
5855 ///
5856 /// A muted lane is `0.0`: silence in the same sum, so the mix, the single
5857 /// stream test ([`AudioSession::is_mixed`]) and the export all see the one
5858 /// answer. Its clips and its volume are left as they are.
5859 pub fn audio_gains(&self) -> Vec<f32> {
5860 self.audio_lanes()
5861 .into_iter()
5862 .map(|lane| match self.lane_muted(lane) {
5863 true => 0.0,
5864 false => db_to_linear(self.lane_gain_db(lane)),
5865 })
5866 .collect()
5867 }
5868
5869 /// The ducks, in the same order and as long as
5870 /// [`audio_gains`](Project::audio_gains): what the mixer reads beside the
5871 /// gains. A duck names its key by the key's [`Lane::ord`], which is stable
5872 /// while lanes are emptied and refilled; here it is rewritten to the key's
5873 /// position in the mix, and dropped when that key is not in the mix at all
5874 /// (an empty audio lane is not one), which leaves the lane unducked rather
5875 /// than ducked under silence it could not hear.
5876 pub fn audio_ducks(&self) -> Vec<Vec<Duck>> {
5877 let mixed = self.audio_lanes();
5878 mixed
5879 .iter()
5880 .map(|&lane| {
5881 self.lane_duck_list(lane)
5882 .into_iter()
5883 .filter_map(|duck| {
5884 let key = Lane::new(LaneKind::Audio, duck.under);
5885 let at = mixed.iter().position(|&l| l == key)?;
5886 Some(Duck { under: at, ..duck })
5887 })
5888 .collect()
5889 })
5890 .collect()
5891 }
5892
5893 /// The voice processors, in the same order and as long as
5894 /// [`audio_gains`](Project::audio_gains): what the mix opens each lane
5895 /// through. All off for a project nobody has cleaned, which is the path
5896 /// that decodes the same samples it always did.
5897 pub fn audio_voices(&self) -> Vec<VoiceFx> {
5898 self.audio_lanes()
5899 .into_iter()
5900 .map(|lane| self.lane_voice(lane))
5901 .collect()
5902 }
5903
5904 /// The master limiter the mix is summed through. A project setting, not a
5905 /// clip's and not a lane's: there is one mix.
5906 pub fn limiter(&self) -> Limiter {
5907 self.settings.limiter
5908 }
5909
5910 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
5911 /// for a setting already in force. One undo step like every other
5912 /// project-setting pick.
5913 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
5914 let limiter = limiter.with_ceiling(limiter.ceiling_db);
5915 if self.settings.limiter == limiter {
5916 return false;
5917 }
5918 self.snapshot();
5919 self.settings.limiter = limiter;
5920 true
5921 }
5922
5923 /// What the clip at `idx` of `lane` plays through, or `None` for one that
5924 /// plays flat (and for an index that is not there) -- what a feeder and an
5925 /// export ask before they build an [`crate::eq::EqState`].
5926 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
5927 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
5928 }
5929
5930 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
5931 /// take them off. One undo step, like every other edit. `false` -- and no
5932 /// history -- for an index that is not there and for params holding a value
5933 /// that is not finite, which is the one thing the file format could not
5934 /// write and read back.
5935 ///
5936 /// Settings equal to ones already in the table share their entry, so a
5937 /// project that puts the same curve on twenty clips writes it once.
5938 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
5939 if idx >= self.lane(lane).len() {
5940 return false;
5941 }
5942 let slot = match params {
5943 None => None,
5944 Some(params) => {
5945 if !finite(&params) {
5946 return false;
5947 }
5948 Some(match self.eq.iter().position(|p| *p == params) {
5949 Some(at) => at as u16,
5950 // corner-cut: the table is append-only within a session (see
5951 // the module docs) and `Clip::eq` is a u16, so the 65535th
5952 // *distinct* setting of one session is refused rather than
5953 // silently aliased. Upgrade path if a UI ever drags a slider
5954 // that far: widen `Clip::eq` to u32 (Clip has the room) or
5955 // snapshot the table into the history and compact it here.
5956 None if self.eq.len() >= usize::from(u16::MAX) => return false,
5957 None => {
5958 self.eq.push(params);
5959 (self.eq.len() - 1) as u16
5960 }
5961 })
5962 }
5963 };
5964 self.snapshot();
5965 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
5966 true
5967 }
5968
5969 /// The clip's own gain in dB ([`Clip::gain_db`]) at `idx` of `lane`, or
5970 /// `None` for an index that is not there. `0.0` is unity.
5971 pub fn clip_gain(&self, lane: Lane, idx: usize) -> Option<f32> {
5972 self.lane(lane).get(idx).map(|c| c.gain_db)
5973 }
5974
5975 /// Give the clip at `idx` of `lane` this gain in dB, clamped to
5976 /// [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. One undo step, like every
5977 /// other edit. `false` -- and no history -- for an index that is not there,
5978 /// a value that is not finite, a video lane (a picture has no volume of its
5979 /// own to set: the gain is on the audio clip the take was split into, not
5980 /// relayed to it), or a value already set exactly so.
5981 pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
5982 if lane.kind != LaneKind::Audio || !db.is_finite() {
5983 return false;
5984 }
5985 let Some(current) = self.lane(lane).get(idx).map(|c| c.gain_db) else {
5986 return false;
5987 };
5988 let db = db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
5989 if current == db {
5990 return false;
5991 }
5992 self.snapshot();
5993 self.lane_mut(lane).expect("checked above")[idx].gain_db = db;
5994 true
5995 }
5996
5997 /// The clip's pan ([`Clip::pan`]) at `idx` of `lane`, or `None` for an index that is not there.
5998 pub fn clip_pan(&self, lane: Lane, idx: usize) -> Option<f32> {
5999 self.lane(lane).get(idx).map(Clip::pan_value)
6000 }
6001
6002 /// Give the clip at `idx` of `lane` this pan, clamped to `-1.0..=1.0`. One undo step.
6003 /// `false` -- and no history -- for an index that is not there, a value that is not
6004 /// finite, a non-audio lane, or a value already set.
6005 pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool {
6006 if lane.kind != LaneKind::Audio || !pan.is_finite() {
6007 return false;
6008 }
6009 let Some(current) = self.lane(lane).get(idx).map(|c| c.pan) else {
6010 return false;
6011 };
6012 let pan = (pan.clamp(-1.0, 1.0) * 100.0).round() as i8;
6013 if current == pan {
6014 return false;
6015 }
6016 self.snapshot();
6017 self.lane_mut(lane).expect("checked above")[idx].pan = pan;
6018 true
6019 }
6020
6021 /// Give the clip at `idx` of `lane` this pitch in semitones, clamped to `-12..=12`.
6022 /// One undo step. `false` -- and no history -- for an index that is not there, a
6023 /// non-audio lane, or a value already set.
6024 pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
6025 if lane.kind != LaneKind::Audio {
6026 return false;
6027 }
6028 let Some(current) = self.lane(lane).get(idx).map(|c| c.pitch) else {
6029 return false;
6030 };
6031 let semitones = semitones.clamp(i32::from(MIN_CLIP_PITCH), i32::from(MAX_CLIP_PITCH)) as i8;
6032 if current == semitones {
6033 return false;
6034 }
6035 self.snapshot();
6036 self.lane_mut(lane).expect("checked above")[idx].pitch = semitones;
6037 true
6038 }
6039
6040 /// The pitch in semitones of the clip at `idx` of `lane`, or `None` for an index that
6041 /// is not there.
6042 pub fn clip_pitch(&self, lane: Lane, idx: usize) -> Option<i8> {
6043 self.lane(lane).get(idx).map(|c| c.pitch)
6044 }
6045
6046 /// The placement animation of the clip at `idx` of `lane`, sorted by source
6047 /// frame ([`Clip::transform_keys`]). Empty for no keys and for an index
6048 /// that is not there.
6049 pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[TransformKey] {
6050 self.lane(lane)
6051 .get(idx)
6052 .map_or(&[][..], |c| c.transform_keys.as_slice())
6053 }
6054
6055 /// Replace the whole placement animation of the clip at `idx` of `lane`; an
6056 /// empty list clears it back to [`Clip::transform`]. Sorted here, one undo
6057 /// step. `false` -- and no history -- for an audio lane, an index that is not
6058 /// there, more than [`MAX_TRANSFORM_KEYS`] keys, a key whose placement is not
6059 /// finite, two keys at one source frame, or a list already exactly so. An
6060 /// opacity is clamped to `0..=1`, as [`TransformParams::opacity`] requires.
6061 pub fn set_transform_keys(
6062 &mut self,
6063 lane: Lane,
6064 idx: usize,
6065 mut keys: Vec<TransformKey>,
6066 ) -> bool {
6067 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6068 return false;
6069 }
6070 if keys.iter().any(|k| !transform_finite(&k.params)) {
6071 return false;
6072 }
6073 keys.sort_by_key(|k| k.at);
6074 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6075 return false;
6076 }
6077 for k in &mut keys {
6078 k.params.opacity = k.params.opacity.clamp(0.0, 1.0);
6079 }
6080 let Some(current) = self.lane(lane).get(idx).map(|c| &c.transform_keys) else {
6081 return false;
6082 };
6083 if *current == keys {
6084 return false;
6085 }
6086 self.snapshot();
6087 self.lane_mut(lane).expect("checked above")[idx].transform_keys = keys;
6088 true
6089 }
6090
6091 /// The opacity animation of the clip at `idx` of `lane`, sorted by source
6092 /// frame ([`Clip::opacity_keys`]). Empty for no keys and for an index that
6093 /// is not there.
6094 pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[OpacityKey] {
6095 self.lane(lane)
6096 .get(idx)
6097 .map_or(&[][..], |c| c.opacity_keys.as_slice())
6098 }
6099
6100 /// Replace the whole opacity animation of the clip at `idx` of `lane`; an
6101 /// empty list clears it. Sorted here, one undo step; opacities are clamped to
6102 /// `0..=1`. `false` -- and no history -- for an audio lane, an index that is
6103 /// not there, more than [`MAX_TRANSFORM_KEYS`] keys, a non-finite opacity, two
6104 /// keys at one source frame, or a list already exactly so.
6105 pub fn set_opacity_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<OpacityKey>) -> bool {
6106 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6107 return false;
6108 }
6109 if keys.iter().any(|k| !k.opacity.is_finite()) {
6110 return false;
6111 }
6112 keys.sort_by_key(|k| k.at);
6113 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6114 return false;
6115 }
6116 for k in &mut keys {
6117 k.opacity = k.opacity.clamp(0.0, 1.0);
6118 }
6119 let Some(current) = self.lane(lane).get(idx).map(|c| &c.opacity_keys) else {
6120 return false;
6121 };
6122 if *current == keys {
6123 return false;
6124 }
6125 self.snapshot();
6126 self.lane_mut(lane).expect("checked above")[idx].opacity_keys = keys;
6127 true
6128 }
6129
6130 /// The colour animation of the clip at `idx` of `lane`, sorted by source
6131 /// frame ([`Clip::color_keys`]). Empty for no keys and for an index that is
6132 /// not there.
6133 pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[ColorKey] {
6134 self.lane(lane)
6135 .get(idx)
6136 .map_or(&[][..], |c| c.color_keys.as_slice())
6137 }
6138
6139 /// The effects stack of the clip at `idx` of `lane` ([`Clip::effects`]).
6140 /// Empty for none and for an index that is not there.
6141 pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] {
6142 self.lane(lane).get(idx).map_or(&[], |c| &c.effects)
6143 }
6144
6145 /// Replaces the effects stack of the clip at `idx` of `lane` (an empty list
6146 /// clears it), each effect's values clamped into range. One undo step; `false`
6147 /// for a lane that is not a video lane, a clip that is not there, more than
6148 /// [`crate::effects::MAX_EFFECTS`] effects, and a stack equal to the current one.
6149 pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool {
6150 if lane.kind != LaneKind::Video || effects.len() > crate::effects::MAX_EFFECTS {
6151 return false;
6152 }
6153 let effects: Vec<_> = effects.into_iter().map(crate::effects::Effect::clamped).collect();
6154 let Some(current) = self.lane(lane).get(idx).map(|c| &c.effects) else {
6155 return false;
6156 };
6157 if *current == effects {
6158 return false;
6159 }
6160 self.snapshot();
6161 self.lane_mut(lane).expect("checked above")[idx].effects = effects;
6162 true
6163 }
6164
6165 /// The keys of the effect at stack position `slot` of the clip at `idx` of `lane`
6166 /// ([`crate::effects::Effect::keys`]); empty for an effect with none.
6167 pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] {
6168 self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)).map_or(&[], |e| &e.keys)
6169 }
6170
6171 /// Replaces the keys of the effect at stack position `slot` of the clip at `idx` of
6172 /// `lane`; an empty list clears them. Keys are source-frame keyed and sorted here with
6173 /// no two alike. Each value is clamped into its parameter's range, a parameter that is
6174 /// not keyable (a switch or a choice) takes the effect's static value, and the unused
6175 /// tail is zeroed. Refused for a clip that is not a picture clip on a video lane, more
6176 /// than [`MAX_TRANSFORM_KEYS`] keys, a non-finite value, or a list equal to the current
6177 /// one. One undo step.
6178 pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, mut keys: Vec<crate::effects::EffectKey>) -> bool {
6179 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6180 return false;
6181 }
6182 keys.sort_by_key(|k| k.at);
6183 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6184 return false;
6185 }
6186 let Some(current) = self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)) else {
6187 return false;
6188 };
6189 let specs = current.kind.params();
6190 if keys.iter().any(|k| k.values[..specs.len()].iter().any(|v| !v.is_finite())) {
6191 return false;
6192 }
6193 for k in &mut keys {
6194 for (i, v) in k.values.iter_mut().enumerate() {
6195 *v = match specs.get(i) {
6196 Some(s) if s.keyable() => v.clamp(s.min, s.max),
6197 Some(_) => current.values[i],
6198 None => 0.0,
6199 };
6200 }
6201 }
6202 if current.keys == keys {
6203 return false;
6204 }
6205 self.snapshot();
6206 self.lane_mut(lane).expect("checked above")[idx].effects[slot].keys = keys;
6207 true
6208 }
6209
6210 /// Replace the whole colour animation of the clip at `idx` of `lane`; an
6211 /// empty list clears it. Sorted here, one undo step; each field is clamped to
6212 /// its range (brightness and tint `-1..=1`, contrast and saturation `0..=2`).
6213 /// `false` -- and no history -- for an audio lane, an index that is not there,
6214 /// more than [`MAX_COLOR_KEYS`] keys, a non-finite value, two keys at one
6215 /// source frame, or a list already exactly so.
6216 pub fn set_color_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<ColorKey>) -> bool {
6217 if lane.kind != LaneKind::Video || keys.len() > MAX_COLOR_KEYS {
6218 return false;
6219 }
6220 if keys.iter().any(|k| !color_finite(&k.params)) {
6221 return false;
6222 }
6223 keys.sort_by_key(|k| k.at);
6224 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6225 return false;
6226 }
6227 for k in &mut keys {
6228 let p = &mut k.params;
6229 p.brightness = p.brightness.clamp(-1.0, 1.0);
6230 p.contrast = p.contrast.clamp(0.0, 2.0);
6231 p.saturation = p.saturation.clamp(0.0, 2.0);
6232 p.tint = p.tint.clamp(-1.0, 1.0);
6233 }
6234 let Some(current) = self.lane(lane).get(idx).map(|c| &c.color_keys) else {
6235 return false;
6236 };
6237 if *current == keys {
6238 return false;
6239 }
6240 self.snapshot();
6241 self.lane_mut(lane).expect("checked above")[idx].color_keys = keys;
6242 true
6243 }
6244
6245 /// The source frame the keys of the clip at `idx` of `lane` are read at for
6246 /// timeline `frame`, rounded to the nearest whole frame: where a key set "at
6247 /// the playhead" lands. `None` for an index that is not there, a frame
6248 /// outside the clip and a lane that is not a video lane.
6249 pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> {
6250 let c = self.lane(lane).get(idx)?;
6251 if lane.kind != LaneKind::Video || timeline_frame < c.start || timeline_frame >= c.end() {
6252 return None;
6253 }
6254 Some(key_pos(c, timeline_frame).round() as u32)
6255 }
6256
6257 /// Whether the clip has any key of `kind` at all.
6258 pub fn is_keyed(&self, lane: Lane, idx: usize, kind: KeyKind) -> bool {
6259 self.lane(lane).get(idx).is_some_and(|c| match kind {
6260 KeyKind::Placement => !c.transform_keys.is_empty(),
6261 KeyKind::Opacity => !c.opacity_keys.is_empty(),
6262 KeyKind::Color => !c.color_keys.is_empty(),
6263 })
6264 }
6265
6266 /// The ease of the key of `kind` that sits exactly on timeline `frame`
6267 /// ([`key_source_frame`](Self::key_source_frame)), `None` with no key there.
6268 pub fn key_ease_at(&self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32) -> Option<KeyEase> {
6269 let at = self.key_source_frame(lane, idx, timeline_frame)?;
6270 let c = self.lane(lane).get(idx)?;
6271 match kind {
6272 KeyKind::Placement => c.transform_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6273 KeyKind::Opacity => c.opacity_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6274 KeyKind::Color => c.color_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6275 }
6276 }
6277
6278 /// The stopwatch: puts a key of `kind` on timeline `frame` holding the value the
6279 /// clip shows there (so the picture does not change), or takes the key that is
6280 /// there off. `Some(true)` for a key added, `Some(false)` for one removed, `None`
6281 /// -- and no history -- where no key can go (see
6282 /// [`key_source_frame`](Self::key_source_frame)) or the keys are full. One undo
6283 /// step. Removing the last key puts the clip back on its single value.
6284 pub fn toggle_key(&mut self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32) -> Option<bool> {
6285 let at = self.key_source_frame(lane, idx, timeline_frame)?;
6286 let had = self.key_ease_at(lane, idx, kind, timeline_frame).is_some();
6287 let c = self.lane(lane).get(idx)?.clone();
6288 let ok = match kind {
6289 KeyKind::Placement => {
6290 let mut keys = c.transform_keys.clone();
6291 if had {
6292 keys.retain(|k| k.at != at);
6293 } else {
6294 let params = self.transform_at(lane, idx, timeline_frame).unwrap_or_default();
6295 keys.push(TransformKey { at, params, ease: KeyEase::Linear });
6296 }
6297 self.set_transform_keys(lane, idx, keys)
6298 }
6299 KeyKind::Opacity => {
6300 let mut keys = c.opacity_keys.clone();
6301 if had {
6302 keys.retain(|k| k.at != at);
6303 } else {
6304 let opacity = self.opacity_at(lane, idx, timeline_frame);
6305 keys.push(OpacityKey { at, opacity, ease: KeyEase::Linear });
6306 }
6307 self.set_opacity_keys(lane, idx, keys)
6308 }
6309 KeyKind::Color => {
6310 let mut keys = c.color_keys.clone();
6311 if had {
6312 keys.retain(|k| k.at != at);
6313 } else {
6314 let params = self.color_at(lane, idx, timeline_frame).unwrap_or_default();
6315 keys.push(ColorKey { at, params, ease: KeyEase::Linear });
6316 }
6317 self.set_color_keys(lane, idx, keys)
6318 }
6319 };
6320 ok.then_some(!had)
6321 }
6322
6323 /// Sets the ease of the key of `kind` on timeline `frame`. `false` -- and no
6324 /// history -- with no key there or one already so. One undo step.
6325 pub fn set_key_ease_at(&mut self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32, ease: KeyEase) -> bool {
6326 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6327 return false;
6328 };
6329 if self.key_ease_at(lane, idx, kind, timeline_frame).is_none_or(|e| e == ease) {
6330 return false;
6331 }
6332 let Some(c) = self.lane(lane).get(idx) else {
6333 return false;
6334 };
6335 match kind {
6336 KeyKind::Placement => {
6337 let mut keys = c.transform_keys.clone();
6338 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6339 self.set_transform_keys(lane, idx, keys)
6340 }
6341 KeyKind::Opacity => {
6342 let mut keys = c.opacity_keys.clone();
6343 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6344 self.set_opacity_keys(lane, idx, keys)
6345 }
6346 KeyKind::Color => {
6347 let mut keys = c.color_keys.clone();
6348 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6349 self.set_color_keys(lane, idx, keys)
6350 }
6351 }
6352 }
6353
6354 /// Writes `keys` as the clip's keys of one kind with the undo step only when
6355 /// `snapshot`: the shape of a drag, whose first sample is a step and the
6356 /// rest are not. The lists were validated by the caller.
6357 fn put_key<K: Keyed>(
6358 &mut self,
6359 lane: Lane,
6360 idx: usize,
6361 snapshot: bool,
6362 key: K,
6363 slot: impl Fn(&mut Clip) -> &mut Vec<K>,
6364 ) -> bool {
6365 if lane.kind != LaneKind::Video {
6366 return false;
6367 }
6368 let Some(clip) = self.lane_mut(lane).and_then(|c| c.get_mut(idx)) else {
6369 return false;
6370 };
6371 let mut keys = slot(clip).clone();
6372 match keys.iter_mut().find(|k| k.at() == key.at()) {
6373 Some(k) => *k = key.placed(key.at(), k.ease()),
6374 None => {
6375 keys.push(key);
6376 keys.sort_by_key(|k| k.at());
6377 }
6378 }
6379 if keys.len() > MAX_TRANSFORM_KEYS {
6380 return false;
6381 }
6382 if snapshot {
6383 self.snapshot();
6384 }
6385 *slot(&mut self.lane_mut(lane).expect("checked")[idx]) = keys;
6386 true
6387 }
6388
6389 /// Sets the placement at timeline `frame` as a key there: a new key, or the
6390 /// existing key's value with its ease kept. The write a slider makes on a clip
6391 /// whose placement is keyed. `snapshot` is the undo step
6392 /// ([`set_transform_live`](Self::set_transform_live)'s rule). `false` where no
6393 /// key can go ([`key_source_frame`](Self::key_source_frame)) or a value is not finite.
6394 pub fn put_transform_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, params: TransformParams, snapshot: bool) -> bool {
6395 self.flat.clear();
6396 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6397 return false;
6398 };
6399 if !transform_finite(&params) {
6400 return false;
6401 }
6402 let params = TransformParams { opacity: params.opacity.clamp(0.0, 1.0), ..params };
6403 self.put_key(lane, idx, snapshot, TransformKey { at, params, ease: KeyEase::Linear }, |c| &mut c.transform_keys)
6404 }
6405
6406 /// [`put_transform_key_at`](Self::put_transform_key_at) for the opacity.
6407 pub fn put_opacity_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, opacity: f32, snapshot: bool) -> bool {
6408 self.flat.clear();
6409 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6410 return false;
6411 };
6412 if !opacity.is_finite() {
6413 return false;
6414 }
6415 let opacity = opacity.clamp(0.0, 1.0);
6416 self.put_key(lane, idx, snapshot, OpacityKey { at, opacity, ease: KeyEase::Linear }, |c| &mut c.opacity_keys)
6417 }
6418
6419 /// [`put_transform_key_at`](Self::put_transform_key_at) for the grade.
6420 pub fn put_color_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, params: ColorParams, snapshot: bool) -> bool {
6421 self.flat.clear();
6422 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6423 return false;
6424 };
6425 if !color_finite(&params) {
6426 return false;
6427 }
6428 let params = ColorParams {
6429 brightness: params.brightness.clamp(-1.0, 1.0),
6430 contrast: params.contrast.clamp(0.0, 2.0),
6431 saturation: params.saturation.clamp(0.0, 2.0),
6432 tint: params.tint.clamp(-1.0, 1.0),
6433 // Keys animate the sliders; the look is the clip's base grade's.
6434 look: crate::color::Look::default(),
6435 };
6436 self.put_key(lane, idx, snapshot, ColorKey { at, params, ease: KeyEase::Linear }, |c| &mut c.color_keys)
6437 }
6438
6439 /// The grade the clip at `idx` of `lane` shows at timeline `frame`: its
6440 /// colour keys evaluated at the source frame that frame plays, or its single
6441 /// grade when it has none. `None` for an index that is not there or a clip
6442 /// with no grade at all and no keys.
6443 pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> {
6444 let c = self.lane(lane).get(idx)?;
6445 if c.color_keys.is_empty() {
6446 return self.color_of(lane, idx).copied();
6447 }
6448 Some(clip_color_at(c, self.color_of(lane, idx).copied().unwrap_or_default(), timeline_frame))
6449 }
6450
6451 /// The opacity the clip at `idx` of `lane` shows at timeline `frame`, the
6452 /// fades not counted: its opacity keys evaluated at the source frame that
6453 /// frame plays, else its placement's (keyed or not). `1.0` for an index
6454 /// that is not there.
6455 pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 {
6456 let Some(c) = self.lane(lane).get(idx) else {
6457 return 1.0;
6458 };
6459 let base = self
6460 .transform_at(lane, idx, timeline_frame)
6461 .map_or(1.0, |t| t.opacity);
6462 clip_opacity_at(c, base, timeline_frame)
6463 }
6464
6465 /// The placement the clip at `idx` of `lane` shows at timeline `frame`: its
6466 /// keys evaluated at the source frame that frame plays
6467 /// ([`keyed_transform`]), or its single [`Clip::transform`] when it has no
6468 /// keys. `None` for an index that is not there or a clip with no
6469 /// transform at all, which is the identity.
6470 pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> {
6471 let c = self.lane(lane).get(idx)?;
6472 if c.transform_keys.is_empty() {
6473 return self.transform_of(lane, idx).copied();
6474 }
6475 Some(clip_transform_at(c, self.transform_of(lane, idx).copied().unwrap_or_default(), timeline_frame))
6476 }
6477
6478 /// The volume envelope of the clip at `idx` of `lane`, sorted by source
6479 /// frame ([`Clip::gain_keys`]). Empty for a clip with no points, and for an
6480 /// index that is not there.
6481 pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] {
6482 self.lane(lane)
6483 .get(idx)
6484 .map_or(&[][..], |c| c.gain_keys.as_slice())
6485 }
6486
6487 /// Replace the whole volume envelope of the clip at `idx` of `lane`; an
6488 /// empty list clears it. The points are sorted here, and each dB is clamped
6489 /// to [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. One undo step.
6490 ///
6491 /// `false` -- and no history -- for a video lane, an index that is not
6492 /// there, more than [`MAX_GAIN_KEYS`] points, a point that is not finite,
6493 /// two points at one source frame, or an envelope already exactly so.
6494 pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<GainKey>) -> bool {
6495 if lane.kind != LaneKind::Audio || keys.len() > MAX_GAIN_KEYS {
6496 return false;
6497 }
6498 if keys.iter().any(|k| !k.db.is_finite()) {
6499 return false;
6500 }
6501 keys.sort_by_key(|k| k.at);
6502 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6503 return false;
6504 }
6505 for k in &mut keys {
6506 k.db = k.db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
6507 }
6508 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6509 return false;
6510 };
6511 if *current == keys {
6512 return false;
6513 }
6514 self.snapshot();
6515 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6516 true
6517 }
6518
6519 /// Put one point into the volume envelope of the clip at `idx` of `lane`:
6520 /// it replaces the point already at `key.at`, or is added in source order.
6521 /// The dB is clamped as [`set_gain_keys`](Self::set_gain_keys) clamps it.
6522 /// One undo step.
6523 ///
6524 /// `false` -- and no history -- for a video lane, an index that is not
6525 /// there, a dB that is not finite, a new point past
6526 /// [`MAX_GAIN_KEYS`], or a point already exactly as it is.
6527 pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool {
6528 if lane.kind != LaneKind::Audio || !key.db.is_finite() {
6529 return false;
6530 }
6531 let key = GainKey {
6532 db: key.db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB),
6533 ..key
6534 };
6535 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6536 return false;
6537 };
6538 let mut keys = current.clone();
6539 match keys.binary_search_by_key(&key.at, |k| k.at) {
6540 Ok(at) => {
6541 if keys[at] == key {
6542 return false;
6543 }
6544 keys[at] = key;
6545 }
6546 Err(at) => {
6547 if keys.len() >= MAX_GAIN_KEYS {
6548 return false;
6549 }
6550 keys.insert(at, key);
6551 }
6552 }
6553 self.snapshot();
6554 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6555 true
6556 }
6557
6558 /// Take the point at source frame `at` out of the volume envelope of the
6559 /// clip at `idx` of `lane`. One undo step.
6560 ///
6561 /// `false` -- and no history -- for a video lane, an index that is not
6562 /// there, or no point at `at`.
6563 pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool {
6564 if lane.kind != LaneKind::Audio {
6565 return false;
6566 }
6567 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6568 return false;
6569 };
6570 let Ok(pos) = current.binary_search_by_key(&at, |k| k.at) else {
6571 return false;
6572 };
6573 let mut keys = current.clone();
6574 keys.remove(pos);
6575 self.snapshot();
6576 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6577 true
6578 }
6579
6580 /// The envelope's effective dB at timeline frame `timeline_frame` of the
6581 /// clip at `idx` of `lane`: its [`Clip::gain_db`] plus its keyed envelope
6582 /// at the source frame that timeline frame plays. The fades are not in it.
6583 /// `None` for a video lane or an index that is not there. Timeline frames
6584 /// before the clip read as its first frame.
6585 pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> {
6586 if lane.kind != LaneKind::Audio {
6587 return None;
6588 }
6589 let c = self.lane(lane).get(idx)?;
6590 Some(c.gain_db + gain_keys_db_at(&c.gain_keys, key_pos(c, timeline_frame)))
6591 }
6592
6593 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
6594 /// ungraded (and for an index that is not there) -- what the renderer and
6595 /// the export ask before they call [`crate::color::apply_yuv`].
6596 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
6597 self.color
6598 .get(usize::from(self.lane(lane).get(idx)?.color?))
6599 }
6600
6601 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
6602 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
6603 /// (and no history) for an index that is not there or a value that is not
6604 /// finite, and equal settings share a table entry.
6605 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
6606 self.write_color(lane, idx, params, true)
6607 }
6608
6609 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
6610 /// one pointer drag, whose first write (a plain `set_color`) already took the
6611 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
6612 /// not one per pixel -- and undoing it lands where the hand picked it up.
6613 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
6614 self.flat.clear();
6615 self.write_color(lane, idx, params, false)
6616 }
6617
6618 fn write_color(
6619 &mut self,
6620 lane: Lane,
6621 idx: usize,
6622 params: Option<ColorParams>,
6623 snapshot: bool,
6624 ) -> bool {
6625 if idx >= self.lane(lane).len() {
6626 return false;
6627 }
6628 let slot = match params {
6629 None => None,
6630 Some(params) => {
6631 if !color_finite(&params) {
6632 return false;
6633 }
6634 Some(match self.color.iter().position(|p| *p == params) {
6635 Some(at) => at as u16,
6636 // corner-cut: the 65535th *distinct* grade of one session is
6637 // refused rather than silently aliased, exactly as `set_eq`
6638 // refuses the 65535th curve; same upgrade path.
6639 None if self.color.len() >= usize::from(u16::MAX) => return false,
6640 None => {
6641 self.color.push(params);
6642 (self.color.len() - 1) as u16
6643 }
6644 })
6645 }
6646 };
6647 if snapshot {
6648 self.snapshot();
6649 }
6650 self.lane_mut(lane).expect("checked above")[idx].color = slot;
6651 true
6652 }
6653
6654 /// Every `.cube` file a clip's grade names, each once, in table order.
6655 pub fn luts(&self) -> Vec<crate::cube::LutRef> {
6656 let used: std::collections::HashSet<u16> =
6657 self.lanes.iter().flat_map(|l| l.clips.iter().filter_map(|c| c.color)).collect();
6658 let mut out = Vec::new();
6659 for (i, p) in self.color.iter().enumerate() {
6660 if let Some(r) = p.look.lut
6661 && used.contains(&(i as u16))
6662 && !out.contains(&r)
6663 {
6664 out.push(r);
6665 }
6666 }
6667 out
6668 }
6669
6670 /// The `.cube` files clips name that cannot be used, and why -- a missing
6671 /// file or a malformed one. Such a clip plays and exports without its LUT
6672 /// (the rest of its grade still applies); this is the warning that says so.
6673 pub fn lut_problems(&self) -> Vec<(PathBuf, String)> {
6674 self.luts().into_iter().filter_map(|r| r.problem().map(|e| (r.path(), e))).collect()
6675 }
6676
6677 /// Points every clip whose grade names the `.cube` file at `from` to `to`
6678 /// instead (re-reading `to` even if it is the same path, so an edited file is
6679 /// picked up). One undo step; the number of clips changed, 0 (and no history)
6680 /// when none names `from`. The colour table only grows, as every grade edit
6681 /// leaves it: the clips are re-pointed, which is what undo restores.
6682 pub fn relink_lut(&mut self, from: &Path, to: &Path) -> usize {
6683 let named = |p: &ColorParams| p.look.lut.is_some_and(|r| r.path() == from);
6684 let hits: Vec<(usize, usize)> = self
6685 .lanes
6686 .iter()
6687 .enumerate()
6688 .flat_map(|(l, lane)| {
6689 lane.clips.iter().enumerate().filter_map(move |(i, c)| c.color.map(|slot| (l, i, slot)))
6690 })
6691 .filter(|&(_, _, slot)| self.color.get(usize::from(slot)).is_some_and(named))
6692 .map(|(l, i, _)| (l, i))
6693 .collect();
6694 if hits.is_empty() {
6695 return 0;
6696 }
6697 let fresh = crate::cube::LutRef::reload(to);
6698 self.snapshot();
6699 for &(l, i) in &hits {
6700 let slot = usize::from(self.lanes[l].clips[i].color.expect("graded"));
6701 let mut params = self.color[slot];
6702 params.look.lut = Some(fresh);
6703 let at = match self.color.iter().position(|p| *p == params) {
6704 Some(at) => at,
6705 None => {
6706 self.color.push(params);
6707 self.color.len() - 1
6708 }
6709 };
6710 self.lanes[l].clips[i].color = Some(at as u16);
6711 }
6712 hits.len()
6713 }
6714
6715 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
6716 /// policy's own placement (and for an index that is not there) -- what the
6717 /// renderer and the export ask before they place its picture.
6718 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
6719 self.transform
6720 .get(usize::from(self.lane(lane).get(idx)?.transform?))
6721 }
6722
6723 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
6724 /// step, `false` (and no history) for an index that is not there or a
6725 /// value that is not finite, and equal settings share a table entry.
6726 pub fn set_transform(
6727 &mut self,
6728 lane: Lane,
6729 idx: usize,
6730 params: Option<TransformParams>,
6731 ) -> bool {
6732 self.write_transform(lane, idx, params, true)
6733 }
6734
6735 /// [`set_transform`](Self::set_transform) without the undo step, for
6736 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
6737 /// one drag on a position/scale/rotate/crop control are one undo, not one
6738 /// per pixel.
6739 pub fn set_transform_live(
6740 &mut self,
6741 lane: Lane,
6742 idx: usize,
6743 params: Option<TransformParams>,
6744 ) -> bool {
6745 self.flat.clear();
6746 self.write_transform(lane, idx, params, false)
6747 }
6748
6749 fn write_transform(
6750 &mut self,
6751 lane: Lane,
6752 idx: usize,
6753 params: Option<TransformParams>,
6754 snapshot: bool,
6755 ) -> bool {
6756 if idx >= self.lane(lane).len() {
6757 return false;
6758 }
6759 let slot = match params {
6760 None => None,
6761 Some(params) => {
6762 if !transform_finite(&params) {
6763 return false;
6764 }
6765 Some(match self.transform.iter().position(|p| *p == params) {
6766 Some(at) => at as u16,
6767 // corner-cut: the 65535th *distinct* transform of one
6768 // session is refused rather than silently aliased,
6769 // exactly as `write_color` refuses the 65535th grade;
6770 // same upgrade path.
6771 None if self.transform.len() >= usize::from(u16::MAX) => return false,
6772 None => {
6773 self.transform.push(params);
6774 (self.transform.len() - 1) as u16
6775 }
6776 })
6777 }
6778 };
6779 if snapshot {
6780 self.snapshot();
6781 }
6782 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
6783 true
6784 }
6785
6786 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
6787 /// index that is not there, which is what every clip starts at anyway.
6788 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
6789 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
6790 }
6791
6792 /// Sets it, for the clip **and its whole group**: a link is one span on
6793 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
6794 /// from its sound would be a group no save could load. One snapshot, so the
6795 /// group's change is one [`Project::undo`].
6796 ///
6797 /// The source range is untouched -- a speed says how many timeline frames
6798 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
6799 /// split still address the file afterwards.
6800 ///
6801 /// Refused, changing nothing and costing no undo step, when the clip would
6802 /// grow into the one after it on its own lane: slowing a clip down makes it
6803 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
6804 /// the way -- by lane and timeline frame -- because "it did not fit" is not
6805 /// something a user can go and fix. Also for an index that is not there.
6806 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
6807 self.write_speed(lane, idx, speed, true)
6808 }
6809
6810 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
6811 /// one pointer drag, whose first write (a plain `set_speed`) already took the
6812 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
6813 /// not one per rate it passed through -- exactly as
6814 /// [`set_color_live`](Self::set_color_live) is for a slider.
6815 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
6816 self.write_speed(lane, idx, speed, false)
6817 }
6818
6819 /// Gives the clip at `idx` of `lane` (and the clips linked to it) a speed ramp
6820 /// `keys` ([`Clip::speed_keys`]); empty keys clear it, and the clip takes its
6821 /// constant [`Clip::speed`] again. Its source range stays, so its footprint is
6822 /// recomputed from the ramp. Nothing ripples: as a constant rate change, the new
6823 /// length must still fit before the next clip on its lane, or the edit is
6824 /// refused, and the caller is told how far it would have run.
6825 pub fn set_speed_ramp(&mut self, lane: Lane, idx: usize, keys: &[SpeedKey]) -> crate::Result<()> {
6826 if !keys.is_empty() && !valid_speed_keys(keys) {
6827 return Err("a speed ramp takes 1 to 8 keys, in strictly increasing frames".into());
6828 }
6829 let Some(members) = self.group_of(lane, idx) else {
6830 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6831 };
6832 if !members.subs.is_empty() {
6833 return Err("this clip is linked to captions, which a speed ramp cannot retime yet".into());
6834 }
6835 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6836 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6837 }
6838 let labels = handles(&self.lanes);
6839 for &(l, i) in &members.clips {
6840 let clips = &self.lanes[l].clips;
6841 let moved = Clip { speed_keys: keys.to_vec(), ..clips[i].clone() };
6842 if let Some(next) = clips.get(i + 1)
6843 && moved.end() > next.start
6844 {
6845 return Err(format!(
6846 "with that ramp the clip would run to frame {} and the next {} clip starts at {}: \
6847 move it along, or trim this one first",
6848 moved.end(),
6849 labels[l].label(),
6850 next.start
6851 )
6852 .into());
6853 }
6854 }
6855 self.snapshot();
6856 for (l, i) in members.clips {
6857 self.lanes[l].clips[i].speed_keys = keys.to_vec();
6858 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
6859 }
6860 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6861 Ok(())
6862 }
6863
6864 fn write_speed(
6865 &mut self,
6866 lane: Lane,
6867 idx: usize,
6868 speed: Speed,
6869 snapshot: bool,
6870 ) -> crate::Result<()> {
6871 let Some(members) = self.group_of(lane, idx) else {
6872 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6873 };
6874 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6875 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6876 }
6877 if self.lane(lane).get(idx).is_some_and(|c| !c.speed_keys.is_empty()) {
6878 return Err("this clip has a speed ramp: clear the ramp before setting a constant speed".into());
6879 }
6880 let labels = handles(&self.lanes);
6881 // The clip the hand is holding is the group's clock: everything else
6882 // in the group, caption members included, re-times by the ratio its new
6883 // rate gives its own frames. The clips take the rate itself; a caption
6884 // has none, so it takes the *ratio* -- its span on the timeline
6885 // compresses or stretches about the held clip's head, while the words
6886 // it reads keep their own timing ([`write_sub_edge`]'s law: the
6887 // timeline moves, the track does not).
6888 let Some(held) = self.lane(lane).get(idx).cloned() else {
6889 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6890 };
6891 // The same per-member piece `speeded_playhead` builds for this op,
6892 // asked here instead of read there -- a caption's length comes from
6893 // the map's own ends (`end - start`), never `round(len * ratio)`
6894 // separately, which is what let the two answers drift apart by a
6895 // frame.
6896 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
6897 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
6898 let retimed = |s: SubClip| {
6899 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
6900 let start = map.apply(s.start);
6901 let end = map.apply(s.end()).max(start.saturating_add(1));
6902 SubClip {
6903 start,
6904 frames: end - start,
6905 ..s
6906 }
6907 };
6908 for &(l, i) in &members.clips {
6909 let clips = &self.lanes[l].clips;
6910 let mut moved = clips[i].clone();
6911 moved.speed = speed;
6912 if let Some(next) = clips.get(i + 1)
6913 && moved.end() > next.start
6914 {
6915 let name = labels[l].label();
6916 return Err(format!(
6917 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
6918 move it along, or trim this one first",
6919 moved.end(),
6920 next.start
6921 )
6922 .into());
6923 }
6924 }
6925 // ...and the captions, against their own lanes' captions: a stretch
6926 // that runs one into its neighbour is refused for the clip arm's
6927 // reason -- a lane may not overlap itself -- and by name like it.
6928 let subs: Vec<(usize, usize, SubClip)> = members
6929 .subs
6930 .iter()
6931 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
6932 .collect();
6933 for &(l, i, moved) in &subs {
6934 for (j, other) in self.lanes[l].subs.iter().enumerate() {
6935 if j != i && moved.start < other.end() && other.start < moved.end() {
6936 return Err(format!(
6937 "at {speed} the {} caption at frame {} would run to frame {} and the next \
6938 starts at {}: move it along, or trim this one first",
6939 labels[l].label(),
6940 self.lanes[l].subs[i].start,
6941 moved.end(),
6942 other.start
6943 )
6944 .into());
6945 }
6946 }
6947 }
6948 if snapshot {
6949 self.snapshot();
6950 }
6951 for (l, i) in members.clips {
6952 self.lanes[l].clips[i].speed = speed;
6953 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
6954 }
6955 for (l, i, moved) in subs {
6956 self.lanes[l].subs[i] = moved;
6957 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
6958 }
6959 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6960 Ok(())
6961 }
6962
6963 /// Whether the clip at `idx` of `lane` plays backwards ([`Clip::reversed`]);
6964 /// `false` for an index that is not there.
6965 pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool {
6966 self.lane(lane).get(idx).is_some_and(|c| c.reversed)
6967 }
6968
6969 /// Plays the clip at `idx` of `lane` backwards (`on`) or forwards again, for the
6970 /// clip **and its whole group**, as [`set_speed`](Self::set_speed) does: a picture
6971 /// run backwards against its sound would be a take nobody recorded. One snapshot,
6972 /// so the group's change is one [`Project::undo`]. Nothing moves: a clip's
6973 /// footprint and window are the same either way, which is why this can never be
6974 /// refused for room.
6975 ///
6976 /// The keys read from the footage -- placement and volume points are source-keyed
6977 /// -- are mirrored across the window as the direction flips, so every animation
6978 /// still plays on the same timeline frames it did, and only the footage under it
6979 /// runs the other way. Flipping twice puts every key back on the frame it was on.
6980 ///
6981 /// Refused, changing nothing, for a still (it has no direction), and for an index
6982 /// that is not there. A group already in the asked state is `Ok` and costs no undo
6983 /// step.
6984 pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> {
6985 let Some(members) = self.group_of(lane, idx) else {
6986 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6987 };
6988 if members.clips.iter().any(|&(l, i)| self.is_still(&self.lanes[l].clips[i])) {
6989 return Err("a still picture has no direction to reverse".into());
6990 }
6991 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6992 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6993 }
6994 if members.clips.iter().all(|&(l, i)| self.lanes[l].clips[i].reversed == on) {
6995 return Ok(());
6996 }
6997 self.snapshot();
6998 for (l, i) in members.clips {
6999 let c = &mut self.lanes[l].clips[i];
7000 if c.reversed != on {
7001 c.reversed = on;
7002 mirror_keys(c);
7003 }
7004 }
7005 debug_assert!(links_are_consistent(&self.lanes).is_ok());
7006 Ok(())
7007 }
7008
7009 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
7010 /// playhead standing at `at` -- read off the geometry **before** the
7011 /// write, because the old ends are gone after it. The question a card
7012 /// asks as its bar moves: the picture under the cursor has to stay the
7013 /// picture under the cursor, or the scene changes with the rate.
7014 ///
7015 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
7016 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
7017 /// a clip member keeps its own start and re-fits its length at the new
7018 /// rate -- its **old** rate against the new one, which is what the bar's
7019 /// live samples ask about as much as a first press does; a caption
7020 /// member scales about the held clip's start by the held clip's own
7021 /// proportion; and a playhead outside every member's old extent stays
7022 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
7023 /// (or the room a stretch takes) absorbs the difference, not the
7024 /// playhead. `None` for an index that is not there.
7025 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
7026 // A ramped clip has no single rate to re-fit against: no answer, not a wrong one.
7027 if self.lane(lane).get(idx).is_some_and(|c| !c.speed_keys.is_empty()) {
7028 return None;
7029 }
7030 let members = self.group_of(lane, idx)?;
7031 let held = self.lane(lane).get(idx).cloned()?;
7032 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
7033 for &(l, i) in members.clips.iter().chain(&members.subs) {
7034 let (span, map) = match self.lanes[l]
7035 .clips
7036 .get(i)
7037 .filter(|_| members.clips.contains(&(l, i)))
7038 {
7039 // The clip's own span, re-fitted at its own old rate: one
7040 // piece of the map, anchored where the clip itself is. The
7041 // new length is the same *source* frames at the new rate --
7042 // len divided by it, never multiplied.
7043 Some(c) => (
7044 (c.start, c.start + c.frames()),
7045 TimelineMap::piece(
7046 (c.start, c.start + c.frames()),
7047 (c.start, c.start + (c.len() as f64 / new).round() as u32),
7048 ),
7049 ),
7050 // The caption's span, scaled about the held clip's head by
7051 // the held clip's proportion -- the offset the group keeps.
7052 None => {
7053 let s = self.lanes[l].subs.get(i)?;
7054 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
7055 (
7056 (s.start, s.end()),
7057 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
7058 )
7059 }
7060 };
7061 // The piece owns only its own old span: outside it the playhead
7062 // is another member's question, or nobody's.
7063 if (span.0..span.1).contains(&at) {
7064 return Some(map.apply(at));
7065 }
7066 }
7067 Some(at)
7068 }
7069
7070 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
7071 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
7072 /// every clip starts at anyway.
7073 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
7074 self.lane(lane)
7075 .get(idx)
7076 .map_or(FitPolicy::default(), |c| c.fit)
7077 }
7078
7079 /// Sets it. One undo step like every other edit, and `false` (with no
7080 /// history) for an index that is not there. Unlike an eq or a grade there is
7081 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
7082 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
7083 if idx >= self.lane(lane).len() {
7084 return false;
7085 }
7086 self.snapshot();
7087 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
7088 true
7089 }
7090
7091 /// Turns the stabilisation of the clip at `idx` of a video `lane` on (with its
7092 /// settings) or off (`None`). One undo step; `false` (no history) for an index
7093 /// that is not there, a lane that is not video, or no change.
7094 pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool {
7095 if lane.kind != LaneKind::Video || self.lane(lane).get(idx).is_none_or(|c| c.stabilise == st) {
7096 return false;
7097 }
7098 self.snapshot();
7099 self.lane_mut(lane).expect("checked above")[idx].stabilise = st;
7100 true
7101 }
7102
7103 /// Sets how a video clip's interlaced source is deinterlaced
7104 /// ([`Clip::deinterlace`]). One undo step; `false`, and no history, for a
7105 /// lane that is not video, a clip that is not there, or no change.
7106 pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: Deinterlace) -> bool {
7107 if lane.kind != LaneKind::Video || self.lane(lane).get(idx).is_none_or(|c| c.deinterlace == mode) {
7108 return false;
7109 }
7110 self.snapshot();
7111 self.lane_mut(lane).expect("checked above")[idx].deinterlace = mode;
7112 true
7113 }
7114
7115 /// Points the clip at `idx` of a video `lane` at another source -- how a generator's
7116 /// parameter is edited (a new spelling is a new source). The window is kept. One undo step;
7117 /// `false` and no history for a clip that is not there, a source that is not, or no change.
7118 pub fn set_clip_source(&mut self, lane: Lane, idx: usize, source: usize) -> bool {
7119 if lane.kind != LaneKind::Video || source >= self.sources.len() || self.lane(lane).get(idx).is_none_or(|c| c.source == source) {
7120 return false;
7121 }
7122 self.snapshot();
7123 self.lane_mut(lane).expect("checked above")[idx].source = source;
7124 true
7125 }
7126
7127 /// Sets the colour label of the clip at `idx` of `lane` (0 for none). One undo step; `false`
7128 /// and no history for a clip that is not there, a label outside the palette, or no change.
7129 pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool {
7130 if label > LABEL_COUNT || self.lane(lane).get(idx).is_none_or(|c| c.mark.label == label) {
7131 return false;
7132 }
7133 self.snapshot();
7134 self.lane_mut(lane).expect("checked above")[idx].mark.label = label;
7135 true
7136 }
7137
7138 /// Switches the clip at `idx` of `lane` on or off ([`ClipMark::off`]). One undo step; `false`
7139 /// and no history for a clip that is not there or no change.
7140 pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool {
7141 if self.lane(lane).get(idx).is_none_or(|c| c.mark.off != enabled) {
7142 return false;
7143 }
7144 self.snapshot();
7145 self.lane_mut(lane).expect("checked above")[idx].mark.off = !enabled;
7146 true
7147 }
7148
7149 /// The clip's mark, the default for no clip.
7150 pub fn mark_of(&self, lane: Lane, idx: usize) -> ClipMark {
7151 self.lane(lane).get(idx).map_or_else(ClipMark::default, |c| c.mark)
7152 }
7153
7154 /// The clip's deinterlace setting, `Frame` for no clip.
7155 pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> Deinterlace {
7156 self.lane(lane).get(idx).map_or_else(Deinterlace::default, |c| c.deinterlace)
7157 }
7158
7159 /// The clip's stabilisation ([`Clip::stabilise`]), `None` for off or no clip.
7160 pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> {
7161 self.lane(lane).get(idx)?.stabilise
7162 }
7163
7164 /// Waveform style flags on the clip at `idx` of `lane`. Bit 0 marks it
7165 /// a visualizer; the rest are outline/smooth/fast/tint. `false` (no
7166 /// history) for an index that is not there.
7167 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
7168 if idx >= self.lane(lane).len() {
7169 return false;
7170 }
7171 self.snapshot();
7172 self.lane_mut(lane).expect("checked above")[idx].visualizer = flags;
7173 true
7174 }
7175
7176 /// Give the clip at `idx` of `lane` this packed look: one undo step, and
7177 /// `false` (with no history) for an index that is not there, the way every
7178 /// other setter refuses.
7179 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
7180 self.write_viz_paint(lane, idx, paint, true)
7181 }
7182
7183 /// [`set_viz_paint`](Self::set_viz_paint) without the undo step: the
7184 /// samples *inside* one pointer drag across the colour wheel, whose first
7185 /// write (a plain `set_viz_paint`) already took the snapshot the gesture
7186 /// rolls back to. One drag is one undo, not one per sample.
7187 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
7188 self.flat.clear();
7189 self.write_viz_paint(lane, idx, paint, false)
7190 }
7191
7192 fn write_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64, snapshot: bool) -> bool {
7193 if idx >= self.lane(lane).len() {
7194 return false;
7195 }
7196 if snapshot {
7197 self.snapshot();
7198 }
7199 self.lane_mut(lane).expect("checked above")[idx].viz_paint = paint;
7200 true
7201 }
7202
7203 /// Timeline frames of ramp-up from silence at the start of the clip at
7204 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
7205 /// that has none.
7206 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
7207 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
7208 }
7209
7210 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
7211 /// can shrink a clip's audible middle to nothing but never ask for more
7212 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
7213 /// and `false` (no history) for an index that is not there.
7214 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7215 if idx >= self.lane(lane).len() {
7216 return false;
7217 }
7218 self.snapshot();
7219 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
7220 clip.fade_in = frames.min(clip.frames());
7221 true
7222 }
7223
7224 /// Timeline frames of ramp-down to silence at the end of the clip at
7225 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
7226 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
7227 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
7228 }
7229
7230 /// Sets it. Same promises as [`Project::set_fade_in`].
7231 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7232 if idx >= self.lane(lane).len() {
7233 return false;
7234 }
7235 self.snapshot();
7236 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
7237 clip.fade_out = frames.min(clip.frames());
7238 true
7239 }
7240
7241 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
7242 /// into its successor, at its own end. `0` for an index that is not
7243 /// there, same as a clip that has none.
7244 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
7245 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
7246 }
7247
7248 /// Sets it, clamped to the clip's own length and to how many frames its
7249 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
7250 /// visible middle to nothing but never ask for more than the two clips
7251 /// between them have. `false` -- no history -- unless `lane` is video,
7252 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
7253 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
7254 /// them. One undo step like [`Project::set_fade_out`].
7255 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7256 if lane.kind != LaneKind::Video {
7257 return false;
7258 }
7259 let clips = self.lane(lane);
7260 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7261 return false;
7262 };
7263 if a.end() != b.start {
7264 return false;
7265 }
7266 let cap = a.frames().min(b.frames());
7267 self.snapshot();
7268 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
7269 true
7270 }
7271
7272 /// The kind of the transition the clip at `idx` of `lane` plays into its
7273 /// successor; a dissolve for an index that is not there.
7274 pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind {
7275 self.lane(lane).get(idx).map_or_else(Default::default, |c| c.transition_kind)
7276 }
7277
7278 /// [`Project::set_transition_out`] with a kind: sets both in one undo step.
7279 pub fn set_transition(
7280 &mut self,
7281 lane: Lane,
7282 idx: usize,
7283 kind: crate::transitions::TransitionKind,
7284 frames: u32,
7285 ) -> bool {
7286 if lane.kind != LaneKind::Video {
7287 return false;
7288 }
7289 let clips = self.lane(lane);
7290 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7291 return false;
7292 };
7293 if a.end() != b.start {
7294 return false;
7295 }
7296 let cap = a.frames().min(b.frames());
7297 self.snapshot();
7298 let a = &mut self.lane_mut(lane).expect("checked above")[idx];
7299 a.transition_out = frames.min(cap);
7300 a.transition_kind = kind;
7301 true
7302 }
7303
7304 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
7305 /// after it, over `frames` timeline frames: sets `idx`'s
7306 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
7307 /// each clamped to its own clip's length. `false` -- no history -- unless
7308 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
7309 /// adjacent: the second's [`Clip::start`] is exactly the first's
7310 /// [`Clip::end`], no gap between them.
7311 ///
7312 /// This is the whole mechanism, not a stand-in for one: a *real*
7313 /// cross-fade -- both takes heard at once, blending -- is what two clips
7314 /// **overlapping** on separate lanes already get for free from the
7315 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
7316 /// This call only shapes the edges of two clips already sitting
7317 /// end-to-end on *one* lane, so the join between them fades like one did.
7318 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7319 if lane.kind != LaneKind::Audio {
7320 return false;
7321 }
7322 let clips = self.lane(lane);
7323 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7324 return false;
7325 };
7326 if a.end() != b.start {
7327 return false;
7328 }
7329 self.snapshot();
7330 let clips = self.lane_mut(lane).expect("checked above");
7331 clips[idx].fade_out = frames.min(clips[idx].frames());
7332 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
7333 true
7334 }
7335
7336 /// Every frame number on every lane rewritten onto a timeline counted at
7337 /// another rate: `k` is old timeline frames per new one, `counts` is how
7338 /// long each source is on the *new* timeline (indexed as
7339 /// [`Project::sources`] is), and the edit survives as the same seconds of
7340 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
7341 /// the edit list, and the only thing that touches the frame numbers without
7342 /// being an edit anyone made.
7343 ///
7344 /// Every position -- a clip's start and its end alike -- goes through the
7345 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
7346 /// stays a gap, and a take's picture and its sound land on the same frame on
7347 /// their two lanes: no lane can drift against another. A clip is then only
7348 /// ever made to *fit* the room its own start and end mapped to, never to
7349 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
7350 /// below is the backstop for the one case that could: a slow clip so short
7351 /// that no source range fits its new room at all).
7352 ///
7353 /// Rounded to the nearest frame of the new grid, every boundary, length and
7354 /// envelope ([`Rate::timeline_nearest`]), so no round trip drifts: a second
7355 /// trip lands where the first did. Not exact both ways in general: a frame
7356 /// of one grid can fall between two of the other, and a rate change keeps
7357 /// only the frame it rounds to. An edit whose frames sit on both grids (on
7358 /// a whole second at 30, 25 and 24 fps) comes back exactly; any other
7359 /// boundary comes back within one frame. The exact fix is to hold the edit
7360 /// in seconds rather than frames, which every frame number in this module
7361 /// is measured in.
7362 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
7363 for lane in &mut self.lanes {
7364 let mut cursor = 0;
7365 for clip in &mut lane.clips {
7366 let start = k.timeline_nearest(clip.start).max(cursor);
7367 // The room its own end mapped to -- never zero, since a clip is
7368 // never empty even on a grid too coarse to hold it.
7369 let room = k.timeline_nearest(clip.end()).saturating_sub(start).max(1);
7370 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
7371 // Its footage, held inside the file's new length: a clip whose
7372 // out-point was the last frame of its source must not come out
7373 // of this naming a frame past the end -- that is a project that
7374 // would not open again ([`crate::PlaybackSession::open_project`]
7375 // refuses one by name).
7376 let in_frame = k.timeline_nearest(clip.in_frame).min(count - 1);
7377 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
7378 // The envelopes are frame counts measured from the clip's own
7379 // start (fades in), its own end (fades out and a dissolve into
7380 // the next clip). Each is its own length in seconds, rounded to the
7381 // nearest frame of the new grid, not a difference of two rounded
7382 // boundaries, which is what let a dissolve drift a frame per trip.
7383 let fade_in = k.timeline_nearest(clip.fade_in);
7384 let fade_out = k.timeline_nearest(clip.fade_out);
7385 let transition = k.timeline_nearest(clip.transition_out);
7386 clip.start = start;
7387 clip.in_frame = in_frame;
7388 clip.out_frame = in_frame + len;
7389 let frames = clip.frames();
7390 clip.fade_in = fade_in.min(frames);
7391 clip.fade_out = fade_out.min(frames);
7392 clip.transition_out = transition.min(frames);
7393 // A volume point is a source frame, numbered the way `in_frame`
7394 // is, so it moves with the footage. Two points that land on one
7395 // frame keep the first, since the envelope holds one per frame.
7396 let mut last = None;
7397 clip.gain_keys.retain_mut(|key| {
7398 key.at = k.timeline_nearest(key.at);
7399 let keep = last != Some(key.at);
7400 last = Some(key.at);
7401 keep
7402 });
7403 // The placement keys are source frames too, so they follow the
7404 // same grid, one point per frame as the envelope keeps them.
7405 let mut last = None;
7406 clip.transform_keys.retain_mut(|key| {
7407 key.at = k.timeline_nearest(key.at);
7408 let keep = last != Some(key.at);
7409 last = Some(key.at);
7410 keep
7411 });
7412 let mut last = None;
7413 clip.opacity_keys.retain_mut(|key| {
7414 key.at = k.timeline_nearest(key.at);
7415 let keep = last != Some(key.at);
7416 last = Some(key.at);
7417 keep
7418 });
7419 let mut last = None;
7420 clip.color_keys.retain_mut(|key| {
7421 key.at = k.timeline_nearest(key.at);
7422 let keep = last != Some(key.at);
7423 last = Some(key.at);
7424 keep
7425 });
7426 cursor = clip.end();
7427 }
7428 // A dissolve is only as long as the clip it dissolves into allows
7429 // too, which the rescale above cannot see one clip at a time.
7430 for i in 1..lane.clips.len() {
7431 let (before, after) = lane.clips.split_at_mut(i);
7432 let (a, b) = (&mut before[i - 1], &after[0]);
7433 if a.end() == b.start {
7434 a.transition_out = a.transition_out.min(b.frames());
7435 }
7436 }
7437 // A subtitle's *window* is in microseconds and a rate change moves
7438 // no seconds, so only where it sits is remapped -- through the same
7439 // [`Rate::timeline_at`] every clip boundary goes through, so a
7440 // caption still starts on the frame its picture does.
7441 let mut cursor = 0;
7442 for sub in &mut lane.subs {
7443 let start = k.timeline_nearest(sub.start).max(cursor);
7444 sub.frames = k.timeline_nearest(sub.end()).saturating_sub(start).max(1);
7445 sub.start = start;
7446 cursor = sub.end();
7447 }
7448 }
7449 // A title is placed and sized in frames like a clip and its captions,
7450 // so it takes the same grid: its window maps start to end, and its
7451 // fades are re-measured from the boundary each one is counted from.
7452 // Held inside the largest frame a title may end on, which is the check
7453 // a load makes of every title.
7454 for title in &mut self.titles {
7455 let (old_start, old_end) = (title.start, title.end());
7456 let start = k.timeline_nearest(old_start);
7457 let end = k.timeline_nearest(old_end).min(MAX_TITLE_END).max(start + 1);
7458 let frames = end - start;
7459 title.fade_in = k.timeline_nearest(title.fade_in).min(frames);
7460 title.fade_out = k.timeline_nearest(title.fade_out).min(frames);
7461 title.start = start;
7462 title.frames = frames;
7463 }
7464 // A chapter is a single frame, so it takes the grid as a title's start
7465 // does; two that land on one frame keep the first.
7466 for chapter in &mut self.chapters {
7467 chapter.frame = k.timeline_nearest(chapter.frame);
7468 }
7469 self.chapters.dedup_by_key(|c| c.frame);
7470 // A marker's start and end take the grid the same way.
7471 for m in &mut self.markers {
7472 let end = k.timeline_nearest(m.frame + m.length);
7473 m.frame = k.timeline_nearest(m.frame);
7474 m.length = end.saturating_sub(m.frame);
7475 }
7476 self.markers.sort_by_key(|m| m.frame);
7477 }
7478
7479 /// Length of the timeline in frames: where the *last* lane runs out. A lane
7480 /// that ends early is a trailing gap in that lane, not a shorter timeline.
7481 ///
7482 /// A subtitle lane counts like any other: a caption placed past the last
7483 /// picture holds the timeline open under it, exactly as an `A2` running
7484 /// past `V1` does, rather than being silently clipped away by the length
7485 /// ([`crate::export::timeline_cues`] clips cues to this).
7486 pub fn timeline_frames(&self) -> u32 {
7487 self.lanes
7488 .iter()
7489 .filter_map(|l| match l.kind {
7490 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
7491 _ => l.clips.last().map(Clip::end),
7492 })
7493 .max()
7494 .unwrap_or(0)
7495 .max(self.title_end())
7496 }
7497
7498 /// The same, counting the *media* alone: where the last picture or sound
7499 /// runs out, with the captions over them ignored.
7500 ///
7501 /// What an export actually writes ends here -- the picture loop walks the
7502 /// composite spans and the file stops with them -- so this is the length a
7503 /// cue has to be inside of to be written at all (what
7504 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
7505 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
7506 /// thing is a picture or a sound, which is every timeline that has no
7507 /// caption hanging past the end of both.
7508 pub fn media_frames(&self) -> u32 {
7509 self.lanes
7510 .iter()
7511 .filter(|l| l.kind != LaneKind::Subtitle)
7512 .filter_map(|l| l.clips.last().map(Clip::end))
7513 .max()
7514 .unwrap_or(0)
7515 // A title is picture too: one past the last clip runs on over black,
7516 // so the export and the picture cover it.
7517 .max(self.title_end())
7518 }
7519
7520 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
7521 /// to lay clips out. Gaps show up as the holes between consecutive entries.
7522 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
7523 self.lane_spans(Lane::V1)
7524 }
7525
7526 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
7527 // Timeline frames, not source ones: a box on a lane is as wide as the
7528 // clip is long *there*, which a speed halves or quadruples.
7529 self.lane(lane)
7530 .iter()
7531 .map(|c| (c.start, c.frames()))
7532 .collect()
7533 }
7534
7535 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
7536 /// and past the end -- [`Project::span_at`] is the version that tells those
7537 /// two apart.
7538 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
7539 let clips = self.lane(lane);
7540 let idx = at(clips, timeline_frame)?;
7541 Some((idx, source_frame(&clips[idx], timeline_frame)))
7542 }
7543
7544 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
7545 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
7546 self.map(Lane::V1, timeline_frame)
7547 }
7548
7549 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
7550 /// it, or the gap running to the next clip (or to the end of the timeline,
7551 /// which is where a lane shorter than its neighbour keeps showing black).
7552 /// `None` at or past the end of the timeline, which is the only "nothing
7553 /// left" there is.
7554 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
7555 let total = self.timeline_frames();
7556 if timeline_frame >= total {
7557 return None;
7558 }
7559 let clips = self.lane(lane);
7560 Some(match at(clips, timeline_frame) {
7561 Some(idx) => {
7562 let (speed, ramp) = span_speed_of(&clips[idx], timeline_frame);
7563 Span {
7564 start: timeline_frame,
7565 len: clips[idx].end() - timeline_frame,
7566 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
7567 speed,
7568 ramp,
7569 reverse: clips[idx].reversed,
7570 pitch: clips[idx].pitch,
7571 }
7572 }
7573 None => Span {
7574 start: timeline_frame,
7575 speed: Speed::NORMAL,
7576 ramp: None,
7577 reverse: false,
7578 pitch: 0,
7579 // The next placement, or the end of the timeline: a gap is
7580 // bounded by what comes after it, never by its own bookkeeping.
7581 len: clips
7582 .iter()
7583 .find(|c| c.start > timeline_frame)
7584 .map_or(total, |c| c.start)
7585 - timeline_frame,
7586 from: None,
7587 },
7588 })
7589 }
7590
7591 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
7592 /// gaps included -- the whole play list, which is what an export walks.
7593 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
7594 let mut out = Vec::new();
7595 let mut t = timeline_frame;
7596 while let Some(span) = self.span_at(lane, t) {
7597 t = span.end();
7598 out.push(span);
7599 }
7600 out
7601 }
7602
7603 /// What the *composite* shows from `timeline_frame` on -- the answer
7604 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
7605 /// video lane by one rule: **the topmost lane with a clip there wins**, and
7606 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
7607 /// (the usual overlay convention). A frame no video lane covers is a gap,
7608 /// which is black however many lanes are above or below it.
7609 ///
7610 /// No blending, so exactly one lane is visible at a time and the composite
7611 /// is itself a span list -- which is why one decoder plays it, the same one
7612 /// a single-lane timeline uses, rather than N running at once.
7613 ///
7614 /// The span is cut short wherever a *higher* lane's clip starts, because
7615 /// from that frame on a different lane wins; that is what makes walking
7616 /// [`composite_spans_from`](Project::composite_spans_from) correct.
7617 ///
7618 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
7619 /// lanes would then be visible in one frame and the caller needs a decoder
7620 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
7621 /// (this same walk, per lane) feeding N decoders.
7622 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
7623 let total = self.timeline_frames();
7624 if timeline_frame >= total {
7625 return None;
7626 }
7627 let video = self.video_lanes();
7628 // The last covering lane is the winner; only the lanes above it can
7629 // interrupt what it shows.
7630 let winner = video
7631 .iter()
7632 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
7633 let (from, speed, ramp, until, reverse) = match winner {
7634 Some(i) => {
7635 let clips = self.lane(video[i]);
7636 let idx = at(clips, timeline_frame).expect("just found above");
7637 let (speed, ramp) = span_speed_of(&clips[idx], timeline_frame);
7638 (
7639 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
7640 speed,
7641 ramp,
7642 clips[idx].end(),
7643 clips[idx].reversed,
7644 )
7645 }
7646 // Nothing covers it: black until something above the floor starts.
7647 None => (None, Speed::NORMAL, None, total, false),
7648 };
7649 let takeover = video[winner.map_or(0, |i| i + 1)..]
7650 .iter()
7651 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
7652 .map(|c| c.start)
7653 .min();
7654 Some(Span {
7655 start: timeline_frame,
7656 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
7657 from,
7658 speed,
7659 ramp,
7660 reverse,
7661 pitch: 0,
7662 })
7663 }
7664
7665 /// The video lanes in display order, topmost last -- the order the composite
7666 /// rule counts in. A hidden one is not in it: the picture is composed from
7667 /// what is visible, so a hidden lane is black where it is the only one
7668 /// covering and the lane below shows through where it is not.
7669 fn video_lanes(&self) -> Vec<Lane> {
7670 self.lanes()
7671 .into_iter()
7672 .filter(|l| l.kind == LaneKind::Video && !self.lane_hidden(*l))
7673 .collect()
7674 }
7675
7676 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
7677 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
7678 /// index on that lane. `None` over a gap and past the end. What a front-end
7679 /// asks to act on "the clip on screen" without re-deriving the rule.
7680 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
7681 let video = self.video_lanes();
7682 let winner = video
7683 .iter()
7684 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
7685 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
7686 }
7687
7688 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
7689 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
7690 /// answers "the clip on screen"; this answers it per lane, which is what
7691 /// walking the lanes for something to select needs.
7692 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
7693 at(self.lane(lane), timeline_frame)
7694 }
7695
7696 /// How the composite is graded at `timeline_frame`, so the picture playback
7697 /// converts and the one an export encodes are graded from one answer.
7698 /// `None` over a gap (black is black) and for a clip nobody has graded,
7699 /// which is the byte-identical path everywhere.
7700 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
7701 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
7702 self.color_of(lane, idx)
7703 }
7704
7705 /// [`composite_color_at`](Self::composite_color_at)'s twin for
7706 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
7707 /// policy's own placement.
7708 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
7709 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
7710 self.transform_of(lane, idx)
7711 }
7712
7713 /// How the composite meets the project canvas at `timeline_frame`, so the
7714 /// picture playback composes and the one an export encodes are placed from
7715 /// one answer. `Fit` over a gap, where black is already the canvas.
7716 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
7717 self.composite_clip_at(timeline_frame)
7718 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
7719 }
7720
7721 /// Waveform flags of the topmost video clip at `timeline_frame`, or 0
7722 /// over a gap / a picture that is not a visualizer.
7723 pub fn composite_visualizer_at(&self, timeline_frame: u32) -> u8 {
7724 self.composite_clip_at(timeline_frame)
7725 .map(|(lane, idx)| self.lane(lane)[idx].visualizer)
7726 .unwrap_or(0)
7727 }
7728
7729 /// Packed look ([`Clip::viz_paint`]) of the topmost video clip at
7730 /// `timeline_frame`, or zero over a gap / a picture that is not a
7731 /// visualizer.
7732 pub fn composite_viz_paint_at(&self, timeline_frame: u32) -> u64 {
7733 self.composite_clip_at(timeline_frame)
7734 .map(|(lane, idx)| self.lane(lane)[idx].viz_paint)
7735 .unwrap_or(0)
7736 }
7737
7738 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
7739 /// viewer sees from `timeline_frame` to the end, in order. What an export
7740 /// encodes and what playback walks at a clip boundary.
7741 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
7742 let mut out = Vec::new();
7743 let mut t = timeline_frame;
7744 while let Some(span) = self.composite_span_at(t) {
7745 t = span.end();
7746 out.push(span);
7747 }
7748 out
7749 }
7750
7751 /// The frame nearest `frame`, within `reach` frames either side, at which a cut lands
7752 /// cleanly on every lane -- `frame` itself when it does. `None` when no such frame is
7753 /// that near, which is what a cut or a freeze there is refused for.
7754 pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> {
7755 let clean = |f: u32| {
7756 self.lanes.iter().all(|l| {
7757 l.clips
7758 .iter()
7759 .all(|c| !(c.start < f && f < c.end()) || split_source(c, f).is_some())
7760 })
7761 };
7762 (0..=reach)
7763 .flat_map(|d| [frame.checked_add(d), frame.checked_sub(d)])
7764 .flatten()
7765 .find(|&f| clean(f))
7766 }
7767
7768 /// Split every lane at `timeline_frame`, so that frame becomes the first
7769 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
7770 /// (`false`, no change) when no lane has a clip to split there -- at a
7771 /// placement's own start, in a gap, and past the end -- all of which would
7772 /// produce an empty clip or nothing at all.
7773 ///
7774 /// Lanes' halves share an id only where they are the *same* span: the lanes
7775 /// are edited apart, so the clip being cut here may start (or end)
7776 /// somewhere else on another lane, and a group id whose clips disagree
7777 /// about their span is not one take (see [`links_are_consistent`], which
7778 /// refuses to load one).
7779 ///
7780 /// Metadata only: no mapping changes, in any lane.
7781 pub fn split(&mut self, timeline_frame: u32) -> bool {
7782 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
7783 }
7784
7785 /// [`split`](Project::split) on the lanes in `scope` only: the lanes outside
7786 /// it keep their clip across the frame. `false`, no change, as `split`.
7787 pub fn split_on(&mut self, timeline_frame: u32, scope: &[Lane]) -> bool {
7788 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
7789 self.write_split(timeline_frame, true, &on)
7790 }
7791
7792 /// [`split`](Project::split), with the snapshot optional and the lanes
7793 /// named: a batch that has already taken a snapshot
7794 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
7795 /// region and must still be one undo press, and a *scoped* batch must not
7796 /// cut a lane it was told to leave alone.
7797 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
7798 let cut: Vec<Option<Clip>> = self
7799 .lanes
7800 .iter()
7801 .enumerate()
7802 .map(|(i, l)| {
7803 on.contains(&i)
7804 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx].clone()))
7805 .flatten()
7806 })
7807 .collect();
7808 // The same question on the subtitle lanes, in their own arithmetic: a
7809 // razor cuts the captions with the picture, and a frame where only a
7810 // caption can be cut is still a cut.
7811 let cut_subs: Vec<bool> = self
7812 .lanes
7813 .iter()
7814 .enumerate()
7815 .map(|(i, l)| {
7816 on.contains(&i)
7817 && l.subs
7818 .iter()
7819 .any(|s| s.start < timeline_frame && timeline_frame < s.end())
7820 })
7821 .collect();
7822 // The links the captions carry, read before the room is opened below
7823 // -- `sub_open_room` takes the id off both halves, exactly as
7824 // `open_room` does for a clip, and the split hands the halves theirs
7825 // back afterwards.
7826 let sub_orig: Vec<Option<u32>> = self
7827 .lanes
7828 .iter()
7829 .zip(&cut_subs)
7830 .map(|(l, &cut)| {
7831 cut.then(|| {
7832 l.subs
7833 .iter()
7834 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
7835 .and_then(|s| s.link)
7836 })
7837 .flatten()
7838 })
7839 .collect();
7840 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
7841 return false;
7842 }
7843 if snapshot {
7844 self.snapshot();
7845 }
7846 // The captions' words are divided before their windows are cut, so
7847 // the words on the far side of the split stay with the far side.
7848 self.split_cues_across(on, &[timeline_frame], false);
7849 for (data, _) in self
7850 .lanes
7851 .iter_mut()
7852 .zip(&cut_subs)
7853 .filter(|&(_, &cut)| cut)
7854 {
7855 // A split is room of no width: the halves keep their windows by
7856 // proportion and nothing moves.
7857 sub_open_room(&mut data.subs, timeline_frame, 0);
7858 debug_assert!(subs_sorted_disjoint(&data.subs));
7859 }
7860 // Each side is its own question, and the answer is the group the clip
7861 // already carried: the left half *keeps* its take's id -- the take the
7862 // frames before the cut still are -- and the right halves of one take
7863 // share one fresh id of their own, clips and captions alike. A lane
7864 // holding no group (a `place`ment, a caption nobody grouped) comes out
7865 // of the cut holding none, which is what it went in with. The captions'
7866 // own links were drawn above, before the room opened.
7867 let orig: Vec<Option<u32>> = cut
7868 .iter()
7869 .map(|c| c.as_ref().and_then(|c| c.link))
7870 .collect();
7871 let mut distinct: Vec<u32> = Vec::new();
7872 for id in orig.iter().chain(&sub_orig).flatten() {
7873 if !distinct.contains(id) {
7874 distinct.push(*id);
7875 }
7876 }
7877 // A cut on a *subset* of the lanes leaves the take's other members whole
7878 // on lanes that were not cut: the cut halves no longer agree with them
7879 // about their span, so the take is unlinked at the cut -- every member,
7880 // in this same snapshot (one undo puts it back).
7881 let detach = distinct.iter().any(|&id| {
7882 self.lanes.iter().enumerate().any(|(j, d)| {
7883 !on.contains(&j)
7884 && (d.clips.iter().any(|c| c.link == Some(id))
7885 || d.subs.iter().any(|s| s.link == Some(id)))
7886 })
7887 });
7888 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
7889 let right_of = |link: Option<u32>| {
7890 link.and_then(|id| distinct.iter().position(|&d| d == id))
7891 .map(|at| fresh[at])
7892 };
7893 for (l, data) in self.lanes.iter_mut().enumerate() {
7894 if !cut_subs[l] {
7895 continue;
7896 }
7897 // The pair the razor just made: they touch at the frame it cut.
7898 if let Some(idx) = data
7899 .subs
7900 .iter()
7901 .position(|s| s.end() == timeline_frame)
7902 .filter(|&idx| {
7903 data.subs
7904 .get(idx + 1)
7905 .is_some_and(|n| n.start == timeline_frame)
7906 })
7907 {
7908 data.subs[idx].link = sub_orig[l];
7909 data.subs[idx + 1].link = right_of(sub_orig[l]);
7910 }
7911 }
7912 for (data_i, data) in self.lanes.iter_mut().enumerate() {
7913 // The lanes this call was not scoped to are not cut, whatever their
7914 // own clips would allow.
7915 let Some(idx) =
7916 splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some())
7917 else {
7918 continue;
7919 };
7920 let mut tail = data.clips[idx].clone();
7921 // Where the cut lands *in the file*, which is the clip's own rate
7922 // away from where it lands on the timeline. Both halves keep the
7923 // speed, and `splittable` has already refused any frame at which
7924 // the two would not add up to the one being cut.
7925 let cut_at = split_source(&tail, timeline_frame).expect("splittable said so");
7926 let (head_speed, tail_speed) = split_keys(&tail, timeline_frame);
7927 tail.speed_keys = tail_speed;
7928 data.clips[idx].speed_keys = head_speed;
7929 let reversed = tail.reversed;
7930 match reversed {
7931 true => tail.out_frame = cut_at,
7932 false => tail.in_frame = cut_at,
7933 }
7934 tail.start = timeline_frame;
7935 // The placement animation is divided, not copied: each half keeps
7936 // its own keys and a key at the cut (see `split_transform_keys`). The
7937 // lower keys go to the tail of a reversed clip, which plays them last.
7938 let (below, above) = split_transform_keys(&data.clips[idx].transform_keys, cut_at);
7939 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7940 tail.transform_keys = tail_keys;
7941 data.clips[idx].transform_keys = head_keys;
7942 // The opacity and grade keys are source frames cut at the same frame as
7943 // the placement, so a reversed clip divides them the same way round. The
7944 // volume envelope stays whole on both halves, so a half trimmed back out
7945 // still has its points.
7946 let (below, above) = split_transform_keys(&data.clips[idx].opacity_keys, cut_at);
7947 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7948 tail.opacity_keys = tail_keys;
7949 data.clips[idx].opacity_keys = head_keys;
7950 let (below, above) = split_transform_keys(&data.clips[idx].color_keys, cut_at);
7951 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7952 tail.color_keys = tail_keys;
7953 data.clips[idx].color_keys = head_keys;
7954 // Each mask's keys divide the same way as the placement's, per stack position.
7955 let masks: Vec<_> = data.clips[idx]
7956 .effects
7957 .iter()
7958 .map(|e| split_transform_keys(&e.keys, cut_at))
7959 .collect();
7960 for ((tail_e, head_e), (below, above)) in tail.effects.iter_mut().zip(data.clips[idx].effects.iter_mut()).zip(masks) {
7961 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7962 tail_e.keys = tail_keys;
7963 head_e.keys = head_keys;
7964 }
7965 tail.link = right_of(orig[data_i]);
7966 // A split makes a new edge for each half, and a fade is a promise
7967 // about an edge: only the half that *kept* the original edge
7968 // keeps that fade, re-clamped to its own now-shorter length (a
7969 // cut inside the ramp shortens it, never leaves it pointing past
7970 // the clip it is on); the edge the cut itself made starts, or
7971 // ends, flat -- there was no silence there to ramp out of.
7972 tail.fade_in = 0;
7973 tail.fade_out = tail.fade_out.min(tail.frames());
7974 // A dissolve is a promise about the *end* edge, same as
7975 // `fade_out`: only the half that kept the clip's original end
7976 // (the tail) keeps it, re-clamped to its own now-shorter length;
7977 // the head's new end is the cut the razor just made, which starts
7978 // flat -- there was no successor to dissolve into there.
7979 tail.transition_out = tail.transition_out.min(tail.frames());
7980 match reversed {
7981 true => data.clips[idx].in_frame = cut_at,
7982 false => data.clips[idx].out_frame = cut_at,
7983 }
7984 data.clips[idx].link = orig[data_i];
7985 data.clips[idx].fade_out = 0;
7986 data.clips[idx].transition_out = 0;
7987 data.clips[idx].transition_kind = Default::default();
7988 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
7989 data.clips.insert(idx + 1, tail);
7990 }
7991 if detach {
7992 // Every member of the take gets an id of its own, as `ungroup` gives
7993 // them: each half is detached (a lone id), never a whole take.
7994 let gone: Vec<u32> = distinct.iter().chain(&fresh).copied().collect();
7995 let count: usize = self
7996 .lanes
7997 .iter()
7998 .map(|d| {
7999 d.clips.iter().filter(|c| c.link.is_some_and(|id| gone.contains(&id))).count()
8000 + d.subs.iter().filter(|s| s.link.is_some_and(|id| gone.contains(&id))).count()
8001 })
8002 .sum();
8003 let mut own = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
8004 for data in &mut self.lanes {
8005 for c in data.clips.iter_mut().filter(|c| c.link.is_some_and(|id| gone.contains(&id))) {
8006 c.link = own.pop();
8007 }
8008 for s in data.subs.iter_mut().filter(|s| s.link.is_some_and(|id| gone.contains(&id))) {
8009 s.link = own.pop();
8010 }
8011 }
8012 }
8013 true
8014 }
8015
8016 /// The inverse of [`split`](Project::split): rejoin the placements that meet
8017 /// at `timeline_frame` in every lane and put the result back in one group.
8018 /// Only what a split could have produced is rejoined -- the two sides must
8019 /// touch on the timeline *and* be consecutive frames of the same source --
8020 /// so the clip list comes back exactly as it was and traversal with it.
8021 /// `false` when no lane has such a pair. The rejoined placement keeps the
8022 /// **left** half's id, which is the take the split left on it: rejoining a
8023 /// cut take puts the take back, id and all. Its animation is both halves'
8024 /// keys merged, so the right half's keys after the cut come back with it; a
8025 /// lane whose merged animation would not fit is left as it is.
8026 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
8027 // What each lane would end up covering, if it joins here at all.
8028 let joined: Vec<Option<(u32, u32)>> = self
8029 .lanes
8030 .iter()
8031 .map(|l| {
8032 joinable(&l.clips, timeline_frame)
8033 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
8034 })
8035 .collect();
8036 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
8037 let join_subs: Vec<Option<usize>> = self
8038 .lanes
8039 .iter()
8040 .map(|l| sub_joinable(&l.subs, timeline_frame))
8041 .collect();
8042 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
8043 return false;
8044 }
8045 self.snapshot();
8046 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
8047 if let Some(idx) = sub {
8048 data.subs[idx].frames += data.subs[idx + 1].frames;
8049 // The left half's `in_us`, the right half's `out_us` -- which
8050 // is the SUM of two legal widths, because `sub_joinable` has
8051 // just established that the two halves are consecutive in the
8052 // *source* (`next.in_us == subs[idx].out_us`). Neither half
8053 // broke the ceiling and the whole does, so this is a composer
8054 // a per-arm check on one writer could never have found:
8055 // `set_window` is what makes the closed set closed.
8056 let (in_us, out_us) = (data.subs[idx].in_us, data.subs[idx + 1].out_us);
8057 set_window(&mut data.subs[idx], in_us, out_us);
8058 data.subs.remove(idx + 1);
8059 debug_assert!(subs_sorted_disjoint(&data.subs));
8060 }
8061 let Some(idx) = joinable(&data.clips, timeline_frame) else {
8062 continue;
8063 };
8064 let Some(joined) = joined_clip(&data.clips[idx], &data.clips[idx + 1]) else {
8065 continue;
8066 };
8067 data.clips[idx] = joined;
8068 data.clips.remove(idx + 1);
8069 }
8070 true
8071 }
8072
8073 /// Take the placement at `idx` of `lane` out of its group: every clip and
8074 /// every caption carrying its id -- on however many lanes -- is handed an
8075 /// id of its own, so from here on each half moves, trims and is deleted
8076 /// alone. The music video whose sound is to be cut against its picture
8077 /// starts here, and so does the caption that has to come off the picture it
8078 /// was pinned to.
8079 ///
8080 /// A group that holds more than one take gives each take back whole: a
8081 /// [`group`](Project::group_all) with a take member merges that take into
8082 /// the group, and one id cannot say which halves were a take before, so
8083 /// the halves are matched by what a take is -- clips with the same source,
8084 /// start and in/out points -- and each match keeps one id of its own. So
8085 /// ungrouping the picture of a take that was grouped with another clip
8086 /// leaves the take linked and detaches only the other clip. A group of one
8087 /// take, or one with a caption, is taken apart whole, as before.
8088 ///
8089 /// An id of its own rather than none at all: a half no other lane is grouped
8090 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
8091 /// (see [`links_are_consistent`]), and it is what a front-end already draws
8092 /// as detached. `None` would instead say "was never part of a take", which
8093 /// is what a one-lane [`place`](Project::place) means.
8094 ///
8095 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
8096 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
8097 /// the group back. Refused (`false`, nothing changed) for an index that is
8098 /// not there, a placement in no group at all, and one whose group has no
8099 /// other half -- that one is already detached, and a refusal must not cost
8100 /// an undo step.
8101 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
8102 let Some(members) = self.group_of(lane, idx) else {
8103 return false;
8104 };
8105 if members.alone() {
8106 return false;
8107 }
8108 let Some(id) = self
8109 .lane(lane)
8110 .get(idx)
8111 .and_then(|c| c.link)
8112 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
8113 else {
8114 return false;
8115 };
8116 self.snapshot();
8117 // The takes the group holds, by what a take is: its halves share these.
8118 let mut takes: Vec<TakeKey> = Vec::new();
8119 for data in &self.lanes {
8120 for c in data.clips.iter().filter(|c| c.link == Some(id)) {
8121 let k = take_key(c);
8122 if !takes.contains(&k) {
8123 takes.push(k);
8124 }
8125 }
8126 }
8127 let whole = takes.len() == 1 && members.subs.is_empty();
8128 // Drawn before the walk: `new_link` takes the whole project, and the
8129 // walk holds the lanes. One id per take (or per clip, when the group is
8130 // one take that comes apart), then one per caption.
8131 let clip_ids = if whole { members.clips.len() } else { takes.len() };
8132 let mut fresh = (0..clip_ids + members.subs.len()).map(|_| self.new_link()).collect::<Vec<_>>();
8133 let mut sub_fresh = fresh.split_off(clip_ids).into_iter();
8134 let mut next = 0;
8135 for data in &mut self.lanes {
8136 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
8137 c.link = Some(if whole {
8138 next += 1;
8139 fresh[next - 1]
8140 } else {
8141 let k = take_key(c);
8142 fresh[takes.iter().position(|t| *t == k).expect("collected above")]
8143 });
8144 }
8145 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
8146 s.link = sub_fresh.next();
8147 }
8148 }
8149 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8150 true
8151 }
8152
8153 /// Put two clips on two lanes into one group, so what moves one moves the
8154 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
8155 /// how a picture is regrouped with sound it was never opened with. Whatever
8156 /// either of them was grouped with comes along: those clips cover this same
8157 /// span already, so the result is one group and not two overlapping ones.
8158 ///
8159 /// Same frames or nothing: a group id names **one span** on however many
8160 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
8161 /// clips that do not cover the same frames cannot be one take, and the
8162 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
8163 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
8164 /// mean, not the rule.
8165 ///
8166 /// Metadata only, one snapshot. The error says what is wrong, because
8167 /// `false` would not: a bad index, one lane twice (a group is at most one
8168 /// clip per lane), spans that disagree, and a pair that is already one take
8169 /// -- nothing changes, and none of them costs an undo step.
8170 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
8171 if a == b {
8172 return Err(format!(
8173 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
8174 a.label()
8175 )
8176 .into());
8177 }
8178 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
8179 p.lane(lane)
8180 .get(idx)
8181 .cloned()
8182 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
8183 };
8184 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
8185 if (x.start, x.end()) != (y.start, y.end()) {
8186 return Err(format!(
8187 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
8188 a.label(),
8189 x.start,
8190 x.end(),
8191 b.label(),
8192 y.start,
8193 y.end()
8194 )
8195 .into());
8196 }
8197 if x.link.is_some() && x.link == y.link {
8198 return Err("those two are one take already".into());
8199 }
8200 self.snapshot();
8201 let id = self.new_link();
8202 // Every clip either of them was grouped with, by the same rule: all of
8203 // them cover this span, so one id over the lot stays consistent.
8204 let old = [x.link, y.link];
8205 for data in &mut self.lanes {
8206 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
8207 if old.contains(&c.link) {
8208 c.link = Some(id);
8209 }
8210 }
8211 }
8212 // And the two themselves, which a `place` may have left in no group.
8213 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
8214 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
8215 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8216 Ok(())
8217 }
8218
8219 /// Put every placement the picks name into one group -- the group a hand
8220 /// builds with ctrl-click and a menu: the picture, its sound and the
8221 /// caption over it, on as many lanes as the picks name. What any of them
8222 /// was already grouped with rides along (one group, not two sharing a
8223 /// member), and the members keep their own spans: a group is one id over
8224 /// one placement per lane, and the offsets between them are what the group
8225 /// preserves -- a drag, a trim and a delete all move the members *by the
8226 /// same distance*, not to the same frames.
8227 ///
8228 /// No two picks may name one lane -- that is the one clip-per-lane rule,
8229 /// and the refusal says which lane -- and a pick that names nothing is
8230 /// refused with its own words. At least two picks, or there is nothing to
8231 /// group.
8232 ///
8233 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
8234 /// apart again. None of the refusals changes anything or costs an undo
8235 /// step.
8236 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
8237 if picks.len() < 2 {
8238 return Err("a group is two placements or more: pick another one first".into());
8239 }
8240 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
8241 for &(lane, idx) in picks {
8242 if seen.contains(&lane) {
8243 return Err(format!(
8244 "a group is one placement per lane: {} is picked twice -- keep one clip per \
8245 track",
8246 lane.label()
8247 )
8248 .into());
8249 }
8250 seen.push(lane);
8251 let there = if lane.kind == LaneKind::Subtitle {
8252 idx < self.sub_lane(lane).len()
8253 } else {
8254 idx < self.lane(lane).len()
8255 };
8256 if !there {
8257 let what = if lane.kind == LaneKind::Subtitle {
8258 "subtitle"
8259 } else {
8260 "clip"
8261 };
8262 return Err(format!("there is no {what} {idx} on {}", lane.label()).into());
8263 }
8264 }
8265 let links: Vec<Option<u32>> = picks
8266 .iter()
8267 .map(|&(lane, idx)| {
8268 if lane.kind == LaneKind::Subtitle {
8269 self.sub_lane(lane)[idx].link
8270 } else {
8271 self.lane(lane)[idx].link
8272 }
8273 })
8274 .collect();
8275 // The picks are already one per lane (`seen`, above), but a pick's
8276 // *existing* group can carry a second member onto a lane another
8277 // pick (or another existing group in the merge) already occupies --
8278 // two captions on one sub lane, say, each grouped with a different
8279 // clip before this call. Merging both in would leave that lane with
8280 // two members of one id, which `links_are_consistent` may never see:
8281 // refused by name, before anything moves, rather than a group closed
8282 // broken.
8283 let labels = handles(&self.lanes);
8284 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
8285 for (li, data) in self.lanes.iter().enumerate() {
8286 let n = data
8287 .clips
8288 .iter()
8289 .filter(|c| c.link.is_some() && links.contains(&c.link))
8290 .count()
8291 + data
8292 .subs
8293 .iter()
8294 .filter(|s| s.link.is_some() && links.contains(&s.link))
8295 .count();
8296 if n > 0 {
8297 per_lane.insert(li, n as u32);
8298 }
8299 }
8300 // A pick that carries no link of its own is invisible to the scan
8301 // above (there is no `Some` to match): it still claims its lane.
8302 for &(lane, _) in picks {
8303 let li = self.index(lane).expect("checked above");
8304 per_lane.entry(li).or_insert(0);
8305 if !self.lanes[li]
8306 .clips
8307 .iter()
8308 .any(|c| c.link.is_some() && links.contains(&c.link))
8309 && !self.lanes[li]
8310 .subs
8311 .iter()
8312 .any(|s| s.link.is_some() && links.contains(&s.link))
8313 {
8314 *per_lane.get_mut(&li).expect("just inserted") += 1;
8315 }
8316 }
8317 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
8318 return Err(format!(
8319 "a group is one placement per lane: merging these groups would put two on {}",
8320 labels[li].label()
8321 )
8322 .into());
8323 }
8324 self.snapshot();
8325 let id = self.new_link();
8326 // Whatever any pick was grouped with comes along, for [`group`]'s
8327 // reason -- one id over the lot, not two groups sharing a member.
8328 for data in &mut self.lanes {
8329 for c in data.clips.iter_mut() {
8330 if c.link.is_some() && links.contains(&c.link) {
8331 c.link = Some(id);
8332 }
8333 }
8334 for s in data.subs.iter_mut() {
8335 if s.link.is_some() && links.contains(&s.link) {
8336 s.link = Some(id);
8337 }
8338 }
8339 }
8340 // And the picks themselves, which a `place` may have left in no group.
8341 // The lane seats are read before the walk, which holds the lanes.
8342 let seats: Vec<(usize, bool)> = picks
8343 .iter()
8344 .map(|&(lane, _)| {
8345 (
8346 self.index(lane).expect("checked above"),
8347 lane.kind == LaneKind::Subtitle,
8348 )
8349 })
8350 .collect();
8351 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
8352 let _ = lane;
8353 if sub {
8354 self.lanes[at].subs[idx].link = Some(id);
8355 } else {
8356 self.lanes[at].clips[idx].link = Some(id);
8357 }
8358 }
8359 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8360 Ok(())
8361 }
8362
8363 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
8364 /// lands on and leaving every other clip exactly where it is -- the
8365 /// per-lane paste. Anything already there is trimmed away (and split in two
8366 /// if `clip` lands inside it), which is what keeps the lane sorted and
8367 /// disjoint; nothing ripples, so a gap before the placement simply stays a
8368 /// gap. Refused only for an empty `clip`.
8369 ///
8370 /// The placement belongs to no group: a clipboard clip carries the link id
8371 /// of the take it was copied from, and placing it twice -- or placing a copy
8372 /// back over the clip it came from -- would put that id on two clips of one
8373 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
8374 /// `None` rather than a fresh id because a one-lane placement has nothing on
8375 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
8376 /// become a group again.
8377 ///
8378 /// Refused for an empty `clip`, for a lane that is not there, and for a
8379 /// subtitle lane, which carries no picture and no sound
8380 /// ([`Project::place_sub`] is its door).
8381 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
8382 if clip.out_frame <= clip.in_frame
8383 || lane.kind == LaneKind::Subtitle
8384 || self.index(lane).is_none()
8385 || self.cycles(&clip)
8386 {
8387 return false;
8388 }
8389 self.snapshot();
8390 let clip = Clip {
8391 fade_in: 0,
8392 fade_out: 0,
8393 transition_out: 0,
8394 transition_kind: Default::default(),
8395 start: timeline_frame,
8396 link: None,
8397 ..clip
8398 };
8399 self.insert_over(lane, clip, &[]);
8400 true
8401 }
8402
8403 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
8404 /// one grouped take -- what a picture let go over a further video track
8405 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
8406 /// if it is not there yet (the `+ V` button adds a video row alone). Without
8407 /// this half a file with sound landed on a layer silent, and the only way to
8408 /// hear it was to drop it a second time on an audio lane.
8409 ///
8410 /// Both halves overwrite what they land on and neither ripples, exactly as
8411 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
8412 /// nothing under it moves. One history snapshot for the pair, the added lane
8413 /// included, so one [`Project::undo`] takes the whole placement back. The two
8414 /// carry one link, which is what makes them one take to a drag, a trim and a
8415 /// save.
8416 ///
8417 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
8418 /// there or is not a video lane: sound placed alone is
8419 /// [`place`](Project::place)'s door, and a still has no sound to pair.
8420 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
8421 if clip.out_frame <= clip.in_frame
8422 || lane.kind != LaneKind::Video
8423 || self.index(lane).is_none()
8424 || self.cycles(&clip)
8425 {
8426 return false;
8427 }
8428 self.snapshot();
8429 // `A2` for `V2` -- and the rows between it and the last audio lane, since
8430 // an ord names a lane only while every ord below it does.
8431 while self.lane_count(LaneKind::Audio) <= lane.ord {
8432 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
8433 }
8434 let clip = Clip {
8435 fade_in: 0,
8436 fade_out: 0,
8437 transition_out: 0,
8438 transition_kind: Default::default(),
8439 start: timeline_frame,
8440 link: Some(self.new_link()),
8441 ..clip
8442 };
8443 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
8444 self.insert_over(half, clip.clone(), &[]);
8445 }
8446 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8447 true
8448 }
8449
8450 /// A source range onto the timeline at `at`, the way an editor's
8451 /// three-point edit puts it: `items` are the `(lane, clip)` halves of one
8452 /// take (a picture on a video lane, its sound on an audio lane, or either
8453 /// alone), each landing with its head on `at` whatever `clip.start` says.
8454 ///
8455 /// * [`SourceEdit::Overwrite`] replaces what is there for the take's length:
8456 /// a clip it covers is trimmed or split around it, and nothing moves.
8457 /// * [`SourceEdit::Insert`] opens room first: on the lanes the items land
8458 /// on, a clip `at` falls inside is cut there and everything from `at` on
8459 /// moves later by the take's length. Lanes that are not item lanes do not
8460 /// move and are never cut -- so, as in a scoped ripple
8461 /// ([`Project::scope_holds_takes_whole`]), a take that would be pulled
8462 /// apart by it (one half on an item lane, the other not) refuses the
8463 /// insert by name. Captions keep their own clock, as a paste leaves them.
8464 ///
8465 /// The halves share one fresh link when there are several and run the same
8466 /// length; a lone half belongs to no group. Exactly one history snapshot,
8467 /// so one [`Project::undo`] takes the whole edit back. Changes the
8468 /// timeline->source mapping: the caller must reseek.
8469 ///
8470 /// Refused, changing nothing and costing no undo step, for no items, a lane
8471 /// that is not there, is locked or is a caption lane, a lane twice, a source
8472 /// that is not there or cannot play on the lane (a song on a video lane, a
8473 /// still on an audio one), an empty range, a start or ripple that would pass
8474 /// the last frame there is, and an insert inside a speeded clip at a frame
8475 /// its rate cannot cut.
8476 pub fn edit_from_source(&mut self, kind: SourceEdit, at: u32, items: &[(Lane, Clip)]) -> crate::Result<()> {
8477 if items.is_empty() {
8478 return Err("nothing to place".into());
8479 }
8480 let labels = handles(&self.lanes);
8481 let mut on: Vec<usize> = Vec::with_capacity(items.len());
8482 for (lane, clip) in items {
8483 let Some(i) = self.index(*lane) else {
8484 return Err(format!("no {} track on this timeline", lane.label()).into());
8485 };
8486 if lane.kind == LaneKind::Subtitle {
8487 return Err(format!("{} is a caption track: a source cannot go on it", labels[i].label()).into());
8488 }
8489 if on.contains(&i) {
8490 return Err(format!("{} is named twice", labels[i].label()).into());
8491 }
8492 if self.lanes[i].locked {
8493 return Err(format!("{} is locked: unlock it to edit it", labels[i].label()).into());
8494 }
8495 if is_sequence_source(clip.source) {
8496 return Err("a sequence is placed with the sequence ops, not as a source".into());
8497 }
8498 let Some(source) = self.sources.get(clip.source) else {
8499 return Err("that source is not in the project".into());
8500 };
8501 if clip.out_frame <= clip.in_frame {
8502 return Err("the range to place is empty".into());
8503 }
8504 if lane.kind == LaneKind::Video && crate::is_audio(&source.path) {
8505 return Err(format!("that source has no picture: it cannot go on {}", labels[i].label()).into());
8506 }
8507 if lane.kind == LaneKind::Audio && crate::is_image(&source.path) {
8508 return Err(format!("a still has no sound: it cannot go on {}", labels[i].label()).into());
8509 }
8510 on.push(i);
8511 }
8512 let len = items.iter().map(|(_, c)| c.frames()).max().unwrap_or(0);
8513 if len == 0 || at.checked_add(len).is_none() {
8514 return Err("the range to place is empty or runs past the last frame there is".into());
8515 }
8516 if kind == SourceEdit::Insert {
8517 for &i in &on {
8518 let clips = &self.lanes[i].clips;
8519 if clips.iter().any(|c| c.end() > at && c.end().checked_add(len).is_none()) {
8520 return Err("the insert would push a clip past the last frame there is".into());
8521 }
8522 if clips.iter().any(|c| c.start < at && at < c.end()) && splittable(clips, at).is_none() {
8523 return Err(format!(
8524 "{} cannot be cut at frame {at}: the clip there plays at a rate that has no source frame at it; pick a neighbouring frame",
8525 labels[i].label()
8526 )
8527 .into());
8528 }
8529 }
8530 self.scope_holds_takes_whole(&on, at)?;
8531 }
8532 self.snapshot();
8533 if kind == SourceEdit::Insert {
8534 self.write_split(at, false, &on);
8535 for &i in &on {
8536 for c in self.lanes[i].clips.iter_mut().filter(|c| c.start >= at) {
8537 c.start += len;
8538 }
8539 }
8540 }
8541 let link = (items.len() > 1 && items.iter().all(|(_, c)| c.frames() == len)).then(|| self.new_link());
8542 // A take the overwrite cuts through keeps its take, when every member of it sits on a lane
8543 // this edit writes: each member is then cut at the same frames, so the head keeps the id and
8544 // the tail takes one fresh id shared by them all. A take with a member on a lane left alone
8545 // would be cut out of step with it, so it is detached as a delete detaches it.
8546 let end = at + len;
8547 let mut straddled: Vec<u32> = Vec::new();
8548 for &i in &on {
8549 for c in &self.lanes[i].clips {
8550 if let Some(id) = c.link.filter(|_| c.start < end && c.end() > at)
8551 && !straddled.contains(&id)
8552 {
8553 straddled.push(id);
8554 }
8555 }
8556 }
8557 let mut keep: Vec<(u32, u32)> = Vec::new();
8558 for id in straddled {
8559 let whole = self
8560 .lanes
8561 .iter()
8562 .enumerate()
8563 .all(|(j, d)| on.contains(&j) || !d.clips.iter().any(|c| c.link == Some(id)));
8564 if whole {
8565 keep.push((id, self.new_link()));
8566 }
8567 }
8568 for (lane, clip) in items {
8569 let clip = Clip {
8570 fade_in: 0,
8571 fade_out: 0,
8572 transition_out: 0,
8573 transition_kind: Default::default(),
8574 start: at,
8575 link,
8576 ..clip.clone()
8577 };
8578 self.insert_over(*lane, clip, &keep);
8579 }
8580 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8581 Ok(())
8582 }
8583
8584 /// `clip` into `lane` at its own start, over whatever it lands on: the
8585 /// insert both placement doors make, which is what keeps a lane sorted and
8586 /// disjoint. The caller has checked that the lane is there.
8587 fn insert_over(&mut self, lane: Lane, clip: Clip, keep: &[(u32, u32)]) {
8588 let clips = self.lane_mut(lane).expect("the caller checked the lane");
8589 // The pieces a cut leaves keep their take where `keep` says so (see `edit_from_source`);
8590 // everywhere else a straddled clip's pieces are detached.
8591 clear_with(clips, clip.start, clip.end(), &mut |link| match link.and_then(|id| keep.iter().find(|k| k.0 == id)) {
8592 Some(&(head, tail)) => (Some(head), Some(tail)),
8593 None => (None, None),
8594 });
8595 let idx = clips.partition_point(|c| c.start < clip.start);
8596 clips.insert(idx, clip);
8597 debug_assert!(sorted_disjoint(clips));
8598 }
8599
8600 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
8601 /// frame `start`: the drag that rearranges takes, along a track and across
8602 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
8603 /// was. `start` at the clip's own is the pure lane change.
8604 ///
8605 /// The whole group travels the same distance, each half on the lane it
8606 /// already sits on -- a link means "these cover one span on however many
8607 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
8608 /// sound would be a group no save could load. Only the dragged half changes
8609 /// lane, and that is not a desync: a link names no lane at all.
8610 ///
8611 /// `start` is **clamped**, never refused, to the room the group has: no
8612 /// member crosses a neighbour on the lane it lands on, exactly as
8613 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
8614 /// dragging past a neighbour means "as far as it goes", and butting up
8615 /// against the take next door is how clips are laid end to end. The
8616 /// tightest member's wall wins, so a sound half boxed in between two others
8617 /// holds its picture still.
8618 ///
8619 /// Refused, changing nothing and costing no undo step, for a lane that is
8620 /// not there, an index that is not there, a move across *kinds* (a picture
8621 /// cannot play on an audio lane, and the save it wrote would not open
8622 /// again), a head let go *inside* another clip or into a gap too narrow to
8623 /// hold this one -- a move that overwrote what it landed on would destroy a
8624 /// take the pointer never named, which is what [`place`](Project::place)
8625 /// may do and a drag may not -- a half let go onto the lane its own partner
8626 /// is on, and a drop that changes neither lane nor frame, which is a clip
8627 /// picked up and put back down, i.e. a click.
8628 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
8629 self.move_selection(&[(from, idx)], from, idx, to, start)
8630 }
8631
8632 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
8633 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
8634 /// reads it) travels the same distance as the clip at `idx` of `from`,
8635 /// which alone changes lane, onto `to`. One clamp across the whole set
8636 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
8637 /// neighbour that boxes in *any* member narrows the delta every member
8638 /// moves by, and a member with no room at all (`lo > hi`) refuses the
8639 /// whole set rather than moving the rest and leaving that one behind.
8640 /// `move_clip` is this with a selection of one -- the dragged clip's own
8641 /// group and nothing else -- so a drag on a clip outside the selection is
8642 /// byte-identical to before this existed.
8643 pub fn move_selection(
8644 &mut self,
8645 picks: &[(Lane, usize)],
8646 from: Lane,
8647 idx: usize,
8648 to: Lane,
8649 start: u32,
8650 ) -> bool {
8651 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).cloned()) else {
8652 return false;
8653 };
8654 if from.kind != to.kind {
8655 return false;
8656 }
8657 let held = self.index(from).expect("the clip was found on it");
8658 // Every pick's own group, unioned: the whole selection moves as one,
8659 // and a pick's link partners (not themselves picked) come along with
8660 // it exactly as a lone drag's do.
8661 let mut members = Members::default();
8662 for &(lane, i) in picks {
8663 let Some(group) = self.group_of(lane, i) else {
8664 continue;
8665 };
8666 for m in group.clips {
8667 if !members.clips.contains(&m) {
8668 members.clips.push(m);
8669 }
8670 }
8671 for m in group.subs {
8672 if !members.subs.contains(&m) {
8673 members.subs.push(m);
8674 }
8675 }
8676 }
8677 if !members.clips.contains(&(held, idx)) {
8678 members.clips.push((held, idx));
8679 }
8680 // The two halves of *the dragged clip's own* group would land on one
8681 // span of one lane, which is the one thing a link may never mean --
8682 // checked against that group alone, not the whole moving set: an
8683 // unlinked fellow pick already sitting on `dest` is no conflict at
8684 // all, since it travels by the same delta and `move_room` below
8685 // leaves it the room to. Refused rather than clamped: the partner
8686 // moves the same distance, so there is no room for it anywhere on
8687 // that lane.
8688 let own_group = self.group_of(from, idx).expect("the clip was found");
8689 if dest != held
8690 && own_group
8691 .clips
8692 .iter()
8693 .chain(&own_group.subs)
8694 .any(|&(l, _)| l == dest)
8695 {
8696 return false;
8697 }
8698 let want = i64::from(start) - i64::from(clip.start);
8699 // First the placement as asked: every member's span shifted by the one
8700 // delta the pointer named, each read against the gap it would land in.
8701 // A drop on empty frames lands exactly there -- jumping over whatever
8702 // clips lie between, on its lane and its linked partners' -- and only
8703 // a member whose new span would meet another clip refuses it.
8704 let as_asked = self
8705 .move_room(&members, Some((held, idx, dest, start)), Some(want))
8706 .filter(|&(lo, hi)| lo <= want && want <= hi);
8707 // Otherwise the drag as it always was: how far the group may travel,
8708 // in timeline frames and signed, with every member narrowing it to the
8709 // gap it stands in (its own lane, or the lane the pointer let it go
8710 // over), and what is left is what the pointer is clamped to.
8711 let Some((lo, hi)) = as_asked.or_else(|| {
8712 self.move_room(&members, Some((held, idx, dest, start)), None)
8713 }) else {
8714 return false;
8715 };
8716 if lo > hi {
8717 return false;
8718 }
8719 let delta = want.clamp(lo, hi);
8720 if delta == 0 && dest == held {
8721 return false;
8722 }
8723 self.snapshot();
8724 for &(l, i) in &members.clips {
8725 let c = &mut self.lanes[l].clips[i];
8726 // In range by the walls above, which are `u32` frames throughout.
8727 c.start = (i64::from(c.start) + delta) as u32;
8728 }
8729 for &(l, i) in &members.subs {
8730 let s = &mut self.lanes[l].subs[i];
8731 s.start = (i64::from(s.start) + delta) as u32;
8732 }
8733 if dest != held {
8734 let clip = self.lanes[held].clips.remove(idx);
8735 let clips = &mut self.lanes[dest].clips;
8736 let at = clips.partition_point(|c| c.start < clip.start);
8737 clips.insert(at, clip);
8738 }
8739 // A jump can carry a member past clips it did not pass before, on its
8740 // own lane as much as onto another, so every lane the set touched is
8741 // put back in order. The members keep their spacing among themselves
8742 // (one delta), so the order is all that can have changed.
8743 let mut touched: Vec<usize> = members
8744 .clips
8745 .iter()
8746 .chain(&members.subs)
8747 .map(|&(l, _)| l)
8748 .chain([dest])
8749 .collect();
8750 touched.sort_unstable();
8751 touched.dedup();
8752 for l in touched {
8753 self.lanes[l].clips.sort_by_key(|c| c.start);
8754 self.lanes[l].subs.sort_by_key(|s| s.start);
8755 }
8756 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
8757 debug_assert!(members.clips.iter().chain(&members.subs).all(|&(l, _)| {
8758 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
8759 }));
8760 true
8761 }
8762
8763 /// How far a group drag may travel, `(least, most)` in timeline frames and
8764 /// signed: every member narrows the range to the gap it is landing in --
8765 /// the clips against their lanes' clips and the captions against their
8766 /// lanes' captions -- and what is left is what the pointer is clamped to.
8767 /// `travelling` names the one member that changes lane, if any: the clip a
8768 /// hand is carrying onto another track, whose walls are read on the lane it
8769 /// is let go over at the frame the pointer named. `None` when a member has
8770 /// no gap to land in at all.
8771 ///
8772 /// `requested`, when given, reads every member's walls where it would sit
8773 /// with the whole group shifted by that many frames, rather than where it
8774 /// stands; a member whose requested spot is inside another placement, or
8775 /// has no gap wide enough, is `None`.
8776 fn move_room(
8777 &self,
8778 members: &Members,
8779 travelling: Option<(usize, usize, usize, u32)>,
8780 requested: Option<i64>,
8781 ) -> Option<(i64, i64)> {
8782 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
8783 for &(l, i) in members.clips.iter().chain(&members.subs) {
8784 let sub = members.subs.contains(&(l, i));
8785 let (start, frames) = match self.lanes[l]
8786 .clips
8787 .get(i)
8788 .filter(|_| !sub)
8789 .map(|c| (c.start, c.frames()))
8790 {
8791 Some(pair) => pair,
8792 None => {
8793 let s = self.lanes[l].subs.get(i)?;
8794 (s.start, s.frames)
8795 }
8796 };
8797 let land = travelling
8798 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
8799 .map_or(l, |(_, _, dest, _)| dest);
8800 // Which gap this member's walls are read off: its own place on the
8801 // lane it stays on, and the frame the pointer named on the lane it
8802 // is let go over. A clip's neighbours are the clips of the lane it
8803 // lands on and a caption's are its captions -- the two lists of one
8804 // lane never meet.
8805 let at = match (requested, travelling) {
8806 (Some(shift), _) => match u32::try_from(i64::from(start) + shift) {
8807 Ok(at) => at,
8808 Err(_) => return None,
8809 },
8810 (None, Some((fl, fi, _, asked))) if (fl, fi) == (l, i) && land != l => asked,
8811 (None, _) => start,
8812 };
8813 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
8814 let neighbours: Vec<(u32, u32)> = if sub {
8815 self.lanes[land]
8816 .subs
8817 .iter()
8818 .map(|s| (s.start, s.end()))
8819 .collect()
8820 } else {
8821 self.lanes[land]
8822 .clips
8823 .iter()
8824 .map(|c| (c.start, c.end()))
8825 .collect()
8826 };
8827 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
8828 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
8829 continue;
8830 }
8831 if *other_start <= at && at < *other_end {
8832 // A head let go inside another placement, which a clamp
8833 // has no answer for: the drop is refused.
8834 return None;
8835 }
8836 match other_end <= &at {
8837 true => wall_lo = wall_lo.max(*other_end),
8838 false => wall_hi = wall_hi.min(*other_start),
8839 }
8840 }
8841 if wall_hi - wall_lo < frames {
8842 return None;
8843 }
8844 lo = lo.max(i64::from(wall_lo) - i64::from(start));
8845 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
8846 }
8847 Some((lo, hi))
8848 }
8849
8850 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
8851 /// the drag on a clip's end that makes it play more or less of its source.
8852 /// The rest of the lane stays exactly where it is (nothing ripples), so what
8853 /// a shortened clip leaves behind is a gap and what a lengthened one takes
8854 /// is room that was already empty. One snapshot, so a whole drag is one
8855 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
8856 /// sample. Changes the timeline->source mapping: the caller must reseek.
8857 ///
8858 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
8859 /// exactly what they played before, which is what makes this a trim and not
8860 /// a slip.
8861 ///
8862 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
8863 /// legal means "as far as it goes", and stopping the box there is the
8864 /// affordance. The walls are: one frame of clip always survives, an edge
8865 /// never crosses the neighbouring clip on its own lane, an in-point never
8866 /// walks back past the source's first frame, and an out-point never runs
8867 /// past `source_frames[clip.source]` -- the caller's table of how long each
8868 /// source actually is ([`Project`] does not know, and a clip ending past its
8869 /// file's last frame is a save that will not open again; see
8870 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
8871 /// there may not grow at all.
8872 ///
8873 /// Linked placements trim *together*, by one delta: every member's same
8874 /// edge moves the distance the dragged one did, clamped to the room its
8875 /// own walls leave -- offsets between the members of a hand-built group
8876 /// survive the trim, exactly as they survive a drag.
8877 ///
8878 /// `false`, changing nothing and costing no undo step, for an index that is
8879 /// not there and for an edge that is already where it was asked to go.
8880 pub fn trim(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, source_frames: &[u32]) -> bool {
8881 self.trim_with_walls(lane, idx, edge, to, SourceWalls::same(source_frames))
8882 }
8883
8884 /// [`trim`](Project::trim) measured against each lane's own table
8885 /// ([`SourceWalls`]): what a linked take needs, since its audio and picture
8886 /// members end on different frames.
8887 pub fn trim_with_walls(
8888 &mut self,
8889 lane: Lane,
8890 idx: usize,
8891 edge: Edge,
8892 to: u32,
8893 walls: SourceWalls<'_>,
8894 ) -> bool {
8895 let (Some((lo, hi)), Some(clip)) = (
8896 self.trim_room_with_walls(lane, idx, edge, walls),
8897 self.lane(lane).get(idx).cloned(),
8898 ) else {
8899 return false;
8900 };
8901 let to = to.clamp(lo, hi);
8902 let at = match edge {
8903 Edge::Start => clip.start,
8904 Edge::End => clip.end(),
8905 };
8906 if to == at {
8907 return false;
8908 }
8909 // Worked out before anything moves: at a slow rate a room can be too
8910 // narrow to hold even one source frame ([`Speed::fit`]), and the
8911 // dragged clip refusing to fit must refuse the whole gesture rather
8912 // than be given a range wider than its room -- which is the overlap
8913 // the lane invariant exists to forbid. The walls below leave that room,
8914 // so this is the backstop for a project that came in through another
8915 // door.
8916 // A ramp's head is not moved yet: its keys are measured from the clip's own
8917 // start, so a head trim would have to rebase them. Refused, as a split is.
8918 if matches!(edge, Edge::Start) && !clip.speed_keys.is_empty() {
8919 return false;
8920 }
8921 let room = match edge {
8922 // The frames that stay play what they played, so what survives is
8923 // measured from the *end*.
8924 Edge::Start => clip.end() - to,
8925 Edge::End => to - clip.start,
8926 };
8927 let Some(keep) = clip.fit_source(room) else {
8928 return false;
8929 };
8930 // An end edge never keeps more source than the source has past the
8931 // in-point: [`Speed::fit`] rounds by the same footprint the wall does, so
8932 // at a fast rate it can name one frame past the source's end, one the wall
8933 // (`clip_walls`) never offers. Held to the wall, the edit it commits is
8934 // the edit a save will accept.
8935 let keep = keep.min(keep_cap(&clip, edge, walls.for_kind(lane.kind)));
8936 let members = self.group_of(lane, idx).expect("checked above");
8937 self.snapshot();
8938 let still = self.is_still(&clip);
8939 let held = self.index(lane).expect("checked above");
8940 write_trim(&mut self.lanes[held].clips[idx], edge, to, keep, still);
8941 rekey_trimmed(&mut self.lanes[held].clips[idx], &clip, edge, still);
8942 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
8943 self.follow_group(
8944 &members,
8945 &(held, idx),
8946 edge,
8947 i64::from(to) - i64::from(at),
8948 walls,
8949 );
8950 true
8951 }
8952
8953 /// **Ripple trim**: [`trim`](Project::trim), except that the hole the trim leaves is closed
8954 /// (or opened) and what comes after moves with the edge, as Premiere's ripple trim does. A
8955 /// start edge keeps the clip where it began and cuts its head out, so the clips behind it
8956 /// move up by as much; an end edge moves what follows by the length it gained or lost. A
8957 /// linked member moves the same way on its own lane. The room an end edge may grow into is
8958 /// still the room its neighbour leaves, as a plain trim's is. One undo step.
8959 pub fn ripple_trim(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, source_frames: &[u32]) -> bool {
8960 self.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls::same(source_frames))
8961 }
8962
8963 /// [`ripple_trim`](Project::ripple_trim) measured against each lane's own table
8964 /// ([`SourceWalls`]), as [`trim_with_walls`](Project::trim_with_walls) is.
8965 pub fn ripple_trim_with_walls(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, walls: SourceWalls<'_>) -> bool {
8966 let Some(members) = self.group_of(lane, idx) else {
8967 return false;
8968 };
8969 let before: Vec<(usize, usize, u32, u32)> = members
8970 .clips
8971 .iter()
8972 .filter_map(|&(l, i)| self.lanes[l].clips.get(i).map(|c| (l, i, c.start, c.end())))
8973 .collect();
8974 if !self.trim_with_walls(lane, idx, edge, to, walls) {
8975 return false;
8976 }
8977 for (l, i, old_start, old_end) in before {
8978 let clip = &self.lanes[l].clips[i];
8979 let (new_start, new_end) = (clip.start, clip.end());
8980 match edge {
8981 Edge::Start => {
8982 // The head went (or came back): the clip starts where it did, and the
8983 // hole between it and what it was cut from closes behind it.
8984 let g = i64::from(new_start) - i64::from(old_start);
8985 if g != 0 {
8986 // Back in place first: `shift_behind` checks the whole lane, and the clip
8987 // still starting at the trimmed head would overlap what moves up.
8988 self.lanes[l].clips[i].start = old_start;
8989 shift_behind(&mut self.lanes[l], old_end, -g);
8990 }
8991 }
8992 Edge::End => {
8993 let g = i64::from(new_end) - i64::from(old_end);
8994 if g != 0 {
8995 shift_behind(&mut self.lanes[l], old_end, g);
8996 }
8997 }
8998 }
8999 }
9000 true
9001 }
9002
9003 /// The rest of a group after one member's `edge` has moved by `delta`:
9004 /// every other member's same edge moves the same distance, clamped to the
9005 /// room its own walls leave -- a clip's against its lane and its source,
9006 /// a caption's against its own lane, its window following by the
9007 /// placement's own proportion. The undo step is the caller's: this is the
9008 // second half of one edit, not an edit of its own.
9009 fn follow_group(
9010 &mut self,
9011 members: &Members,
9012 dragged: &(usize, usize),
9013 edge: Edge,
9014 delta: i64,
9015 walls: SourceWalls<'_>,
9016 ) {
9017 for &(l, i) in &members.clips {
9018 if (l, i) == *dragged {
9019 continue;
9020 }
9021 let old = self.lanes[l].clips[i].clone();
9022 let c = &old;
9023 let at = match edge {
9024 Edge::Start => c.start,
9025 Edge::End => c.end(),
9026 };
9027 let (lo, hi) = self.clip_room(l, i, edge, walls);
9028 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
9029 if to == at {
9030 continue;
9031 }
9032 let room = match edge {
9033 Edge::Start => c.end() - to,
9034 Edge::End => to - c.start,
9035 };
9036 if matches!(edge, Edge::Start) && !c.speed_keys.is_empty() {
9037 continue;
9038 }
9039 let Some(keep) = c.fit_source(room) else {
9040 continue;
9041 };
9042 // Held to the member's own source, as the dragged clip is.
9043 let keep = keep.min(keep_cap(c, edge, walls.for_kind(self.lanes[l].kind)));
9044 let still = self.is_still(&self.lanes[l].clips[i]);
9045 write_trim(&mut self.lanes[l].clips[i], edge, to, keep, still);
9046 rekey_trimmed(&mut self.lanes[l].clips[i], &old, edge, still);
9047 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9048 }
9049 for &(l, i) in &members.subs {
9050 if (l, i) == *dragged {
9051 continue;
9052 }
9053 let s = self.lanes[l].subs[i];
9054 let at = match edge {
9055 Edge::Start => s.start,
9056 Edge::End => s.end(),
9057 };
9058 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
9059 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
9060 if to == at {
9061 continue;
9062 }
9063 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
9064 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
9065 }
9066 }
9067
9068 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
9069 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
9070 /// What a front-end drawing the box *during* a drag asks, so the live width
9071 /// is the width the release will commit and an edge stops under the pointer
9072 /// rather than snapping back. The **clip's own** walls: the rest of its
9073 /// group follows by the same delta within their own ([`follow_group`]), so
9074 /// what is drawn for the dragged edge is what its own clip will commit.
9075 /// `None` for an index that is not there.
9076 pub fn trim_room(
9077 &self,
9078 lane: Lane,
9079 idx: usize,
9080 edge: Edge,
9081 source_frames: &[u32],
9082 ) -> Option<(u32, u32)> {
9083 self.trim_room_with_walls(lane, idx, edge, SourceWalls::same(source_frames))
9084 }
9085
9086 /// [`trim_room`](Project::trim_room) against each lane's own table.
9087 pub fn trim_room_with_walls(
9088 &self,
9089 lane: Lane,
9090 idx: usize,
9091 edge: Edge,
9092 walls: SourceWalls<'_>,
9093 ) -> Option<(u32, u32)> {
9094 let l = self.index(lane)?;
9095 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, walls))
9096 }
9097
9098 /// [`trim_room`](Project::trim_room) with the same two walls, and for each
9099 /// one whether it is the source's media limit (head for a start edge, tail
9100 /// for an end edge) rather than a neighbouring clip. Stills never report
9101 /// media. `None` for an index that is not there.
9102 pub fn trim_walls(
9103 &self,
9104 lane: Lane,
9105 idx: usize,
9106 edge: Edge,
9107 source_frames: &[u32],
9108 ) -> Option<TrimWalls> {
9109 self.trim_walls_with_walls(lane, idx, edge, SourceWalls::same(source_frames))
9110 }
9111
9112 /// [`trim_walls`](Project::trim_walls) against each lane's own table.
9113 pub fn trim_walls_with_walls(
9114 &self,
9115 lane: Lane,
9116 idx: usize,
9117 edge: Edge,
9118 walls: SourceWalls<'_>,
9119 ) -> Option<TrimWalls> {
9120 let l = self.index(lane)?;
9121 (idx < self.lanes[l].clips.len()).then(|| self.clip_walls(l, idx, edge, walls).0)
9122 }
9123
9124 /// [`trim_walls`](Project::trim_walls) with each wall's bound named: what
9125 /// sets the low wall and what the high one, as a [`WallBound`]. The same
9126 /// walls, so a trim to one of them lands on the bound named for it. Asked
9127 /// before the trim: a clip committed at a wall sits on it, and the name is
9128 /// the one for the place it was asked to go. `None` for a bad index.
9129 pub fn trim_bounds(
9130 &self,
9131 lane: Lane,
9132 idx: usize,
9133 edge: Edge,
9134 walls: SourceWalls<'_>,
9135 ) -> Option<(WallBound, WallBound)> {
9136 let l = self.index(lane)?;
9137 (idx < self.lanes[l].clips.len()).then(|| {
9138 let (_, lo, hi) = self.clip_walls(l, idx, edge, walls);
9139 (lo, hi)
9140 })
9141 }
9142
9143 // ---- roll, slip, slide ------------------------------------------------
9144 //
9145 // The three trims that move *two* things at once, so no single-edge
9146 // [`trim`](Project::trim) can do them: the pair of edges at a cut, the
9147 // window a clip reads, the clip between its neighbours. Each is one undo
9148 // step, carries the clip's linked take along by the same delta, and is
9149 // measured against the same source tables a trim is. The engine ignores
9150 // locks, as everywhere: the front-end refuses first.
9151 //
9152 // Each plans the whole edit on clones and commits only a plan every member
9153 // can take *exactly*: at a rate that does not divide the frame grid a
9154 // timeline length can be unreachable for a source range ([`Speed::fit`]),
9155 // and an edit that lands one frame off would open a gap or an overlap and
9156 // move the timeline's length. The delta therefore backs off toward zero
9157 // until the plan is exact; a delta of zero is "no change" and costs no step.
9158
9159 /// `c` with its `edge` at timeline frame `to`, as [`trim`](Project::trim)
9160 /// would leave it, ignoring the neighbours (the caller owns them). `None`
9161 /// where a trim would refuse: a ramped head, no room for a source frame.
9162 fn edge_moved(&self, c: &Clip, edge: Edge, to: u32, table: &[u32]) -> Option<Clip> {
9163 if matches!(edge, Edge::Start) && !c.speed_keys.is_empty() {
9164 return None;
9165 }
9166 let still = self.is_still(c);
9167 let room = match edge {
9168 Edge::Start => c.end().checked_sub(to)?,
9169 Edge::End => to.checked_sub(c.start)?,
9170 };
9171 let keep = c.fit_source(room)?;
9172 let mut n = c.clone();
9173 match edge {
9174 Edge::End => n.out_frame = c.in_frame + keep.min(source_left(c, table)),
9175 Edge::Start if still => {
9176 n.in_frame = 0;
9177 n.out_frame = keep.min(table.get(c.source).copied().unwrap_or(c.len())).max(1);
9178 n.start = to;
9179 }
9180 Edge::Start => {
9181 n.in_frame = c.out_frame - keep.min(c.out_frame);
9182 n.start = to;
9183 }
9184 }
9185 rekey_trimmed(&mut n, c, edge, still);
9186 Some(n)
9187 }
9188
9189 /// The lane slot and index of every cut a roll at `(lane, idx)` moves: the
9190 /// clip before the cut first, then the same cut of each other member of its
9191 /// take that has a clip abutting behind it. `None` when `idx` has no clip
9192 /// abutting behind it.
9193 fn roll_pairs(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
9194 let l = self.index(lane)?;
9195 let abuts = |l: usize, i: usize| {
9196 let clips = &self.lanes[l].clips;
9197 matches!((clips.get(i), clips.get(i + 1)), (Some(a), Some(b)) if a.end() == b.start)
9198 };
9199 if lane.kind == LaneKind::Subtitle || !abuts(l, idx) {
9200 return None;
9201 }
9202 let members = self.group_of(lane, idx)?;
9203 let mut out = vec![(l, idx)];
9204 out.extend(members.clips.into_iter().filter(|&(ml, mi)| (ml, mi) != (l, idx) && abuts(ml, mi)));
9205 Some(out)
9206 }
9207
9208 /// How far the cut after `(l, i)` may travel on its media alone, as the
9209 /// delta range `(back, forward)` around where it is: the clip before it can
9210 /// play on to the end of its source, the one behind it back to the start of
9211 /// its own, and each keeps a frame.
9212 fn roll_span(&self, l: usize, i: usize, walls: SourceWalls<'_>) -> (i64, i64) {
9213 let (a, b) = (&self.lanes[l].clips[i], &self.lanes[l].clips[i + 1]);
9214 let t = walls.for_kind(self.lanes[l].kind);
9215 let cut = i64::from(a.end());
9216 if !b.speed_keys.is_empty() {
9217 return (0, 0);
9218 }
9219 let tail = i64::from(a.start)
9220 + i64::from(footprint(a, t.get(a.source).copied().unwrap_or(a.out_frame).saturating_sub(a.in_frame)));
9221 let head = if self.is_still(b) {
9222 i64::from(b.end()) - i64::from(b.speed.room(t.get(b.source).copied().unwrap_or(b.len())))
9223 } else {
9224 i64::from(b.start) - i64::from(footprint(b, b.in_frame))
9225 };
9226 let lo = head.max(0).max(i64::from(a.start) + i64::from(footprint(a, 1)));
9227 let hi = tail.min(i64::from(b.end()) - i64::from(footprint(b, 1)));
9228 ((lo - cut).min(0), (hi - cut).max(0))
9229 }
9230
9231 /// The two clips of the cut after `(l, i)` once it sits at `to`, or `None`
9232 /// when either cannot take it *exactly* (see the section note).
9233 fn rolled(&self, l: usize, i: usize, to: u32, walls: SourceWalls<'_>) -> Option<(Clip, Clip)> {
9234 let (a, b) = (&self.lanes[l].clips[i], &self.lanes[l].clips[i + 1]);
9235 let t = walls.for_kind(self.lanes[l].kind);
9236 let na = self.edge_moved(a, Edge::End, to, t)?;
9237 let nb = self.edge_moved(b, Edge::Start, to, t)?;
9238 (na.end() == to && nb.start == to && nb.end() == b.end()).then_some((na, nb))
9239 }
9240
9241 /// Where the cut at the end of the clip at `idx` of `lane` may travel,
9242 /// `(first, last)` timeline frame inclusive: the walls [`roll`](Project::roll)
9243 /// clamps to -- the media of both clips of every member of the take, and a
9244 /// frame of each. `None` for a clip with nothing abutting behind it.
9245 pub fn roll_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(u32, u32)> {
9246 let pairs = self.roll_pairs(lane, idx)?;
9247 let (back, fwd) = self.roll_delta_span(&pairs, walls);
9248 let cut = i64::from(self.lanes[pairs[0].0].clips[pairs[0].1].end());
9249 Some(((cut + back) as u32, (cut + fwd) as u32))
9250 }
9251
9252 fn roll_delta_span(&self, pairs: &[(usize, usize)], walls: SourceWalls<'_>) -> (i64, i64) {
9253 pairs.iter().fold((i64::MIN, i64::MAX), |(back, fwd), &(l, i)| {
9254 let (b, f) = self.roll_span(l, i, walls);
9255 (back.max(b), fwd.min(f))
9256 })
9257 }
9258
9259 /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to
9260 /// timeline frame `to`. The out-point of that clip and the in-point of the
9261 /// clip abutting behind it move together, so the pair keeps its joint span
9262 /// and nothing else on the lane moves: the timeline's length does not
9263 /// change. The frames that stay play what they played.
9264 ///
9265 /// Like [`trim`](Project::trim), `to` is clamped to the walls
9266 /// ([`roll_room`](Project::roll_room)), never refused. The rest of the take
9267 /// rolls its own cut by the same delta -- the ones that have a cut there --
9268 /// and the whole take is held to the tightest member. At a rate where the
9269 /// exact frame is unreachable the cut stops on the nearest one that is.
9270 ///
9271 /// `Some(cut)`: where the cut is now (the old place when nothing moved, at
9272 /// no cost in undo steps; one step otherwise). `None`, changing nothing:
9273 /// no clip there, or none abutting behind it -- a roll needs a cut. A
9274 /// speed-ramped clip behind the cut cannot take a new in-point (as a trim
9275 /// refuses a ramped head), which pins the cut.
9276 pub fn roll(&mut self, lane: Lane, idx: usize, to: u32, walls: SourceWalls<'_>) -> Option<u32> {
9277 let pairs = self.roll_pairs(lane, idx)?;
9278 let cut = i64::from(self.lanes[pairs[0].0].clips[pairs[0].1].end());
9279 let (back, fwd) = self.roll_delta_span(&pairs, walls);
9280 let mut d = (i64::from(to) - cut).clamp(back, fwd);
9281 let plan = loop {
9282 if d == 0 {
9283 return Some(cut as u32);
9284 }
9285 let plan: Option<Vec<_>> = pairs
9286 .iter()
9287 .map(|&(l, i)| {
9288 let at = i64::from(self.lanes[l].clips[i].end()) + d;
9289 let at = u32::try_from(at).ok()?;
9290 self.rolled(l, i, at, walls).map(|p| (l, i, p))
9291 })
9292 .collect();
9293 if let Some(plan) = plan {
9294 break plan;
9295 }
9296 d -= d.signum();
9297 };
9298 self.snapshot();
9299 for (l, i, (a, b)) in plan {
9300 self.lanes[l].clips[i] = a;
9301 self.lanes[l].clips[i + 1] = b;
9302 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9303 }
9304 Some((cut + d) as u32)
9305 }
9306
9307 /// The clips a slide at `(lane, idx)` moves, as lane slot and index: the
9308 /// clip itself first, then the rest of its take. `None` unless every one of
9309 /// them has a clip on both sides -- sliding needs neighbours to give to.
9310 fn slide_members(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
9311 let l = self.index(lane)?;
9312 if lane.kind == LaneKind::Subtitle || self.lanes[l].clips.get(idx).is_none() {
9313 return None;
9314 }
9315 let members = self.group_of(lane, idx)?;
9316 let mut out = vec![(l, idx)];
9317 out.extend(members.clips.into_iter().filter(|&m| m != (l, idx)));
9318 out.iter()
9319 .all(|&(ml, mi)| mi > 0 && mi + 1 < self.lanes[ml].clips.len())
9320 .then_some(out)
9321 }
9322
9323 /// How far the clip at `(l, i)` may slide on its neighbours' media alone, as
9324 /// the delta range `(back, forward)`. A neighbour it abuts gives or takes
9325 /// frames at its cut, up to its own media and a frame of itself; a
9326 /// neighbour across a gap only bounds the move where it begins.
9327 fn slide_span(&self, l: usize, i: usize, walls: SourceWalls<'_>) -> (i64, i64) {
9328 let clips = &self.lanes[l].clips;
9329 let (p, c, n) = (&clips[i - 1], &clips[i], &clips[i + 1]);
9330 let t = walls.for_kind(self.lanes[l].kind);
9331 let (start, end) = (i64::from(c.start), i64::from(c.end()));
9332 let (mut back, mut fwd) = (i64::MIN, i64::MAX);
9333 if p.end() == c.start {
9334 let tail = i64::from(p.start)
9335 + i64::from(footprint(p, t.get(p.source).copied().unwrap_or(p.out_frame).saturating_sub(p.in_frame)));
9336 back = back.max(i64::from(p.start) + i64::from(footprint(p, 1)) - start);
9337 fwd = fwd.min(tail - start);
9338 } else {
9339 back = back.max(i64::from(p.end()) - start);
9340 }
9341 if n.start == c.end() {
9342 if n.speed_keys.is_empty() {
9343 let head = if self.is_still(n) {
9344 i64::from(n.end()) - i64::from(n.speed.room(t.get(n.source).copied().unwrap_or(n.len())))
9345 } else {
9346 i64::from(n.start) - i64::from(footprint(n, n.in_frame))
9347 };
9348 back = back.max(head - end);
9349 fwd = fwd.min(i64::from(n.end()) - i64::from(footprint(n, 1)) - end);
9350 } else {
9351 back = back.max(0);
9352 fwd = fwd.min(0);
9353 }
9354 } else {
9355 fwd = fwd.min(i64::from(n.start) - end);
9356 }
9357 (back.min(0), fwd.max(0))
9358 }
9359
9360 /// The three clips of the slide at `(l, i)` once the middle one starts
9361 /// `d` frames later: the previous clip and the next one `None` when a gap
9362 /// (not a cut) lies on that side and so nothing there changes.
9363 fn slid(&self, l: usize, i: usize, d: i64, walls: SourceWalls<'_>) -> Option<(Option<Clip>, Clip, Option<Clip>)> {
9364 let clips = &self.lanes[l].clips;
9365 let (p, c, n) = (&clips[i - 1], &clips[i], &clips[i + 1]);
9366 let t = walls.for_kind(self.lanes[l].kind);
9367 let start = u32::try_from(i64::from(c.start) + d).ok()?;
9368 let end = start.checked_add(c.frames())?;
9369 let np = if p.end() == c.start {
9370 let np = self.edge_moved(p, Edge::End, start, t)?;
9371 (np.end() == start).then_some(())?;
9372 Some(np)
9373 } else {
9374 (start >= p.end()).then_some(())?;
9375 None
9376 };
9377 let nn = if n.start == c.end() {
9378 let nn = self.edge_moved(n, Edge::Start, end, t)?;
9379 (nn.start == end && nn.end() == n.end()).then_some(())?;
9380 Some(nn)
9381 } else {
9382 (end <= n.start).then_some(())?;
9383 None
9384 };
9385 Some((np, Clip { start, ..c.clone() }, nn))
9386 }
9387
9388 /// Where the clip at `idx` of `lane` may start when slid, `(first, last)`
9389 /// timeline frame inclusive: the walls [`slide`](Project::slide) clamps to.
9390 /// `None` for a clip that lacks a neighbour on either side (or any member
9391 /// of its take does).
9392 pub fn slide_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(u32, u32)> {
9393 let members = self.slide_members(lane, idx)?;
9394 let (back, fwd) = self.slide_delta_span(&members, walls);
9395 let start = i64::from(self.lanes[members[0].0].clips[members[0].1].start);
9396 Some(((start + back).max(0) as u32, (start + fwd).min(i64::from(u32::MAX)) as u32))
9397 }
9398
9399 fn slide_delta_span(&self, members: &[(usize, usize)], walls: SourceWalls<'_>) -> (i64, i64) {
9400 members.iter().fold((i64::MIN, i64::MAX), |(back, fwd), &(l, i)| {
9401 let (b, f) = self.slide_span(l, i, walls);
9402 (back.max(b), fwd.min(f))
9403 })
9404 }
9405
9406 /// **Slide**: starts the clip at `idx` of `lane` at timeline frame `to`,
9407 /// between its neighbours. Its content and length stay; the out-point of the
9408 /// clip before it and the in-point of the clip after it absorb the move
9409 /// (each gives or takes the frames at its cut), so the timeline's length
9410 /// does not change. A neighbour across a gap is not edited: the clip just
9411 /// may not run into it.
9412 ///
9413 /// Clamped like [`trim`](Project::trim) to [`slide_room`](Project::slide_room);
9414 /// the take slides by the same delta, held to its tightest member, and at a
9415 /// rate where the exact frame is unreachable stops on the nearest one that
9416 /// is. `Some(start)`: where the clip starts now (the old place when nothing
9417 /// moved, costing no undo step; one step otherwise). `None`, changing
9418 /// nothing: no clip, or no neighbour on a side -- the first and last clip
9419 /// of a lane have nothing to give or take. A speed-ramped clip *after* the
9420 /// slid one cannot take a new in-point, which pins the slide.
9421 pub fn slide(&mut self, lane: Lane, idx: usize, to: u32, walls: SourceWalls<'_>) -> Option<u32> {
9422 let members = self.slide_members(lane, idx)?;
9423 let start = i64::from(self.lanes[members[0].0].clips[members[0].1].start);
9424 let (back, fwd) = self.slide_delta_span(&members, walls);
9425 let mut d = (i64::from(to) - start).clamp(back, fwd);
9426 let plan = loop {
9427 if d == 0 {
9428 return Some(start as u32);
9429 }
9430 let plan: Option<Vec<_>> = members
9431 .iter()
9432 .map(|&(l, i)| self.slid(l, i, d, walls).map(|p| (l, i, p)))
9433 .collect();
9434 if let Some(plan) = plan {
9435 break plan;
9436 }
9437 d -= d.signum();
9438 };
9439 self.snapshot();
9440 for (l, i, (p, c, n)) in plan {
9441 if let Some(p) = p {
9442 self.lanes[l].clips[i - 1] = p;
9443 }
9444 self.lanes[l].clips[i] = c;
9445 if let Some(n) = n {
9446 self.lanes[l].clips[i + 1] = n;
9447 }
9448 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9449 }
9450 Some((start + d) as u32)
9451 }
9452
9453 /// The source frames that `by` timeline frames are worth for the clip at
9454 /// `idx` of `lane`: `by` itself at real time, `by * speed` at a constant
9455 /// rate and at the ramp's average rate for a ramped clip. Rounded to the
9456 /// nearest frame, so a tiny `by` on a slow clip can be zero. What a
9457 /// front-end turns a pointer or a typed timeline distance into before
9458 /// [`slip`](Project::slip), which works in the media's own frames.
9459 pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
9460 let c = self.lane(lane).get(idx)?;
9461 let (len, frames) = (i128::from(c.len()), i128::from(c.frames()));
9462 let n = i128::from(by) * len;
9463 // Round half away from zero.
9464 let r = (n.abs() * 2 + frames) / (frames * 2) * n.signum();
9465 Some(r as i64)
9466 }
9467
9468 /// How far the clip at `idx` of `lane` may slip, `(back, forward)` in
9469 /// source frames (`back <= 0 <= forward`): back to the first frame of the
9470 /// source and forward to its last, which is where the clip's own window
9471 /// stops. `None` for a bad index and for a still, which has no frames to
9472 /// slip through.
9473 pub fn slip_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(i64, i64)> {
9474 let l = self.index(lane)?;
9475 let c = self.lanes[l].clips.get(idx)?;
9476 if self.is_still(c) {
9477 return None;
9478 }
9479 let t = walls.for_kind(self.lanes[l].kind);
9480 let limit = i64::from(t.get(c.source).copied().unwrap_or(c.out_frame));
9481 Some((-i64::from(c.in_frame), (limit - i64::from(c.out_frame)).max(0)))
9482 }
9483
9484 /// **Slip**: shifts the source window of the clip at `idx` of `lane` by
9485 /// `by` source frames (see [`slip_source_delta`](Project::slip_source_delta)
9486 /// for timeline frames), later in the file for positive. Its place on the
9487 /// timeline and its length -- at its speed or ramp -- are unchanged: the
9488 /// same slot shows different content. Gain and placement keys stay on the
9489 /// footage they were set on.
9490 ///
9491 /// Clamped to [`slip_room`](Project::slip_room), never refused; the rest of
9492 /// the take slips by the same source frames, each within its own media. A
9493 /// source with no known length may not slip forward, as it may not grow in
9494 /// a trim. `Some(shift)`: the source frames the clip actually moved (`0`
9495 /// when pinned at a limit or asked for nothing, costing no undo step; one
9496 /// step otherwise). `None`, changing nothing: no clip, or a still.
9497 pub fn slip(&mut self, lane: Lane, idx: usize, by: i64, walls: SourceWalls<'_>) -> Option<i64> {
9498 let (lo, hi) = self.slip_room(lane, idx, walls)?;
9499 let d = by.clamp(lo, hi);
9500 if d == 0 {
9501 return Some(0);
9502 }
9503 let l = self.index(lane)?;
9504 let members = self.group_of(lane, idx)?;
9505 let mut plan: Vec<(usize, usize, Clip)> = Vec::new();
9506 for &(ml, mi) in &members.clips {
9507 let c = &self.lanes[ml].clips[mi];
9508 let t = walls.for_kind(self.lanes[ml].kind);
9509 let limit = i64::from(t.get(c.source).copied().unwrap_or(c.out_frame));
9510 let own = if (ml, mi) == (l, idx) {
9511 d
9512 } else if self.is_still(c) {
9513 continue;
9514 } else {
9515 d.clamp(-i64::from(c.in_frame), (limit - i64::from(c.out_frame)).max(0))
9516 };
9517 if own == 0 {
9518 continue;
9519 }
9520 let mut n = c.clone();
9521 n.in_frame = (i64::from(c.in_frame) + own) as u32;
9522 n.out_frame = (i64::from(c.out_frame) + own) as u32;
9523 if !c.transform_keys.is_empty() {
9524 n.transform_keys = keys_within(&c.transform_keys, n.in_frame, n.out_frame);
9525 }
9526 for (ne, ce) in n.effects.iter_mut().zip(&c.effects) {
9527 if !ce.keys.is_empty() {
9528 ne.keys = keys_within(&ce.keys, n.in_frame, n.out_frame);
9529 }
9530 }
9531 plan.push((ml, mi, n));
9532 }
9533 self.snapshot();
9534 for (ml, mi, n) in plan {
9535 self.lanes[ml].clips[mi] = n;
9536 }
9537 Some(d)
9538 }
9539
9540 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
9541 /// its lane's storage index: the one wall computation, asked for the clip
9542 /// itself and for each member a group trim carries.
9543 fn clip_room(&self, l: usize, i: usize, edge: Edge, walls: SourceWalls<'_>) -> (u32, u32) {
9544 let (w, _, _) = self.clip_walls(l, i, edge, walls);
9545 (w.lo, w.hi)
9546 }
9547
9548 /// The walls [`clip_room`](Self::clip_room) measures, with the media flags
9549 /// [`trim_walls`](Project::trim_walls) reports. Every wall is computed here
9550 /// once; the flags are read off the same comparisons that pick the wall.
9551 fn clip_walls(
9552 &self,
9553 l: usize,
9554 i: usize,
9555 edge: Edge,
9556 walls: SourceWalls<'_>,
9557 ) -> (TrimWalls, WallBound, WallBound) {
9558 // The lane's own table: a sound's length on an audio lane, the picture's
9559 // everywhere else.
9560 let source_frames = walls.for_kind(self.lanes[l].kind);
9561 let clips = &self.lanes[l].clips;
9562 let c = clips[i].clone();
9563 // A still has no media limit to report: its head and tail reach as far
9564 // as the caller's table says, which is a cap, not a source's end.
9565 let still = self.is_still(&c);
9566 let prev_end = i.checked_sub(1).map_or(0, |p| clips[p].end());
9567 let (lo, hi, lo_media, hi_media, lo_bound, hi_bound) = match edge {
9568 Edge::Start => {
9569 // Back to the source's own first frame -- as many *timeline*
9570 // frames as that head is worth at the clip's rate, which at
9571 // real time is the head itself -- and never over the clip in
9572 // front of it. Saturating because a clip may hold *more*
9573 // head than the timeline has room for -- a ripple delete
9574 // slides a clip back to frame 0 with its in-point wherever
9575 // the cut left it -- and frame 0 is the other wall.
9576 //
9577 // A still is measured from its *tail* instead: it has no
9578 // in-point worth the name (every frame the same picture), so
9579 // its head reaches exactly as far as its tail does -- out to
9580 // the length the caller's table gives it, whole. Measured
9581 // from the in-point it would have no head room at all, which
9582 // is a placed picture whose left edge cannot be dragged out.
9583 // No entry in the table means no growth, as it does at the
9584 // other end.
9585 let head = if still {
9586 c.end().saturating_sub(
9587 c.speed
9588 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
9589 )
9590 } else if c.reversed {
9591 // The head is the window's far end: what it can still grow into
9592 // is what the file has past the out-point.
9593 c.start.saturating_sub(c.speed.room(
9594 source_frames
9595 .get(c.source)
9596 .copied()
9597 .unwrap_or(c.out_frame)
9598 .saturating_sub(c.out_frame),
9599 ))
9600 } else {
9601 c.start.saturating_sub(c.speed.room(c.in_frame))
9602 };
9603 (
9604 head.max(prev_end),
9605 // One *frame of clip* always survives, and at a rate below
9606 // real time one frame of clip is several frames of timeline
9607 // ([`Speed::room`]): an edge dragged closer than that would
9608 // ask for a range no source frame fits in. At real time this
9609 // is `end - 1`, unchanged.
9610 c.end() - c.speed.room(1),
9611 // The head is the binding wall when it is not behind the
9612 // neighbour; equal walls count as media. With no neighbour
9613 // the wall is frame 0, which the head always meets or beats.
9614 !still && head >= prev_end,
9615 // The clip's own minimum length, not a neighbour or media.
9616 false,
9617 // A neighbour that sits on the same frame as the source's
9618 // head is named: the two walls coincide, and the neighbour is
9619 // the one a caller can move, so a tie is worded as it.
9620 if i > 0 && head <= prev_end {
9621 WallBound::Neighbour(prev_end)
9622 } else if still {
9623 WallBound::Cap
9624 } else {
9625 WallBound::Source
9626 },
9627 WallBound::MinLength,
9628 )
9629 }
9630 Edge::End => {
9631 // Out to whatever is left of the source -- again in timeline
9632 // frames, at this clip's rate -- and never over the clip
9633 // behind it.
9634 let tail = c.start.saturating_add(c.speed.room(match c.reversed {
9635 // The tail is the window's near end, which grows down to the
9636 // file's first frame.
9637 true => c.out_frame,
9638 false => source_frames
9639 .get(c.source)
9640 .copied()
9641 .unwrap_or(c.out_frame)
9642 .saturating_sub(c.in_frame),
9643 }));
9644 let next = clips.get(i + 1).map_or(u32::MAX, |n| n.start);
9645 (
9646 // ...and the same wall from the other end: the shortest this
9647 // clip can be is the room one source frame of it takes.
9648 c.start + c.speed.room(1),
9649 tail.min(next),
9650 false,
9651 // The tail is the binding wall when it is not past the
9652 // neighbour; equal walls count as media.
9653 !still && tail <= next,
9654 WallBound::MinLength,
9655 // A tie with the neighbour's start is named as the neighbour
9656 // too, for the same reason as the start edge's.
9657 if clips.get(i + 1).is_some() && tail >= next {
9658 WallBound::Neighbour(next)
9659 } else if still {
9660 WallBound::Cap
9661 } else {
9662 WallBound::Source
9663 },
9664 )
9665 }
9666 };
9667 // `hi.max(lo)`: for a clip the invariants hold for, the range always
9668 // contains the edge's own place, and a caller's wrong `source_frames`
9669 // must not become an empty range (or a panicking `clamp`) here.
9670 (
9671 TrimWalls {
9672 lo,
9673 hi: hi.max(lo),
9674 lo_media,
9675 hi_media,
9676 },
9677 lo_bound,
9678 hi_bound,
9679 )
9680 }
9681
9682 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
9683 /// every frame is the same picture, so which frame of it a clip's in-point
9684 /// names is not a question -- what [`Project::trim`] lets grow at either
9685 /// end. `false` for a source that is not there.
9686 fn is_still(&self, clip: &Clip) -> bool {
9687 self.sources
9688 .get(clip.source)
9689 .is_some_and(|s| crate::is_image(&s.path))
9690 }
9691
9692 /// The placements that move as one with the one at `idx` of `lane` --
9693 /// itself and whatever carries its link, on the media lanes and the
9694 /// subtitle ones alike. `None` for an index that is not there.
9695 /// Whether the clip at `idx` is in a take: its link is shared with another clip. A lone link
9696 /// (what [`ungroup`](Self::ungroup) leaves) is not a take, so the clip moves on its own.
9697 fn in_take(&self, lane: Lane, idx: usize) -> bool {
9698 self.group_of(lane, idx).is_some_and(|m| !m.alone())
9699 }
9700
9701 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
9702 let sub = lane.kind == LaneKind::Subtitle;
9703 let link = if sub {
9704 self.sub_lane(lane).get(idx)?.link
9705 } else {
9706 self.lane(lane).get(idx)?.link
9707 };
9708 let mut members = Members::default();
9709 match link {
9710 Some(link) => {
9711 for (l, data) in self.lanes.iter().enumerate() {
9712 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
9713 members.clips.push((l, i));
9714 }
9715 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
9716 members.subs.push((l, i));
9717 }
9718 }
9719 }
9720 None => {
9721 let l = self.index(lane).expect("the placement was found on it");
9722 if sub {
9723 members.subs.push((l, idx));
9724 } else {
9725 members.clips.push((l, idx));
9726 }
9727 }
9728 }
9729 Some(members)
9730 }
9731
9732 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
9733 /// new group, pushing everything from there on later by its length in
9734 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
9735 /// the clip it lands in is split around it; past the end of the timeline it
9736 /// goes down where it was asked for, with black in front of it -- which is
9737 /// what a library row let go on the open bed means, and what the ghost under
9738 /// the pointer promised. A clipboard means "put it here", not "here and
9739 /// black in front", and clamps to the end at its own door
9740 /// ([`crate::PlaybackSession::paste_at`]).
9741 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
9742 ///
9743 /// `V1` and `A1` and no other lane, because a take is one picture and one
9744 /// sound: copying it onto every lane there is would play the same audio
9745 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
9746 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
9747 /// video lane it is a clip that decodes to nothing, and a save carrying one
9748 /// does not open again -- and a still image ([`crate::is_image`]) reaches
9749 /// `V1` only, for the mirror of that reason. The room is still opened on
9750 /// every media lane, or the lanes it was not inserted into would slide out
9751 /// of step with the ones it was -- and the subtitle lanes are left alone:
9752 /// the words keep their own clock, and a caption that should travel with a
9753 /// clip is what a group is for.
9754 ///
9755 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
9756 /// Changes the timeline->source mapping: the caller must reseek. Refused for
9757 /// an empty `clip` and for one naming a source that is not there (both of
9758 /// which the public fields let a caller build), and for a paste whose ripple
9759 /// would push a clip past the last frame there is -- nothing is changed by
9760 /// any of them.
9761 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
9762 let source = self.sources.get(clip.source);
9763 let compound = is_sequence_source(clip.source);
9764 if source.is_none() && (!compound || self.compound_refusal(&clip).is_some()) {
9765 return false;
9766 }
9767 if clip.out_frame <= clip.in_frame {
9768 return false;
9769 }
9770 let audio_only = source.is_some_and(|s| crate::is_audio(&s.path));
9771 // ...and its mirror: a still is a picture and no sound, so a copy of one
9772 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
9773 // worker tries to demux -- which silences the *whole session*, not just
9774 // that clip -- and a save the engine's own `open_project` then refuses.
9775 let picture_only = source.is_some_and(|s| crate::is_image(&s.path));
9776 // The frame it was asked for and no other: a row let go on the empty
9777 // bed past the last clip lands *there*, under the ghost that promised
9778 // it, with black in front. Clamping to the end here made every drop on
9779 // open bed an append -- the clipboard's rule, applied to a hand that
9780 // had named a place.
9781 let at = timeline_frame;
9782 // The room it takes on the timeline, which its speed decides -- not the
9783 // source range it reads.
9784 let len = clip.frames();
9785 // Room for it: `open_room` adds `len` to every start from `at` on, and a
9786 // hand-written file may hold a clip that ends at the very last frame
9787 // (`edith::check` permits `start + len == u32::MAX`). Refused here
9788 // rather than wrapped there -- a wrapped start lands *behind* the clip
9789 // it belongs after, which is an overlap no save will read back.
9790 if at.checked_add(len).is_none()
9791 || self
9792 .lanes
9793 .iter()
9794 .flat_map(|l| &l.clips)
9795 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
9796 {
9797 return false;
9798 }
9799 // ...and room *to open*: the paste splits whatever it lands inside of,
9800 // and a speeded clip can only be cut where its own rate has a source
9801 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
9802 // of one, which is the overlap a lane may never hold. At real time every
9803 // frame answers, so this cannot refuse an unspeeded paste.
9804 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
9805 if self
9806 .lanes
9807 .iter()
9808 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
9809 {
9810 return false;
9811 }
9812 self.snapshot();
9813 let clip = Clip {
9814 fade_in: 0,
9815 fade_out: 0,
9816 transition_out: 0,
9817 transition_kind: Default::default(),
9818 start: at,
9819 link: Some(self.new_link()),
9820 ..clip
9821 };
9822 // Only lanes that can play the source: a file with no picture belongs on
9823 // an audio lane and nowhere else, exactly as `place_stream_at` decides
9824 // it for an import. On a video lane it would decode to nothing, and the
9825 // save it wrote would not open again.
9826 let kinds: &[LaneKind] = match (audio_only, picture_only) {
9827 (true, _) => &[LaneKind::Audio],
9828 (_, true) => &[LaneKind::Video],
9829 _ => &[LaneKind::Video, LaneKind::Audio],
9830 };
9831 let takes: Vec<usize> = kinds
9832 .iter()
9833 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
9834 .collect();
9835 for (i, data) in self.lanes.iter_mut().enumerate() {
9836 open_room(&mut data.clips, at, len);
9837 // The subtitle lanes are NOT touched: a paste inserts media, and
9838 // the words keep their own clock. Opening room here used to split
9839 // a caption the paste landed inside and slide the rest behind it
9840 // -- "a caption that stayed put while the picture moved on no
9841 // longer says the same thing" -- but a caption pinned to nothing
9842 // (and a video arriving on a timeline of words alone) has no
9843 // picture to follow, and the split did to the words what no hand
9844 // asked for. A caption that should travel with a clip is what a
9845 // group is for, and a group moves as one.
9846 if takes.contains(&i) {
9847 let idx = data.clips.partition_point(|c| c.start < at);
9848 data.clips.insert(idx, clip.clone());
9849 }
9850 debug_assert!(sorted_disjoint(&data.clips));
9851 debug_assert!(subs_sorted_disjoint(&data.subs));
9852 }
9853 true
9854 }
9855
9856 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
9857 /// `items` lands on the lane it names, its head moved by the offset every
9858 /// other item moves by too -- `at` less the earliest `start` among them,
9859 /// so the set's own gaps and lane assignment survive the trip from
9860 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
9861 /// way a lone clip's copy does.
9862 ///
9863 /// The links come back among the copies: clips that shared a link id in
9864 /// the set share one fresh id between them, distinct from every link in
9865 /// the project, so a picture and its sound pasted together stay linked. A
9866 /// clip whose link partner was not in the set comes back unlinked.
9867 ///
9868 /// All-or-nothing, and **refused** rather than opening room or splitting
9869 /// a neighbour the way [`paste`](Project::paste) does for one clip:
9870 /// a set-paste never ripples the bed, so a landing that overlaps so much
9871 /// as one existing clip on its own lane refuses the whole set, changing
9872 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
9873 /// clamps instead of refusing, but a paste has no drag to clamp against,
9874 /// and a landing moved off the frame asked for is not what a paste means.
9875 /// `items` empty, naming a lane or a source that is not there, or a clip
9876 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
9877 ///
9878 /// Exactly one history snapshot for the whole set, so one
9879 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
9880 /// on every lane an item lands on: the caller must reseek.
9881 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
9882 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
9883 return false;
9884 };
9885 // Resolved once, up front, off the lanes as they stand now: a lane or
9886 // source that is not there, or a landing that would overlap a
9887 // neighbour, refuses the whole set before any of it is written.
9888 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
9889 for (lane, clip) in items.iter().cloned() {
9890 let Some(li) = self.index(lane) else {
9891 return false;
9892 };
9893 let known = self.sources.get(clip.source).is_some()
9894 || (is_sequence_source(clip.source) && self.compound_refusal(&clip).is_none());
9895 if !known || clip.out_frame <= clip.in_frame {
9896 return false;
9897 }
9898 let delta = i64::from(clip.start) - i64::from(anchor);
9899 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
9900 return false;
9901 };
9902 let Some(end) = start.checked_add(clip.frames()) else {
9903 return false;
9904 };
9905 if self.lanes[li]
9906 .clips
9907 .iter()
9908 .any(|c| c.start < end && start < c.end())
9909 {
9910 return false;
9911 }
9912 landings.push((li, Clip { start, ..clip }));
9913 }
9914 // The links the copies carry among themselves. A clipboard link names
9915 // the take it was copied from: members that were copied together and
9916 // land on distinct lanes get one fresh id between them, so the take
9917 // stays a take. A member whose partner was not copied, or two members
9918 // forced onto one lane (a `lane` override), gets none, because a link
9919 // may never name two clips of one lane.
9920 let members: Vec<(usize, u32)> = landings
9921 .iter()
9922 .filter_map(|(li, c)| c.link.map(|id| (*li, id)))
9923 .collect();
9924 let keeps = |old: u32| {
9925 let lanes: Vec<usize> = members
9926 .iter()
9927 .filter(|m| m.1 == old)
9928 .map(|m| m.0)
9929 .collect();
9930 lanes.len() >= 2 && lanes.iter().enumerate().all(|(i, l)| !lanes[..i].contains(l))
9931 };
9932 self.snapshot();
9933 let mut fresh: Vec<(u32, u32)> = Vec::new();
9934 for (li, mut clip) in landings {
9935 clip.link = match clip.link {
9936 Some(old) if keeps(old) => match fresh.iter().find(|(o, _)| *o == old) {
9937 Some(&(_, id)) => Some(id),
9938 None => {
9939 let id = self.new_link();
9940 fresh.push((old, id));
9941 Some(id)
9942 }
9943 },
9944 _ => None,
9945 };
9946 clip.fade_in = 0;
9947 clip.fade_out = 0;
9948 clip.transition_out = 0;
9949 let clips = &mut self.lanes[li].clips;
9950 let idx = clips.partition_point(|c| c.start < clip.start);
9951 clips.insert(idx, clip);
9952 }
9953 true
9954 }
9955
9956 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
9957 /// silence, and nothing else moves. Refused only for an out-of-range index
9958 /// (which a lane that is not there always is) -- lifting the last placement
9959 /// there is leaves an *empty* timeline, which is a state the project holds
9960 /// like any other and an undo brings back.
9961 /// Swaps the placements at `a` and `b` of `lane`: `b` takes `a`'s start, the
9962 /// placements between them move by the difference in their lengths (the
9963 /// ripple within this one lane), and `a` lands where `b` was, moved by the
9964 /// same difference. The span the two cover keeps its length, so nothing
9965 /// after `b` moves. One snapshot.
9966 ///
9967 /// `false`, nothing changed, for an index that is not there, `a == b`, and a
9968 /// placement in a group: a take is moved as a take, never swapped apart.
9969 pub fn swap(&mut self, lane: Lane, a: usize, b: usize) -> bool {
9970 let (a, b) = if a < b { (a, b) } else { (b, a) };
9971 let Some(new) = (|| {
9972 let clips = self.lane(lane);
9973 if a == b || b >= clips.len() || self.in_take(lane, a) || self.in_take(lane, b) {
9974 return None;
9975 }
9976 let span = &clips[a..=b];
9977 let (sa, sb) = (span[0].start, span[span.len() - 1].start);
9978 let d = i64::from(span[span.len() - 1].frames()) - i64::from(span[0].frames());
9979 let shift = |x: u32, by: i64| (i64::from(x) + by) as u32;
9980 let last = span.len() - 1;
9981 let mut out = Vec::with_capacity(span.len());
9982 let mut first_in = span[last].clone();
9983 first_in.start = sa;
9984 out.push(first_in);
9985 for c in &span[1..last] {
9986 let mut m = c.clone();
9987 m.start = shift(m.start, d);
9988 out.push(m);
9989 }
9990 let mut back = span[0].clone();
9991 back.start = shift(sb, d);
9992 out.push(back);
9993 Some(out)
9994 })() else {
9995 return false;
9996 };
9997 self.snapshot();
9998 self.lane_mut(lane).expect("checked above").splice(a..=b, new);
9999 true
10000 }
10001
10002 /// Exchanges the positions of two unlinked clips on `lane` without rippling
10003 /// anything: each takes the other's head, and whatever lies between them stays
10004 /// where it is. When the two differ in length the shorter leaves a gap where it
10005 /// was and the longer must fit its new place -- the one that does not fit is
10006 /// refused, naming the clip it would overlap, and nothing changes.
10007 ///
10008 /// Both new footprints are checked against every clip that stays put, at once,
10009 /// so a clip moving into the slot the other one vacates is not refused for
10010 /// overlapping a slot that is about to be free (which is what sequencing three
10011 /// single moves did). One undo step.
10012 pub fn swap_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> {
10013 let label = lane.label();
10014 let clips = self.lane(lane);
10015 if a == b {
10016 return Err("the same clip twice: name two different clips".into());
10017 }
10018 let (Some(ca), Some(cb)) = (clips.get(a).cloned(), clips.get(b).cloned()) else {
10019 return Err(format!("there is no clip {} or {} on {label}", a.max(b), a.min(b)).into());
10020 };
10021 if self.in_take(lane, a) || self.in_take(lane, b) {
10022 return Err(format!(
10023 "clip {a} and clip {b} on {label} are grouped with other lanes: a take moves as a take, not swapped apart"
10024 )
10025 .into());
10026 }
10027 let mut moved_a = ca.clone();
10028 moved_a.start = cb.start;
10029 let mut moved_b = cb.clone();
10030 moved_b.start = ca.start;
10031 let placed = [(a, &moved_a), (b, &moved_b)];
10032 for (idx, moved) in placed {
10033 for (i, other) in clips.iter().enumerate() {
10034 if i == a || i == b {
10035 continue;
10036 }
10037 if moved.start < other.end() && other.start < moved.end() {
10038 return Err(format!(
10039 "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",
10040 moved.start,
10041 moved.end(),
10042 other.start,
10043 other.end()
10044 )
10045 .into());
10046 }
10047 }
10048 }
10049 if moved_a.start < moved_b.end() && moved_b.start < moved_a.end() {
10050 return Err(format!(
10051 "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",
10052 moved_b.start,
10053 moved_b.end(),
10054 moved_a.start,
10055 moved_a.end()
10056 )
10057 .into());
10058 }
10059 self.snapshot();
10060 let list = self.lane_mut(lane).expect("checked above");
10061 list[a] = moved_a;
10062 list[b] = moved_b;
10063 list.sort_by_key(|c| c.start);
10064 debug_assert!(sorted_disjoint(list));
10065 Ok(())
10066 }
10067
10068 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
10069 if idx >= self.lane(lane).len() {
10070 return false;
10071 }
10072 self.snapshot();
10073 self.lane_mut(lane).expect("checked above").remove(idx);
10074 true
10075 }
10076
10077 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
10078 /// the hole: everything after slides back by `len`. The rippling delete --
10079 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
10080 /// empty range; a delete that leaves nothing behind empties the timeline,
10081 /// which is a state like any other and one undo away.
10082 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
10083 if len == 0 {
10084 return false;
10085 }
10086 // Nothing reaches past `at`: there is nothing to cut and nothing to
10087 // slide back, and a delete that changes nothing must not cost an undo
10088 // step (see [`snapshot`](Project::snapshot)).
10089 if !self
10090 .lanes
10091 .iter()
10092 .flat_map(|l| &l.clips)
10093 .any(|c| c.end() > at)
10094 {
10095 return false;
10096 }
10097 self.snapshot();
10098 let on = all_lanes(&self.lanes);
10099 let tracks = self.caption_tracks_on(&on);
10100 let placed = self.placed_cues(&tracks);
10101 let pieces = self.split_cues_across(&on, &[at, at.saturating_add(len)], true);
10102 ripple(&mut self.lanes, &on, at, len);
10103 self.drop_unplaced(&tracks, &placed, &pieces);
10104 true
10105 }
10106
10107 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
10108 /// a right-click on empty bench space names before offering to close it.
10109 /// `None` when `frame` sits inside a placement, or past the last one: the
10110 /// open end of a lane is not a gap, since there is nothing after it to slide
10111 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
10112 /// the media [`Clip`] list they deliberately never hold.
10113 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
10114 let data = self.index(lane).map(|i| &self.lanes[i])?;
10115 match data.kind {
10116 LaneKind::Subtitle => gap(&data.subs, frame),
10117 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
10118 }
10119 }
10120
10121 /// How many bounded holes `lane` holds. The open end after the last
10122 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
10123 /// it would move nothing.
10124 pub fn gap_count(&self, lane: Lane) -> usize {
10125 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
10126 return 0;
10127 };
10128 match data.kind {
10129 LaneKind::Subtitle => gaps(&data.subs).len(),
10130 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
10131 }
10132 }
10133
10134 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
10135 /// together to keep sync -- what a right-click on empty bench space asks
10136 /// before the menu offers to close it, and what widens
10137 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
10138 /// named to the whole take the gap might be half of.
10139 ///
10140 /// A clip bordering the gap on `lane` -- the one ending where it starts,
10141 /// the one starting where it ends -- carries a link when it is one take
10142 /// with a clip on another lane. That lane joins the scope only when the
10143 /// *exact same* stretch is empty there too (same start, same length): the
10144 /// ripple then removes nothing but silence, on every lane it touches, and
10145 /// both halves stay the length they always were. A link whose partner
10146 /// lane is not empty there -- a gap of a different length, or none at all
10147 /// -- is named back to the caller rather than silently widened past
10148 /// (which would cut real media out of a lane nothing asked to touch) or
10149 /// silently left out (which is the defect this closes: a per-lane ripple
10150 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
10151 /// to refuse it after the fact, on the very half this could have carried
10152 /// along).
10153 ///
10154 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
10155 /// partner clip sits on another lane -- the unlinked case, untouched.
10156 ///
10157 /// Subtitle lanes have no media take halves to inspect. A caption can be
10158 /// hand-grouped with clips, but it is not the imported A/V take this method
10159 /// widens for, so a subtitle gap stays scoped to its own lane; the later
10160 /// scoped cut still refuses an explicit group split.
10161 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
10162 let Some(li) = self.index(lane) else {
10163 return Err("no track to work on".into());
10164 };
10165 let labels = handles(&self.lanes);
10166 let end = start + frames;
10167 let mut scope = vec![lane];
10168 for c in self.lanes[li]
10169 .clips
10170 .iter()
10171 .filter(|c| c.end() == start || c.start == end)
10172 {
10173 let Some(id) = c.link else { continue };
10174 for (j, data) in self.lanes.iter().enumerate() {
10175 if j == li {
10176 continue;
10177 }
10178 if !data.clips.iter().any(|o| o.link == Some(id)) {
10179 continue;
10180 }
10181 match gap(&data.clips, start) {
10182 Some((s, f)) if s == start && f == frames => {
10183 let other = labels[j];
10184 if !scope.contains(&other) {
10185 scope.push(other);
10186 }
10187 }
10188 _ => {
10189 // One plain line: the partner by name, and the reason in a word.
10190 return Err(format!("Can't close this gap: it would put {} out of sync.", labels[j].label()).into());
10191 }
10192 }
10193 }
10194 }
10195 Ok(scope)
10196 }
10197
10198 /// Close every bounded gap on `lane`, as one undo step, without making the
10199 /// lane's scope global. Media lanes use the same take-safety widening
10200 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
10201 /// halves ride along only when their matching lane is empty over that exact
10202 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
10203 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
10204 /// halves of an imported A/V take, so the media take-widening rule has
10205 /// nothing to add there.
10206 ///
10207 /// The walk is back-to-front. Closing a gap shifts everything after it, so
10208 /// later holes must be consumed while their measured starts are still true;
10209 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
10210 /// only before the first successful close, so an all-skipped sweep is not an
10211 /// undo step.
10212 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
10213 let Some(i) = self.index(lane) else {
10214 return Err("no track to work on".into());
10215 };
10216 if self.lanes[i].kind == LaneKind::Subtitle {
10217 return Ok(self.close_all_subtitle_gaps_on_lane(i));
10218 }
10219 let mut report = GapSweep::default();
10220 let mut snapshot = false;
10221 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
10222 match self.gap_take_scope(lane, start, frames).and_then(|scope| {
10223 let on = self.scoped(&scope)?;
10224 self.scope_holds_takes_whole(&on, start)?;
10225 Ok(on)
10226 }) {
10227 Ok(on) => {
10228 if !snapshot {
10229 self.snapshot();
10230 snapshot = true;
10231 }
10232 ripple(&mut self.lanes, &on, start, frames);
10233 report.closed += 1;
10234 }
10235 Err(e) => report.skipped.push(GapSkip {
10236 start,
10237 reason: e.to_string(),
10238 }),
10239 }
10240 }
10241 report.skipped.reverse();
10242 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10243 Ok(report)
10244 }
10245
10246 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
10247 /// take-scope widening: a caption is not one half of an A/V take. Explicit
10248 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
10249 /// so a grouped caption is refused rather than pulled away from its group.
10250 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
10251 let mut report = GapSweep::default();
10252 let mut snapshot = false;
10253 let on = [i];
10254 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
10255 match self.scope_holds_takes_whole(&on, start) {
10256 Ok(()) => {
10257 if !snapshot {
10258 self.snapshot();
10259 snapshot = true;
10260 }
10261 ripple(&mut self.lanes, &on, start, frames);
10262 report.closed += 1;
10263 }
10264 Err(e) => report.skipped.push(GapSkip {
10265 start,
10266 reason: e.to_string(),
10267 }),
10268 }
10269 }
10270 report.skipped.reverse();
10271 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10272 report
10273 }
10274
10275 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
10276 /// out of the lanes in `scope` and close each hole, as one edit: the
10277 /// jumpcut a silence scan asks for ([`crate::silence`]).
10278 ///
10279 /// A lane that is not in `scope` **does not move**, which is the whole
10280 /// point of the parameter: the silences of a podcast track come out
10281 /// without the music track under it sliding. `scope` is an arbitrary set of
10282 /// lanes and not a kind or a range, so a caller with its own idea of what
10283 /// is selected (a take, a track, everything) says it in lanes and nothing
10284 /// here has to learn about selection.
10285 ///
10286 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
10287 /// reason this exists rather than a caller's loop over
10288 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
10289 /// undo press, not forty. Cut back to front, so a region's frames still
10290 /// mean what the caller measured while the ones before it are cut.
10291 ///
10292 /// The list is sorted and overlapping entries are merged before anything is
10293 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
10294 /// other's frames. Refused, with no undo step, for an empty list, for a
10295 /// scope naming no lane that is there, and -- by name -- when the scope
10296 /// would take one half of a take with it
10297 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
10298 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
10299 let regions = tidy(regions);
10300 let on = self.scoped(scope)?;
10301 let Some(&(first, _)) = regions.first() else {
10302 return Err("nothing to cut".into());
10303 };
10304 self.scope_holds_takes_whole(&on, first)?;
10305 self.snapshot();
10306 for &(at, len) in regions.iter().rev() {
10307 let tracks = self.caption_tracks_on(&on);
10308 let placed = self.placed_cues(&tracks);
10309 let pieces = self.split_cues_across(&on, &[at, at.saturating_add(len)], true);
10310 ripple_keeping_takes(&mut self.lanes, &on, at, len, &mut self.next_link);
10311 self.drop_unplaced(&tracks, &placed, &pieces);
10312 }
10313 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10314 self.settle();
10315 Ok(())
10316 }
10317
10318 /// The storage indices of `scope`, which is what every batch below walks.
10319 /// `Err` for a scope that names nothing there rather than a silent no-op:
10320 /// an edit asked for on a lane that is not there did not happen, and the
10321 /// caller has to hear so.
10322 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
10323 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
10324 match on.is_empty() {
10325 true => Err("no track to work on".into()),
10326 false => Ok(on),
10327 }
10328 }
10329
10330 /// The law a scoped ripple lives under: **a group travels as one**, so a
10331 /// batch that moves one half of a take and not the other would leave the
10332 /// halves disagreeing about where they stand -- an offset no hand asked
10333 /// for, and the reason the take's lanes have to be scoped together.
10334 ///
10335 /// Refused by name rather than widened silently. Widening would edit a
10336 /// track the user did not scope, which is exactly the surprise scoping
10337 /// exists to end; a front-end that wants the take is free to *say* the
10338 /// take's lanes, and to name them in what it tells the user afterwards.
10339 ///
10340 /// Only from `from` on: a take sitting entirely before the first cut does
10341 /// not move, so it is not this rule's business.
10342 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
10343 let labels = handles(&self.lanes);
10344 // The halves of a group are on either of a lane's lists, and the
10345 // refusal names whichever sits outside the scope -- a clip like it
10346 // always has, and a caption now that a group may hold one.
10347 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
10348 let Some(id) = link else {
10349 return Ok(());
10350 };
10351 for (j, data) in self.lanes.iter().enumerate() {
10352 if on.contains(&j) {
10353 continue;
10354 }
10355 let clip = data.clips.iter().find(|o| o.link == Some(id));
10356 let sub = data.subs.iter().find(|s| s.link == Some(id));
10357 if let Some(half) = clip {
10358 return Err(format!(
10359 "the {what} at frame {start} is one take with the {} clip at frame {}: \
10360 moving one track of a take would pull it apart -- take the whole take, \
10361 or detach them first",
10362 labels[j].label(),
10363 half.start
10364 )
10365 .into());
10366 }
10367 if let Some(half) = sub {
10368 return Err(format!(
10369 "the {what} at frame {start} is one take with the {} caption at frame {}: \
10370 moving one track of a take would pull it apart -- take the whole take, \
10371 or detach them first",
10372 labels[j].label(),
10373 half.start
10374 )
10375 .into());
10376 }
10377 }
10378 Ok(())
10379 };
10380 for &i in on {
10381 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
10382 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
10383 }
10384 // A caption before the first cut does not move, so it is not this
10385 // rule's business -- exactly the clip test's own line.
10386 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
10387 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
10388 }
10389 }
10390 Ok(())
10391 }
10392
10393 /// Play every one of `regions` at `speed` instead of cutting it: each is
10394 /// split out of whatever covers it, re-rated, and the room it no longer
10395 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
10396 /// does not ripple, and a hole where a silence shrank is the one thing this
10397 /// must not leave. One snapshot for the lot, like
10398 /// [`cut_regions`](Project::cut_regions).
10399 ///
10400 /// The rate is **absolute**, not a multiplier on what is there: running it
10401 /// twice over the same stretch leaves it at `speed`, not at `speed`
10402 /// squared, so a second pass over an already-cut timeline changes nothing.
10403 ///
10404 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
10405 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
10406 ///
10407 /// Refused by name, with nothing changed and no undo step, when:
10408 ///
10409 /// * the scope would take one half of a take with it
10410 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
10411 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
10412 /// shrink by different amounts and the ripple would pull them apart,
10413 /// which is what cutting does not suffer and why delete mode has no such
10414 /// refusal;
10415 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
10416 /// piece could not be split out exactly;
10417 /// * two lanes' pieces would end up different lengths, which is a group
10418 /// whose halves disagree about their span (the refusal
10419 /// [`write_speed`](Project::write_speed) already makes, in its words);
10420 /// * the region would grow rather than shrink, i.e. it already plays faster
10421 /// than `speed`.
10422 pub fn speed_regions(
10423 &mut self,
10424 regions: &[(u32, u32)],
10425 speed: Speed,
10426 scope: &[Lane],
10427 ) -> crate::Result<()> {
10428 let regions = tidy(regions);
10429 let on = self.scoped(scope)?;
10430 let Some(&(first, _)) = regions.first() else {
10431 return Err("nothing to speed up".into());
10432 };
10433 self.scope_holds_takes_whole(&on, first)?;
10434 if self.lanes.iter().any(|l| {
10435 l.clips.iter().any(|c| {
10436 is_sequence_source(c.source) && regions.iter().any(|&(a, b)| c.start < b && a < c.end())
10437 })
10438 }) {
10439 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
10440 }
10441 if self.lanes.iter().any(|l| {
10442 l.clips.iter().any(|c| {
10443 !c.speed_keys.is_empty()
10444 && regions.iter().any(|&(a, b)| c.start < b && a < c.end())
10445 })
10446 }) {
10447 return Err("a clip under the region has a speed ramp: clear the ramp first".into());
10448 }
10449 let labels = handles(&self.lanes);
10450 // Before anything is touched, because this is the refusal a person can
10451 // act on: a clip that laps over the edge of a silence has to be trimmed
10452 // (or the silences cut instead), and saying so after a rollback would
10453 // be saying it about a timeline that already looks different.
10454 for &(at, len) in &regions {
10455 for &l in &on {
10456 for c in &self.lanes[l].clips {
10457 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
10458 {
10459 return Err(format!(
10460 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
10461 speeding it up would pull the lanes apart -- trim it first, or cut the \
10462 silences out instead",
10463 labels[l].label(),
10464 c.start,
10465 at + len
10466 )
10467 .into());
10468 }
10469 }
10470 }
10471 }
10472 // The rest is checked as it is built: a split's own arithmetic is what
10473 // says whether a rate can address an edge. So the snapshot is taken
10474 // first and *rolled back* on a refusal -- one undo either way, and a
10475 // refusal still costs no step (`roll_back_snapshot` takes back the one just pushed).
10476 self.snapshot();
10477 for &(at, len) in regions.iter().rev() {
10478 self.write_split(at, false, &on);
10479 self.write_split(at + len, false, &on);
10480 let mut room: Option<(Lane, u32)> = None;
10481 let mut refused = None;
10482 for &l in &on {
10483 let clips = &self.lanes[l].clips;
10484 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
10485 if (c.start, c.end()) != (at, at + len) {
10486 // *Which* edge did not come off: a rate that cannot
10487 // address the end of the silence is not a rate that
10488 // cannot address its start, and naming the wrong frame
10489 // sends the user looking in the wrong place.
10490 let edge = match c.start == at {
10491 true => at + len,
10492 false => at,
10493 };
10494 refused = Some(format!(
10495 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
10496 detach it, or put it back to 1.00x first",
10497 labels[l].label(),
10498 c.start,
10499 c.speed
10500 ));
10501 continue;
10502 }
10503 let after = speed.frames(c.len());
10504 match room {
10505 None => room = Some((labels[l], after)),
10506 Some((first, n)) if n != after => {
10507 refused = Some(format!(
10508 "at {speed} the {} half of the silence at frame {at} would cover \
10509 {after} frames and the {} half {n}: they are one take and a take \
10510 is one span -- detach them first",
10511 labels[l].label(),
10512 first.label()
10513 ));
10514 }
10515 Some(_) => {}
10516 }
10517 }
10518 }
10519 let shrunk = match (refused, room) {
10520 (Some(e), _) => {
10521 self.roll_back_snapshot();
10522 return Err(e.into());
10523 }
10524 // A gap on every lane: nothing to re-rate, and nothing to close.
10525 (None, None) => continue,
10526 (None, Some((_, after))) => after,
10527 };
10528 // The region's new length, on every scoped lane alike.
10529 let after = shrunk;
10530 let Some(delta) = len.checked_sub(shrunk) else {
10531 self.roll_back_snapshot();
10532 return Err(format!(
10533 "the silence at frame {at} already plays faster than {speed}: \
10534 at that rate it would be {shrunk} frames instead of {len}"
10535 )
10536 .into());
10537 };
10538 for &l in &on {
10539 for c in &mut self.lanes[l].clips {
10540 if c.start == at && c.end() == at + len {
10541 c.speed = speed;
10542 } else if c.start >= at + len {
10543 c.start -= delta;
10544 }
10545 }
10546 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
10547 // The captions on a scoped lane travel with the region's time:
10548 // a piece inside it plays in `after` frames instead of `len`
10549 // -- same words on less timeline, its window untouched, for
10550 // [`write_speed`]'s reason -- and everything behind the region
10551 // slides up by what the region gave back.
10552 //
10553 // The pieces inside re-time by their *boundaries*, not each
10554 // on its own: rounding one piece's start and its neighbour's
10555 // start apart can land both on the same frame (two one-frame
10556 // cues of a thirty-frame region at 2x both want frame 15), so
10557 // the mapped boundaries are walked in order and forced apart
10558 // -- each piece at least one frame, none past the region's own
10559 // new end, where the first follower lands exactly. A rounding
10560 // artifact is clamped, not refused: nothing about the words
10561 // asked for an overlap.
10562 let share = f64::from(after) / f64::from(len).max(1.);
10563 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
10564 let mut prev = at;
10565 let subs = &mut self.lanes[l].subs;
10566 for sub in subs.iter_mut() {
10567 let s = *sub;
10568 if s.start >= at + len {
10569 sub.start = s.start - delta;
10570 } else if s.start >= at && s.end() <= at + len {
10571 let mut start = map(s.start).max(prev);
10572 let end = map(s.end()).max(start + 1).min(at + after);
10573 start = start.min(end - 1);
10574 sub.start = start;
10575 sub.frames = end - start;
10576 prev = end;
10577 }
10578 }
10579 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
10580 }
10581 }
10582 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10583 self.settle();
10584 Ok(())
10585 }
10586
10587 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
10588 /// -- the whole-group delete a single-lane front-end means. `false` for a
10589 /// bad index. Changes the mapping: the caller must reseek.
10590 pub fn delete(&mut self, idx: usize) -> bool {
10591 self.delete_in(Lane::V1, idx)
10592 }
10593
10594 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
10595 /// in no group (or a group of one, which is the same thing to a delete) is
10596 /// what it always was: its own span cut out of *every* lane, so the
10597 /// timeline closes up under it. A clip in a group takes the group with it,
10598 /// each member by its **own** span and on its **own** lane -- the members
10599 /// keep their offsets, so their spans may disagree, and the lanes may end
10600 /// up out of step with each other, which is inherent to a hand-built group
10601 /// and one undo away. Every member -- clips and captions alike -- goes by
10602 /// the same law: its own span out of its own lane, hole closed; a caption
10603 /// in no group keeps the lift that leaves a gap, which is its own door's
10604 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
10605 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
10606 /// index, and for a lane that is not there. Changes the mapping: the
10607 /// caller must reseek.
10608 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
10609 let Some(members) = self.group_of(lane, idx) else {
10610 return false;
10611 };
10612 if !members.alone() {
10613 return self.delete_members(&members);
10614 }
10615 let Some(clip) = self.lane(lane).get(idx).cloned() else {
10616 return false;
10617 };
10618 self.ripple_delete(clip.start, clip.frames())
10619 }
10620
10621 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
10622 /// caption in no group lifts, exactly as its own key always made it
10623 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
10624 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
10625 /// span out of its own lane, hole closed, captions and clips alike.
10626 /// `false` for a bad index.
10627 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
10628 let Some(members) = self.group_of(lane, idx) else {
10629 return false;
10630 };
10631 if !members.alone() {
10632 return self.delete_members(&members);
10633 }
10634 self.lift_sub(lane, idx)
10635 }
10636
10637 /// The one whole-group delete both doors land in: every member's own span
10638 /// cut out of its own lane and the hole closed there -- clips and
10639 /// captions by the same law -- and nothing else on another lane moves,
10640 /// which is what keeps one member's ripple from dragging another
10641 /// member's lane out from under it. One snapshot, one undo step.
10642 fn delete_members(&mut self, members: &Members) -> bool {
10643 self.snapshot();
10644 for &(l, i) in &members.clips {
10645 let c = self.lanes[l].clips[i].clone();
10646 ripple(&mut self.lanes, &[l], c.start, c.frames());
10647 }
10648 // The captions go by the same law their clip siblings do -- the span
10649 // out of its own lane, the hole closed -- and not by the lift a
10650 // *lone* caption's delete is: deleted with its group, the words after
10651 // it slide up with everything else, or the lane the group emptied is
10652 // the one lane the delete left a hole in. `ripple` is the one
10653 // mechanism (it clears the span and shifts the rest, clips and
10654 // captions alike); a sub lane holds no clips, so its other list is
10655 // untouched.
10656 for &(l, i) in &members.subs {
10657 let s = self.lanes[l].subs[i];
10658 ripple(&mut self.lanes, &[l], s.start, s.frames);
10659 }
10660 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10661 true
10662 }
10663
10664 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
10665 #[cfg(test)]
10666 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
10667 self.lane(lane)
10668 }
10669
10670 /// The mark an action takes before it runs, for [`Project::name_step`]: the count
10671 /// of every step pushed so far. Settles a no-op first, so the mark is exact.
10672 pub(crate) fn step_mark(&mut self) -> u64 {
10673 self.settle();
10674 self.pushes
10675 }
10676
10677 /// Names the newest undo step, but only when the action that took `mark` pushed one:
10678 /// an action that changed nothing, or only undid, names nothing. The name is what
10679 /// Undo and Redo say about this step ([`Project::undo_label`]) and it leaves with
10680 /// the step, so a settled no-op or a capped-out step takes its name with it.
10681 pub(crate) fn name_step(&mut self, mark: u64, label: &str) {
10682 self.settle();
10683 if self.pushes > mark
10684 && let Some(top) = self.history.last_mut()
10685 {
10686 top.label = Some(label.to_string());
10687 }
10688 }
10689
10690 /// The name of the step [`Project::undo`] would take back; `None` when that step
10691 /// was never named, or when there is nothing to undo.
10692 pub fn undo_label(&self) -> Option<&str> {
10693 let top = match self.settling_no_op() {
10694 // The no-op is the newest step; settling it leaves the one under it on top.
10695 Some(_) => self.history.len().checked_sub(2).and_then(|i| self.history.get(i)),
10696 None => self.history.last(),
10697 };
10698 top.and_then(|s| s.label.as_deref())
10699 }
10700
10701 /// The name of the step [`Project::redo`] would walk forward to; `None` when that
10702 /// step was never named, or when there is nothing to redo.
10703 pub fn redo_label(&self) -> Option<&str> {
10704 let stack = match self.settling_no_op() {
10705 Some(pending) => &pending.redo,
10706 None => &self.redo,
10707 };
10708 stack.last().and_then(|s| s.label.as_deref())
10709 }
10710
10711 /// How many undo steps are stacked: what the sweep asks so "one op, one
10712 /// snapshot" is a count and not a guess.
10713 /// The name of every step [`Project::undo`] can take back, oldest first; `None` for a step
10714 /// nobody named. The last one is the step the project is on.
10715 pub fn undo_labels(&self) -> Vec<Option<String>> {
10716 let n = self.history_len();
10717 self.history.iter().take(n).map(|s| s.label.clone()).collect()
10718 }
10719
10720 /// The name of every step [`Project::redo`] can walk forward to, the next one last (the
10721 /// mirror of [`undo_labels`](Project::undo_labels)).
10722 pub fn redo_labels(&self) -> Vec<Option<String>> {
10723 let stack = match self.settling_no_op() {
10724 Some(pending) => &pending.redo,
10725 None => &self.redo,
10726 };
10727 stack.iter().map(|s| s.label.clone()).collect()
10728 }
10729
10730 pub(crate) fn history_len(&self) -> usize {
10731 match self.settling_no_op() {
10732 // The no-op's step goes, and the one it evicted comes back.
10733 Some(pending) => self.history.len() - 1 + usize::from(pending.evicted.is_some()),
10734 None => self.history.len(),
10735 }
10736 }
10737
10738 /// Every snapshot pushed so far, including those the cap has since dropped.
10739 pub(crate) fn history_pushes(&self) -> u64 {
10740 match self.settling_no_op() {
10741 Some(_) => self.pushes.saturating_sub(1),
10742 None => self.pushes,
10743 }
10744 }
10745
10746 /// Which state the project is in: a fresh id after every edit, and the id the
10747 /// state had before it after an undo, so equal revisions mean the same
10748 /// timeline. Never reused, so a revision names one state for good.
10749 pub fn revision(&self) -> u64 {
10750 match (self.settling_no_op(), self.history.last()) {
10751 (Some(_), Some(top)) => top.revision,
10752 _ => self.revision,
10753 }
10754 }
10755
10756 /// Drops the redo stack without a step: for a caller whose own trial edits
10757 /// were rolled back, which left their undone states here to redo.
10758 pub(crate) fn clear_redo(&mut self) {
10759 self.settle();
10760 self.redo.clear();
10761 }
10762
10763 /// Moves the redo stack out, leaving it empty, for a caller whose trial edits
10764 /// are about to run and may be rolled back. [`Project::restore_redo`] puts it
10765 /// back exactly, replacing whatever the trial's own undo steps left on it.
10766 pub(crate) fn take_redo(&mut self) -> RedoCheckpoint {
10767 self.settle();
10768 RedoCheckpoint(std::mem::take(&mut self.redo))
10769 }
10770
10771 /// Puts back a stack [`Project::take_redo`] took out.
10772 pub(crate) fn restore_redo(&mut self, cp: RedoCheckpoint) {
10773 self.settle();
10774 self.redo = cp.0;
10775 }
10776
10777 /// Lets the undo history run past [`HISTORY_CAP`] while a trial batch is open,
10778 /// so the trial's pushes evict nothing; closing it (`false`) trims the history
10779 /// back to the cap, dropping the oldest steps as an edit would.
10780 pub(crate) fn hold_history(&mut self, hold: bool) {
10781 self.settle();
10782 self.hold_cap = hold;
10783 if !hold {
10784 let over = self.history.len().saturating_sub(HISTORY_CAP);
10785 self.history.drain(..over);
10786 }
10787 }
10788
10789 /// How many redo steps are stacked: what the sweep asks to check `undo`
10790 /// left a branch behind, and that a fresh edit clears it.
10791 pub(crate) fn redo_len(&self) -> usize {
10792 match self.settling_no_op() {
10793 Some(pending) => pending.redo.len(),
10794 None => self.redo.len(),
10795 }
10796 }
10797
10798 /// The project's own settings as they stand ([`ProjectSettings`]) -- what an
10799 /// undo entry holds beside the lanes, and what the session reads back after
10800 /// one is restored ([`crate::PlaybackSession::undo`]).
10801 pub(crate) fn settings_now(&self) -> ProjectSettings {
10802 self.settings.clone()
10803 }
10804
10805 /// One undo step for a change to the project's own settings: `from` is the
10806 /// state the change is from and `now` the one it leaves behind. The entry
10807 /// pushed holds `from`, while the copy kept here is `now` -- so the next
10808 /// lane edit's own entry carries the canvas and the rate really in force
10809 /// rather than the ones before the pick. The lanes the entry holds are the
10810 /// ones in place at the call: a settings door leaves them alone and may
10811 /// take this step after its change, and one that moves them
10812 /// ([`Project::retime`] on a rate change) takes it before, with `now` equal
10813 /// to `from`, mirroring the new state afterwards
10814 /// ([`Project::mirror_settings`]).
10815 pub(crate) fn push_settings_step(&mut self, from: ProjectSettings, now: ProjectSettings) {
10816 self.settle();
10817 self.settings = from;
10818 self.snapshot();
10819 self.settings = now;
10820 }
10821
10822 /// Keeps `now` as this project's copy of its own settings, without a step:
10823 /// the second half of a settings door that had to take its step before the
10824 /// change.
10825 pub(crate) fn mirror_settings(&mut self, now: ProjectSettings) {
10826 self.settle();
10827 self.settings = now;
10828 }
10829
10830 /// Every part of the project that an edit can change, as comparable
10831 /// values: what the sweep's undo round-trip asks "byte identical?" of.
10832 #[cfg(test)]
10833 pub(crate) fn parts(&self) -> SweepParts {
10834 SweepParts(
10835 self.sources.len(),
10836 self.lanes
10837 .iter()
10838 .map(|l| (l.kind, l.clips.clone()))
10839 .collect(),
10840 self.lanes.iter().map(|l| l.subs.clone()).collect(),
10841 self.subtitles.clone(),
10842 self.settings.clone(),
10843 )
10844 }
10845
10846 /// Restore everything from before the last successful edit -- the lanes,
10847 /// the subtitle palette, the project's own settings and the sources (a
10848 /// relink is undone by the old path coming back). `false` when there
10849 /// is nothing left to undo. Pushes what was just left onto the redo stack,
10850 /// so [`Project::redo`] can walk forward again.
10851 pub fn undo(&mut self) -> bool {
10852 self.settle();
10853 match self.history.pop() {
10854 Some(prev) => {
10855 self.batch_snapped = false;
10856 self.pending = None;
10857 let displaced = self.swap_state(prev);
10858 self.redo.push(displaced);
10859 true
10860 }
10861 None => false,
10862 }
10863 }
10864
10865 /// Restore everything from before the last [`Project::undo`] -- the
10866 /// mirror of `undo`, walking the redo stack it fills. `false` when there
10867 /// is nothing left to redo, which is also true after any fresh edit: a
10868 /// new [`Project::snapshot`] clears the branch `undo` left behind.
10869 pub fn redo(&mut self) -> bool {
10870 self.settle();
10871 match self.redo.pop() {
10872 Some(next) => {
10873 self.batch_snapped = false;
10874 self.pending = None;
10875 let displaced = self.swap_state(next);
10876 self.history.push(displaced);
10877 true
10878 }
10879 None => false,
10880 }
10881 }
10882
10883 /// Puts `to` back as the project's state and returns the state it replaced,
10884 /// as the snapshot an undo or redo of that replacement restores.
10885 fn swap_state(&mut self, to: Snapshot) -> Snapshot {
10886 let sources = restored_sources(to.sources, &self.sources);
10887 let displaced = Snapshot {
10888 revision: std::mem::replace(&mut self.revision, to.revision),
10889 label: to.label.clone(),
10890 lanes: std::mem::replace(&mut self.lanes, to.lanes),
10891 subtitles: self.subtitles.clone(),
10892 cue_edits: self.cue_edits.clone(),
10893 cue_adds: self.cue_adds.clone(),
10894 titles: self.titles.clone(),
10895 chapters: self.chapters.clone(),
10896 markers: self.markers.clone(),
10897 settings: self.settings.clone(),
10898 sources: std::mem::replace(&mut self.sources, sources),
10899 bins: std::mem::replace(&mut self.bins, to.bins),
10900 seq: std::mem::replace(&mut self.seq, to.seq),
10901 };
10902 self.flat.clear();
10903 self.subtitles = to.subtitles;
10904 self.cue_edits = to.cue_edits;
10905 self.cue_adds = to.cue_adds;
10906 self.titles = to.titles;
10907 self.chapters = to.chapters;
10908 self.markers = to.markers;
10909 self.settings = to.settings;
10910 displaced
10911 }
10912
10913 /// Half-open `(source, start, end)` segments in *source* seconds, from
10914 /// `timeline_frame` to the end of the timeline -- the play list for the
10915 /// audio worker, read off **`A1`**. A `None` source is a gap: the
10916 /// worker synthesises that many seconds of silence, which is what keeps the
10917 /// audio master clock counting across a hole instead of stalling on it.
10918 /// The first entry is partial when the position is mid-clip. Empty when the
10919 /// position is past the end or `fps` is not usable.
10920 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
10921 self.lane_segments_from(Lane::A1, timeline_frame, fps)
10922 }
10923
10924 /// [`segments_from`](Project::segments_from) for a named lane.
10925 pub fn lane_segments_from(
10926 &self,
10927 lane: Lane,
10928 timeline_frame: u32,
10929 fps: f64,
10930 ) -> Vec<(Option<usize>, f64, f64)> {
10931 if !(fps.is_finite() && fps > 0.0) {
10932 return Vec::new();
10933 }
10934 self.spans_from(lane, timeline_frame)
10935 .iter()
10936 .map(|span| match span.from {
10937 // A clip's window is in *source* seconds: where in the file it
10938 // reads from, which a delete before it never shifts. How many
10939 // source frames that is, is the span's own arithmetic -- at a
10940 // speed it is not the timeline length ([`Span::source_len`]).
10941 Some(_) => {
10942 let (source, lo, hi) = span.source_window().expect("a clip's span");
10943 (Some(source), f64::from(lo) / fps, f64::from(hi) / fps)
10944 }
10945 // A gap has no file, so all it can say is how long it is.
10946 None => (None, 0.0, f64::from(span.len) / fps),
10947 })
10948 .collect()
10949 }
10950
10951 /// One play list per audio lane that *holds* something, in display order --
10952 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
10953 /// what an export asks how many lanes it would have to mix.
10954 ///
10955 /// Never empty: a timeline whose audio lanes are all empty (or which has no
10956 /// audio lane at all) still yields one all-gap list, so it plays silence
10957 /// against a master clock exactly as it did before there were lanes to
10958 /// count. Lanes with nothing on them are left out rather than mixed in as
10959 /// silence: they would cost a decode thread each and add zero.
10960 pub fn audio_segments_from(
10961 &self,
10962 timeline_frame: u32,
10963 fps: f64,
10964 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
10965 self.audio_lanes()
10966 .into_iter()
10967 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
10968 .collect()
10969 }
10970
10971 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
10972 /// builds a play list for, in the same order. Public because everything
10973 /// asked per audio lane -- which clip a segment's equalizer belongs to,
10974 /// which lane an mp4 export would copy -- has to read the very list the
10975 /// sound comes off, or the two answers drift apart (which is exactly how an
10976 /// `A2`-only project once exported silently, ledger).
10977 pub fn audio_lanes(&self) -> Vec<Lane> {
10978 let lanes: Vec<Lane> = self
10979 .lanes()
10980 .into_iter()
10981 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
10982 .collect();
10983 match lanes.is_empty() {
10984 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
10985 // no sound still plays silence against the master clock.
10986 true => vec![Lane::A1],
10987 false => lanes,
10988 }
10989 }
10990
10991 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
10992 /// segments plays at, and how long the timeline gives it: the same lanes in
10993 /// the same order, one entry per segment, `None` for a segment at real time
10994 /// -- which is every segment of a project nobody has speeded, and the path
10995 /// the audio worker leaves bit-identical.
10996 ///
10997 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
10998 /// the segment tuple is what every opener and a dozen tests speak, and a
10999 /// rate is not part of *which samples* a segment names.
11000 ///
11001 /// The seconds are what makes a resample exact: a segment's own window
11002 /// resolves to whole source frames, and dividing that by the rate would
11003 /// leave each clip a fraction of a frame short or long -- a drift that grows
11004 /// clip by clip. Told how much timeline it owes, the worker pads or trims
11005 /// the last few samples of each segment instead, so the sound stays locked
11006 /// to the picture however many speeded cuts it walks through.
11007 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
11008 self.audio_lanes()
11009 .into_iter()
11010 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
11011 .collect()
11012 }
11013
11014 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
11015 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
11016 /// same walk, same `fps` refusal.
11017 pub fn lane_speeds_from(
11018 &self,
11019 lane: Lane,
11020 timeline_frame: u32,
11021 fps: f64,
11022 ) -> Vec<Option<Stretch>> {
11023 if !(fps.is_finite() && fps > 0.0) {
11024 return Vec::new();
11025 }
11026 self.spans_from(lane, timeline_frame)
11027 .iter()
11028 .map(|span| {
11029 // A ramp's `step` is its mean rate over the span (the source it reads
11030 // over the timeline it fills), the fallback; the stretch follows the
11031 // ramp itself through `ramp`.
11032 let ramped = span.ramp.is_some();
11033 let step = match span.ramp {
11034 Some(_) => f64::from(span.source_len()) / f64::from(span.len),
11035 None => span.speed.as_f64(),
11036 };
11037 (ramped || !span.speed.is_normal() || span.reverse || span.pitch != 0).then(|| Stretch {
11038 step,
11039 timeline_secs: f64::from(span.len) / fps,
11040 reverse: span.reverse,
11041 ramp: span.ramp,
11042 fps,
11043 pitch: span.pitch,
11044 })
11045 })
11046 .collect()
11047 }
11048
11049 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
11050 /// segments plays through: the same lanes in the same order, one entry per
11051 /// segment, `None` where the segment is a gap or its clip plays flat.
11052 ///
11053 /// A parallel list rather than a fourth element of the segment tuple: that
11054 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
11055 /// and an effect is not part of *which samples* a segment names. A short
11056 /// list therefore means "flat from here on" rather than a length mismatch --
11057 /// see [`crate::AudioSession::open_mixed_streams_eq`].
11058 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
11059 self.audio_lanes()
11060 .into_iter()
11061 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
11062 .collect()
11063 }
11064
11065 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
11066 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
11067 /// same walk, same `fps` refusal, so the two lists cannot come out different
11068 /// lengths.
11069 pub fn lane_eqs_from(
11070 &self,
11071 lane: Lane,
11072 timeline_frame: u32,
11073 fps: f64,
11074 ) -> Vec<Option<EqParams>> {
11075 if !(fps.is_finite() && fps > 0.0) {
11076 return Vec::new();
11077 }
11078 self.spans_from(lane, timeline_frame)
11079 .iter()
11080 // A span off a clip covers that clip's frames and no others, so its
11081 // own start names the clip -- the index a [`Span`] does not carry.
11082 .map(|span| {
11083 self.map(lane, span.start)
11084 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
11085 })
11086 .collect()
11087 }
11088
11089 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
11090 /// segments plays through: the same lanes in the same order, one entry per
11091 /// segment, `None` where the segment is a gap or its clip has neither a
11092 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
11093 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
11094 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
11095 self.audio_lanes()
11096 .into_iter()
11097 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
11098 .collect()
11099 }
11100
11101 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
11102 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
11103 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
11104 if !(fps.is_finite() && fps > 0.0) {
11105 return Vec::new();
11106 }
11107 let lane_pan = self.lane_pan(lane);
11108 self.spans_from(lane, timeline_frame)
11109 .iter()
11110 .map(|span| {
11111 let (idx, _) = self.map(lane, span.start)?;
11112 let clip = self.lane(lane).get(idx)?;
11113 (clip.fade_in > 0
11114 || clip.fade_out > 0
11115 || clip.gain_db != 0.0
11116 || clip.pan != 0
11117 || lane_pan != 0.0
11118 || !clip.gain_keys.is_empty())
11119 .then(|| Fade {
11120 // `span.len` is the clip's own remaining frames from
11121 // `span.start` on -- shorter than `clip.frames()` only
11122 // when this is the first span of a seek mid-clip.
11123 elapsed: clip.frames().saturating_sub(span.len),
11124 fade_in: clip.fade_in,
11125 fade_out: clip.fade_out,
11126 total: clip.frames(),
11127 gain: db_to_linear(clip.gain_db),
11128 pan: pan_gains(clip.pan_value(), lane_pan),
11129 curve: clip_curve(clip),
11130 })
11131 })
11132 .collect()
11133 }
11134
11135 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
11136 /// it has decided it will succeed -- a refusal must not cost an undo step.
11137 /// Clears the redo stack: a fresh edit branches off from here, so whatever
11138 /// `undo` had left to redo is no longer where this edit leads back to.
11139 fn snapshot(&mut self) {
11140 self.flat.clear();
11141 if self.batching && self.batch_snapped {
11142 // The open batch already holds its one step, taken before its first edit.
11143 self.redo.clear();
11144 self.revision = next_revision();
11145 return;
11146 }
11147 // A no-op left on top is dropped first, so it never stacks as a step of its own,
11148 // evicts one, or clears a redo branch it did not displace.
11149 self.settle();
11150 let evicted = match !self.hold_cap && self.history.len() == HISTORY_CAP {
11151 true => Some(self.history.remove(0)),
11152 false => None,
11153 };
11154 let redo = std::mem::take(&mut self.redo);
11155 self.pending = Some(PendingStep { redo, evicted });
11156 self.pushes += 1;
11157 self.history.push(Snapshot {
11158 revision: self.revision,
11159 label: None,
11160 lanes: self.lanes.clone(),
11161 subtitles: self.subtitles.clone(),
11162 cue_edits: self.cue_edits.clone(),
11163 cue_adds: self.cue_adds.clone(),
11164 titles: self.titles.clone(),
11165 chapters: self.chapters.clone(),
11166 markers: self.markers.clone(),
11167 settings: self.settings.clone(),
11168 sources: self.sources.clone(),
11169 bins: self.bins.clone(),
11170 seq: self.seq.clone(),
11171 });
11172 self.batch_snapped = self.batching;
11173 self.revision = next_revision();
11174 }
11175
11176 /// Whether the project is exactly the state the newest undo step restores.
11177 /// Every field a step holds is compared, the sources in full (their own `==`
11178 /// ignores the library's star and bin, which an edit may change).
11179 fn matches_newest_step(&self) -> bool {
11180 let Some(top) = self.history.last() else {
11181 return false;
11182 };
11183 let same_sources = top.sources.len() == self.sources.len()
11184 && top.sources.iter().zip(&self.sources).all(|(a, b)| {
11185 a == b && a.fav == b.fav && a.bin == b.bin
11186 });
11187 top.lanes == self.lanes
11188 && top.subtitles == self.subtitles
11189 && top.cue_edits == self.cue_edits
11190 && top.cue_adds == self.cue_adds
11191 && top.titles == self.titles
11192 && top.chapters == self.chapters
11193 && top.markers == self.markers
11194 && top.settings == self.settings
11195 && same_sources
11196 && top.bins == self.bins
11197 && top.seq == self.seq
11198 }
11199
11200 /// Takes back the step this method's own [`Project::snapshot`] pushed, when
11201 /// the method refuses after it has already changed things. Unlike
11202 /// [`Project::undo`] it does not settle first: a refused edit that changed
11203 /// nothing must still take back its own step, not an earlier real one. The
11204 /// redo branch the snapshot displaced comes back exactly as it was.
11205 fn roll_back_snapshot(&mut self) {
11206 let Some(pending) = self.pending.take() else {
11207 self.undo();
11208 return;
11209 };
11210 let Some(prev) = self.history.pop() else {
11211 return;
11212 };
11213 self.swap_state(prev);
11214 self.redo = pending.redo;
11215 if let Some(old) = pending.evicted {
11216 self.history.insert(0, old);
11217 }
11218 self.pushes = self.pushes.saturating_sub(1);
11219 self.batch_snapped = false;
11220 }
11221
11222 /// The pending step, when it is a no-op that [`Project::settle`] would drop.
11223 /// Every reader looks through it, so a no-op never shows as a step, a new
11224 /// revision or a cleared redo branch, whether or not anything has settled it yet.
11225 fn settling_no_op(&self) -> Option<&PendingStep> {
11226 self.pending.as_ref().filter(|_| self.matches_newest_step())
11227 }
11228
11229 /// Takes back the step the last edit pushed when that edit left the project
11230 /// as it was: no undo step, the revision it started from, and the redo branch
11231 /// it displaced put back. Nothing is dropped unless the step is the newest
11232 /// one this project pushed and the state matches it exactly. Outside a batch
11233 /// the step is then settled, so a later edit cannot pick it up. Every snapshot,
11234 /// undo and redo settles first, so a no-op is gone before anything builds on it.
11235 pub(crate) fn settle(&mut self) {
11236 if self.pending.is_some() && self.matches_newest_step() {
11237 let (Some(prev), Some(pending)) = (self.history.pop(), self.pending.take()) else {
11238 return;
11239 };
11240 self.revision = prev.revision;
11241 self.redo = pending.redo;
11242 if let Some(old) = pending.evicted {
11243 self.history.insert(0, old);
11244 }
11245 self.pushes = self.pushes.saturating_sub(1);
11246 self.batch_snapped = false;
11247 self.flat.clear();
11248 }
11249 if !self.batching {
11250 self.pending = None;
11251 }
11252 }
11253
11254 /// Starts a batch: until [`Project::end_batch`], every edit shares one undo
11255 /// step, the snapshot taken before the batch's first edit. Idempotent while open.
11256 pub fn begin_batch(&mut self) {
11257 if !self.batching {
11258 self.batching = true;
11259 self.batch_snapped = false;
11260 }
11261 }
11262
11263 /// Ends the batch [`Project::begin_batch`] opened. The next edit takes its own step.
11264 pub fn end_batch(&mut self) {
11265 if self.batching {
11266 self.settle();
11267 }
11268 self.batching = false;
11269 self.batch_snapped = false;
11270 self.pending = None;
11271 }
11272
11273 fn new_link(&mut self) -> u32 {
11274 let id = self.next_link;
11275 self.next_link = self.next_link.saturating_add(1);
11276 id
11277 }
11278}
11279
11280/// The handle of every lane, in storage order -- the one definition of what
11281/// [`Lane::ord`] counts.
11282fn handles(lanes: &[LaneData]) -> Vec<Lane> {
11283 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
11284 lanes
11285 .iter()
11286 .map(|l| match l.kind {
11287 LaneKind::Video => {
11288 video += 1;
11289 Lane::new(LaneKind::Video, video - 1)
11290 }
11291 LaneKind::Audio => {
11292 audio += 1;
11293 Lane::new(LaneKind::Audio, audio - 1)
11294 }
11295 LaneKind::Subtitle => {
11296 subtitle += 1;
11297 Lane::new(LaneKind::Subtitle, subtitle - 1)
11298 }
11299 })
11300 .collect()
11301}
11302
11303/// The one law a caption re-time scales by: frame `f` moves about the held
11304/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
11305/// commits it, [`Project::speeded_playhead`] previews it -- both build their
11306/// [`TimelineMap`] piece from this single answer so the two cannot drift
11307/// apart by a frame the way they once did.
11308fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
11309 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
11310 .round()
11311 .clamp(0., f64::from(u32::MAX)) as u32
11312}
11313
11314/// Where in the source a clip's `clip_frame`th timeline frame plays, fractional:
11315/// its in-point plus the speed's integral up to that frame. The one place the two
11316/// frame spaces meet, so a speed cannot be applied twice or forgotten in one of
11317/// them. At a constant speed the position is whole (the floored
11318/// [`Speed::source_at`]), so `floor` of it is that path's frame exactly; with a
11319/// ramp ([`Clip::speed_keys`]) it is the continuous integral and the frame is its
11320/// floor.
11321pub fn source_pos(clip: &Clip, clip_frame: u32) -> f64 {
11322 let offset = if clip.speed_keys.is_empty() {
11323 f64::from(clip.speed.source_at(clip_frame))
11324 } else {
11325 ramp_source_at(&clip.speed_keys, f64::from(clip_frame))
11326 };
11327 match clip.reversed {
11328 // Walked from the window's last frame down. The whole frames travelled are
11329 // what is mirrored (`out - 1 - floor`), so a ramp's fraction cannot lift the
11330 // floor of the frame shown, and the first frame is the last one of the window.
11331 true => f64::from(clip.out_frame - 1) - offset.floor() + offset.fract(),
11332 false => f64::from(clip.in_frame) + offset,
11333 }
11334}
11335
11336/// Where the source-keyed things of a clip (its placement and volume keys) are read
11337/// at `timeline_frame`: the playing source position, fractional. At a constant
11338/// speed this is its own expression, so an unramped, unreversed clip is bit-identical
11339/// to what it was before there were ramps.
11340/// The source position a key is sampled at: [`key_pos`] rounded to a whole frame,
11341/// the frame [`Project::key_source_frame`] writes a key at. A key is read back
11342/// exactly where it was written; sampling the fraction would blend it with its
11343/// neighbour (a typed 40% on a 1.5x clip reads 41%).
11344pub(crate) fn key_sample_pos(clip: &Clip, timeline_frame: u32) -> f64 {
11345 key_pos(clip, timeline_frame).round()
11346}
11347
11348fn key_pos(clip: &Clip, timeline_frame: u32) -> f64 {
11349 let offset = timeline_frame.saturating_sub(clip.start);
11350 match (clip.speed_keys.is_empty(), clip.reversed) {
11351 (true, false) => f64::from(clip.in_frame) + f64::from(offset) * clip.speed.as_f64(),
11352 (true, true) => f64::from(clip.out_frame - 1) - f64::from(offset) * clip.speed.as_f64(),
11353 (false, false) => source_pos(clip, offset),
11354 // Continuous, unlike [`source_pos`]'s floor-exact walk: a key is interpolated,
11355 // and a saw-toothed position would make it jump.
11356 (false, true) => {
11357 f64::from(clip.out_frame - 1) - ramp_source_at(&clip.speed_keys, f64::from(offset))
11358 }
11359 }
11360}
11361
11362/// Which source frame a clip plays at `timeline_frame` -- [`source_pos`] floored.
11363/// Clamped inside the clip's own range: rounding at a slow rate can put the last
11364/// timeline frame of a clip a frame past its out-point, and a source frame outside
11365/// the range is one the next clip owns.
11366fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
11367 (source_pos(c, timeline_frame - c.start).floor() as u32).clamp(c.in_frame, c.out_frame - 1)
11368}
11369
11370/// The span a clip contributes from `timeline_frame` on: its speed field, and its ramp
11371/// when it has one, based at the span's own start.
11372pub(crate) fn span_speed_of(c: &Clip, timeline_frame: u32) -> (Speed, Option<SpeedRamp>) {
11373 if c.speed_keys.is_empty() {
11374 (c.speed, None)
11375 } else {
11376 let base = timeline_frame - c.start;
11377 (Speed::NORMAL, Some(SpeedRamp::new(&c.speed_keys, base)))
11378 }
11379}
11380
11381/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
11382/// finder generic makes the subtitle path use the same bounded-hole rules as
11383/// media lanes without teaching the media-specific take logic about captions.
11384trait GapPlacement {
11385 fn start_frame(&self) -> u32;
11386 fn end_frame(&self) -> u32;
11387}
11388
11389impl GapPlacement for Clip {
11390 fn start_frame(&self) -> u32 {
11391 self.start
11392 }
11393
11394 fn end_frame(&self) -> u32 {
11395 self.end()
11396 }
11397}
11398
11399impl GapPlacement for SubClip {
11400 fn start_frame(&self) -> u32 {
11401 self.start
11402 }
11403
11404 fn end_frame(&self) -> u32 {
11405 self.end()
11406 }
11407}
11408
11409/// Index of the placement covering `frame`, or `None` for a gap or past the
11410/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
11411fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
11412 let idx = items
11413 .partition_point(|item| item.start_frame() <= frame)
11414 .checked_sub(1)?;
11415 (frame < items[idx].end_frame()).then_some(idx)
11416}
11417
11418/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
11419/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
11420/// invariant like [`at`]: the first placement whose start is past `frame` is
11421/// the far wall, and the last one that ends at or before `frame` (or the
11422/// timeline's own head, `0`, when there is none) is the near one.
11423fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
11424 if at(items, frame).is_some() {
11425 return None;
11426 }
11427 let idx = items.partition_point(|item| item.start_frame() <= frame);
11428 let next = items.get(idx)?;
11429 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
11430 Some((start, next.start_frame() - start))
11431}
11432
11433/// Every bounded hole in `items`, left to right. The tail after the last
11434/// placement is deliberately absent: there is no later placement for a ripple
11435/// to bring back.
11436fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
11437 let mut out = Vec::new();
11438 let mut next = 0;
11439 for item in items {
11440 if item.start_frame() > next {
11441 out.push((next, item.start_frame() - next));
11442 }
11443 next = item.end_frame();
11444 }
11445 out
11446}
11447
11448/// The clip's gain envelope in clip-relative timeline frames, or `None` when it
11449/// has no points. Source frame `s` is reached `(s - in_frame) / speed` timeline
11450/// frames in, which is exact because a speed is one linear rate.
11451fn clip_curve(clip: &Clip) -> Option<std::sync::Arc<[(f64, f32, KeyEase)]>> {
11452 if clip.gain_keys.is_empty() {
11453 return None;
11454 }
11455 let step = clip.speed.as_f64();
11456 let base = f64::from(clip.in_frame);
11457 let mut curve: Vec<(f64, f32, KeyEase)> = match clip.reversed {
11458 // The far end of the window is the clip's head, so the points are walked from
11459 // there and come out in time order the other way about.
11460 true => {
11461 let top = f64::from(clip.out_frame - 1);
11462 clip.gain_keys
11463 .iter()
11464 .enumerate()
11465 .rev()
11466 .map(|(n, k)| {
11467 // The segment that arrived at a point is the one that now leaves it.
11468 let ease = if n > 0 { clip.gain_keys[n - 1].ease } else { k.ease };
11469 ((top - f64::from(k.at)) / step, k.db, ease)
11470 })
11471 .collect()
11472 }
11473 false => clip
11474 .gain_keys
11475 .iter()
11476 .map(|k| ((f64::from(k.at) - base) / step, k.db, k.ease))
11477 .collect(),
11478 };
11479 curve.shrink_to_fit();
11480 Some(curve.into())
11481}
11482
11483/// `keys` walked from the far end of a window whose last frame is `top`, in the
11484/// order a reversed clip plays them: each point at source frame `p` moves to
11485/// `top - p`, and each segment keeps the easing it had, now leaving the point at
11486/// its other end. A point the mirror would put before frame 0 is dropped -- it lay
11487/// far outside the window, where nothing reads it.
11488fn mirrored<K: Clone>(
11489 keys: &[K],
11490 top: i64,
11491 at: impl Fn(&K) -> u32,
11492 ease: impl Fn(&K) -> KeyEase,
11493 with: impl Fn(&K, u32, KeyEase) -> K,
11494) -> Vec<K> {
11495 keys.iter()
11496 .enumerate()
11497 .rev()
11498 .filter_map(|(n, k)| {
11499 // The segment that arrived at this point is the one that now leaves it.
11500 let e = if n > 0 { ease(&keys[n - 1]) } else { ease(k) };
11501 Some(with(k, u32::try_from(top - i64::from(at(k))).ok()?, e))
11502 })
11503 .collect()
11504}
11505
11506/// Re-keys `c`'s source-keyed animation after its direction flipped: each point at
11507/// source frame `p` moves to `in + out - 1 - p`, the same footage frame seen from the
11508/// other end of the window, so the point stays on the timeline frame it was on.
11509fn mirror_keys(c: &mut Clip) {
11510 let top = i64::from(c.in_frame) + i64::from(c.out_frame) - 1;
11511 c.gain_keys = mirrored(&c.gain_keys, top, |k| k.at, |k| k.ease, |k, at, ease| GainKey { at, ease, ..*k });
11512 c.transform_keys =
11513 mirrored(&c.transform_keys, top, |k| k.at, |k| k.ease, |k, at, ease| TransformKey { at, ease, ..*k });
11514 c.opacity_keys = mirrored(&c.opacity_keys, top, |k| k.at, |k| k.ease, |k, at, ease| OpacityKey { at, ease, ..*k });
11515 c.color_keys = mirrored(&c.color_keys, top, |k| k.at, |k| k.ease, |k, at, ease| ColorKey { at, ease, ..*k });
11516 for e in &mut c.effects {
11517 e.keys = mirrored(&e.keys, top, |k| k.at, |k| k.ease, |k, at, ease| crate::effects::EffectKey { at, ease, ..*k });
11518 }
11519}
11520
11521/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
11522/// there would cut in two. A placement's own first frame is not inside it.
11523fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
11524 let idx = at(clips, frame)?;
11525 // ...and, on a speeded clip, one its rate can actually address
11526 // ([`Speed::split_at`]): a cut between two showings of one source frame
11527 // would leave halves that no longer add up to the clip that was cut.
11528 (frame > clips[idx].start)
11529 .then_some(idx)
11530 .filter(|&idx| split_source(&clips[idx], frame).is_some())
11531}
11532
11533/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
11534/// rate cannot address that frame.
11535fn split_source(c: &Clip, frame: u32) -> Option<u32> {
11536 if !c.speed_keys.is_empty() {
11537 // A reversed ramp is not cut yet: its far end would need the ramp mirrored.
11538 if c.reversed {
11539 return None;
11540 }
11541 return ramp_split(&c.speed_keys, c.len(), frame - c.start).map(|(src, _, _)| c.in_frame + src);
11542 }
11543 c.speed.split_at(c.len(), frame - c.start).map(|src| match c.reversed {
11544 // The head of a reversed clip is the window's far end, so the cut is that
11545 // far down from the out-point.
11546 true => c.out_frame - src,
11547 false => c.in_frame + src,
11548 })
11549}
11550
11551/// The speed keys each half of `c` keeps when it is cut at `frame`. Both empty for a
11552/// constant rate, which keeps its own [`Speed`] on both halves.
11553fn split_keys(c: &Clip, frame: u32) -> (Vec<SpeedKey>, Vec<SpeedKey>) {
11554 if c.speed_keys.is_empty() {
11555 return (Vec::new(), Vec::new());
11556 }
11557 match ramp_split(&c.speed_keys, c.len(), frame - c.start) {
11558 Some((_, head, tail)) => (head, tail),
11559 None => (Vec::new(), Vec::new()),
11560 }
11561}
11562
11563/// Where a ramped clip of `src_len` source frames can be cut at its clip-relative timeline
11564/// frame `off`, and the keys each half keeps. The source frame the tail starts at is
11565/// relative to the clip's in-point. `None` where the cut would not add up in whole frames
11566/// on both halves -- the ramp's own version of what [`Speed::split_at`] asks of a constant
11567/// rate. Reads at which the ramp lands near a frame boundary answer; the others do not.
11568pub fn ramp_split(keys: &[SpeedKey], src_len: u32, off: u32) -> Option<(u32, Vec<SpeedKey>, Vec<SpeedKey>)> {
11569 let len = ramp_frames(keys, src_len);
11570 if off == 0 || off >= len {
11571 return None;
11572 }
11573 let src = ramp_source_at(keys, f64::from(off)).round();
11574 if src < 1. || src >= f64::from(src_len) {
11575 return None;
11576 }
11577 let src = src as u32;
11578 let head = ramp_keys_until(keys, off);
11579 let tail = ramp_keys_from(keys, off);
11580 let whole = valid_speed_keys(&head)
11581 && valid_speed_keys(&tail)
11582 && ramp_frames(&head, src) == off
11583 && ramp_frames(&tail, src_len - src) == len - off;
11584 whole.then_some((src, head, tail))
11585}
11586
11587/// The keys of the part of a ramped clip up to clip-relative frame `cut`: the keys before
11588/// it, and the speed there as the last one when the ramp goes on past it. The ramp is held
11589/// to `cut` exactly as the whole ramp plays there, so the head's length comes back as `cut`.
11590pub fn ramp_keys_until(keys: &[SpeedKey], cut: u32) -> Vec<SpeedKey> {
11591 let mut out: Vec<SpeedKey> = keys.iter().copied().filter(|k| k.at < cut).collect();
11592 if keys.iter().any(|k| k.at > cut) {
11593 out.push(SpeedKey { at: cut, speed: ramp_speed_at(keys, cut) });
11594 }
11595 out
11596}
11597
11598/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
11599/// rejoin: they must touch there, and be consecutive frames of one source.
11600fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
11601 let idx = clips.iter().position(|c| c.end() == frame)?;
11602 let next = clips.get(idx + 1)?;
11603 let left = &clips[idx];
11604 (next.start == frame
11605 && next.source == left.source
11606 && next.reversed == left.reversed
11607 && match left.reversed {
11608 // The halves of a reversed cut swap sides: the head holds the window's
11609 // upper part.
11610 true => left.in_frame == next.out_frame,
11611 false => next.in_frame == left.out_frame,
11612 }
11613 // ...at one rate, and one that puts the rejoined clip back in exactly
11614 // the room the two took up: what a split could have produced, which is
11615 // all this undoes. A ramp is held to the same test, on its own keys.
11616 && next.speed == left.speed
11617 && joined_clip(left, next).is_some_and(|j| j.frames() == left.frames() + next.frames()))
11618 .then_some(idx)
11619}
11620
11621/// The clip that two halves of one cut rejoin into: `left` extended to the end of
11622/// `right`, with the animation both halves hold merged ([`merge_keys`]) and the
11623/// right half's end edge kept (its `fade_out` and dissolve), which a split takes
11624/// away from the left half. The speed ramp is [`joined_speed_keys`]. `None` when
11625/// the merged animation would not fit or is not a ramp the engine plays.
11626fn joined_clip(left: &Clip, right: &Clip) -> Option<Clip> {
11627 let mut out = left.clone();
11628 out.speed_keys = joined_speed_keys(left, right)?;
11629 out.transform_keys =
11630 merge_keys(&left.transform_keys, &right.transform_keys, |k| k.at, MAX_TRANSFORM_KEYS)?;
11631 out.opacity_keys =
11632 merge_keys(&left.opacity_keys, &right.opacity_keys, |k| k.at, MAX_TRANSFORM_KEYS)?;
11633 out.color_keys = merge_keys(&left.color_keys, &right.color_keys, |k| k.at, MAX_COLOR_KEYS)?;
11634 out.gain_keys = merge_keys(&left.gain_keys, &right.gain_keys, |k| k.at, MAX_GAIN_KEYS)?;
11635 // Effects are matched by stack slot, and only when both halves carry the same
11636 // stack; otherwise the left half's effects stand as they are.
11637 let same_stack = left.effects.len() == right.effects.len()
11638 && left.effects.iter().zip(&right.effects).all(|(l, r)| l.kind == r.kind);
11639 if same_stack {
11640 for (e, r) in out.effects.iter_mut().zip(&right.effects) {
11641 e.keys = merge_keys(&e.keys, &r.keys, |k| k.at, MAX_TRANSFORM_KEYS)?;
11642 }
11643 }
11644 out.fade_out = right.fade_out;
11645 out.transition_out = right.transition_out;
11646 out.transition_kind = right.transition_kind;
11647 match left.reversed {
11648 true => out.in_frame = right.in_frame,
11649 false => out.out_frame = right.out_frame,
11650 }
11651 Some(out)
11652}
11653
11654/// The keys of one animation, both halves of a cut joined: the left half's keys,
11655/// then the right half's keys whose source frame the left does not already hold
11656/// (the cut is a key on both halves, so it is kept once), sorted by frame. Keys
11657/// are source frames on both sides, so the union is the same whichever half
11658/// comes first. `None` when the union holds more than `cap` keys.
11659fn merge_keys<K: Clone>(
11660 left: &[K],
11661 right: &[K],
11662 at: impl Fn(&K) -> u32,
11663 cap: usize,
11664) -> Option<Vec<K>> {
11665 let mut out = left.to_vec();
11666 out.extend(right.iter().filter(|r| left.iter().all(|l| at(l) != at(r))).cloned());
11667 out.sort_by_key(|k| at(k));
11668 (out.len() <= cap).then_some(out)
11669}
11670
11671/// The speed ramp of two rejoined halves ([`Clip::speed_keys`]). Ramp keys count
11672/// clip-relative timeline frames, so the right half's keys move on by the left
11673/// half's timeline length and the left's last key and the right's first are the
11674/// same cut, kept once. Two constant halves have no ramp; one ramped half and one
11675/// constant half, or a reversed ramp (which no split makes), do not join. `None`
11676/// when the joined keys are not a ramp the engine plays.
11677fn joined_speed_keys(left: &Clip, right: &Clip) -> Option<Vec<SpeedKey>> {
11678 match (left.speed_keys.is_empty(), right.speed_keys.is_empty()) {
11679 (true, true) => return Some(Vec::new()),
11680 (false, false) if !left.reversed => {}
11681 _ => return None,
11682 }
11683 let off = left.frames();
11684 let mut keys = left.speed_keys.clone();
11685 for k in &right.speed_keys {
11686 let at = k.at + off;
11687 if keys.last().map_or(true, |l| l.at < at) {
11688 keys.push(SpeedKey { at, speed: k.speed });
11689 }
11690 }
11691 valid_speed_keys(&keys).then_some(keys)
11692}
11693
11694/// The lane invariant: sorted by `start`, no two placements overlapping, no
11695/// empty placement. Checked at every constructor and asserted after every
11696/// mutation -- the offset model is only tractable while it holds.
11697/// The one thing an equalizer setting may not be: a value the text format
11698/// cannot write and read back as itself. Checked wherever params come in, so
11699/// what an edit produces is always what a save writes and a load reads.
11700fn finite(params: &EqParams) -> bool {
11701 params
11702 .bands
11703 .iter()
11704 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
11705}
11706
11707/// The same for a colour grade: [`crate::color`] itself falls back to identity
11708/// on a non-finite value, but a value that cannot be written and read back as
11709/// itself has no business reaching the model.
11710fn color_finite(p: &ColorParams) -> bool {
11711 let w = &p.look.wheels;
11712 w.lift.iter().chain(&w.gamma).chain(&w.gain).all(|v| v.is_finite())
11713 && p.look.lut_mix.is_finite()
11714 && p.brightness.is_finite()
11715 && p.contrast.is_finite()
11716 && p.saturation.is_finite()
11717 && p.tint.is_finite()
11718}
11719
11720/// The same for a transform: [`crate::scale`] clamps a non-finite value to
11721/// identity at read time, but a value that cannot round-trip has no business
11722/// reaching the model.
11723fn transform_finite(p: &TransformParams) -> bool {
11724 p.pos_x.is_finite()
11725 && p.pos_y.is_finite()
11726 && p.scale.is_finite()
11727 && p.rotate.is_finite()
11728 && p.crop_l.is_finite()
11729 && p.crop_r.is_finite()
11730 && p.crop_t.is_finite()
11731 && p.crop_b.is_finite()
11732 && (0.0..=1.0).contains(&p.opacity)
11733}
11734
11735fn sorted_disjoint(clips: &[Clip]) -> bool {
11736 clips.iter().all(|c| c.out_frame > c.in_frame)
11737 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
11738}
11739
11740/// The very same invariant on a subtitle lane, in that lane's own two units:
11741/// sorted by `start`, no two placements overlapping, no empty placement at
11742/// either end. Asserted after every mutation, exactly as its twin is.
11743fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
11744 subs.iter()
11745 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
11746 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
11747}
11748
11749/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
11750/// the one conversion between a lane's clock and a cue's, and `0` for a rate
11751/// that is not one (every caller of this has already refused such a rate).
11752fn us_of(frames: i64, fps: f64) -> i64 {
11753 match fps.is_finite() && fps > 0.0 {
11754 true => ((frames as f64) / fps * 1e6).round() as i64,
11755 false => 0,
11756 }
11757}
11758
11759/// **The one function in this file that writes a caption's window.** Every
11760/// composer -- a trim, a split, a ripple, a group follow, a rejoin -- routes
11761/// through it, and the invariant it holds is total:
11762///
11763/// ```text
11764/// 0 <= in_us and in_us < out_us and out_us - in_us <= MAX_WINDOW_US
11765/// ```
11766///
11767/// which is the never-empty invariant plus the width ceiling, restated as one
11768/// shape both ends of it come from. Note that the ceiling bounds a
11769/// **difference**, which is why a per-arm check is not enough and this is:
11770///
11771/// - Growing `out_us` (a tail trim) makes the width larger, so the *upper*
11772/// wall bites.
11773/// - Falling `in_us` (a head trim) makes the width larger too, from the other
11774/// side -- so bounding `in_us` alone, which is what a head trim's own clamp
11775/// (`in_us <= out_us - 1`) does, says nothing at all about the ceiling.
11776/// - A rejoin takes the left half's `in_us` and the right half's `out_us`, and
11777/// the two halves are consecutive in the *source* (that is what
11778/// [`sub_joinable`] requires), so the joined width is the **sum** of two
11779/// legal widths. Each half passes its own door; the whole does not.
11780///
11781/// Three rounds of review each found one more composer this way, so the
11782/// function is the fix rather than any single call site: clamping a new
11783/// caller into shape is a two-line change, and forgetting one is silent.
11784/// `every_window_write_goes_through_set_window` (in the tests below) is the
11785/// other half of that promise -- it scans the file and fails if a write
11786/// appears anywhere else.
11787///
11788/// **Why it clamps where the doors refuse.** The doors -- the parser,
11789/// [`Project::with_subs`], [`Project::place_sub`] -- see a value on the way
11790/// IN, from a file or a foreign caller, where nobody was mid-gesture, so a
11791/// value that wide is named and refused rather than quietly changed. Every
11792/// composer below is an edit a person is watching happen, so the same value is
11793/// clamped to the end of the window: a drag that stops, exactly like the frame
11794/// walls these trims already apply.
11795fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {
11796 let in_us = in_us.max(0);
11797 // The `+ 1` is the never-empty invariant: the window is open, always, so a
11798 // composer that would otherwise clamp it shut lands on one microsecond.
11799 let out_us = out_us.clamp(in_us + 1, in_us.saturating_add(MAX_WINDOW_US));
11800 s.in_us = in_us;
11801 s.out_us = out_us;
11802 debug_assert!(
11803 s.in_us >= 0 && s.out_us > s.in_us && s.out_us - s.in_us <= MAX_WINDOW_US,
11804 "set_window left an illegal window: {:?}",
11805 (s.in_us, s.out_us)
11806 );
11807}
11808
11809/// The two pieces a cue becomes when a window edge at `t_us` falls inside it:
11810/// `(start, end, text)` for the piece before the edge and the one after, the
11811/// words shared between them at the word boundary nearest the point that is the
11812/// same fraction of the words as `t_us` is of the time. A piece with no words is
11813/// left out. A cue with one word has no boundary to divide at, so that word
11814/// stays on the longer side of the edge (ties: the piece before it) and the
11815/// other side is left out too. `None` for a cue with no words at all.
11816fn split_words(c: &crate::subtitle::Cue, t_us: i64) -> Option<Vec<(i64, i64, String)>> {
11817 let text = c.text.as_str();
11818 let mut starts: Vec<usize> = Vec::new();
11819 let mut prev_space = true;
11820 for (i, ch) in text.char_indices() {
11821 let space = ch.is_whitespace();
11822 if !space && prev_space {
11823 starts.push(i);
11824 }
11825 prev_space = space;
11826 }
11827 let n = starts.len();
11828 if n == 0 {
11829 return None;
11830 }
11831 if n == 1 {
11832 let word = text.trim().to_string();
11833 let before = t_us - c.start_us;
11834 let after = c.end_us - t_us;
11835 return Some(if before >= after {
11836 vec![(c.start_us, t_us, word)]
11837 } else {
11838 vec![(t_us, c.end_us, word)]
11839 });
11840 }
11841 let p = (t_us - c.start_us) as f64 / (c.end_us - c.start_us) as f64;
11842 let k = ((p * n as f64).round() as usize).min(n);
11843 let mut out = Vec::with_capacity(2);
11844 if k >= 1 {
11845 let end = if k < n { starts[k] } else { text.len() };
11846 out.push((c.start_us, t_us, text[..end].trim_end().to_string()));
11847 }
11848 if k < n {
11849 out.push((t_us, c.end_us, text[starts[k]..].to_string()));
11850 }
11851 Some(out)
11852}
11853
11854/// [`split_words`] for one edge of a cut. With `both_sides` a one-word cue is
11855/// kept whole on both sides of the point, so the side the cut leaves in its
11856/// window survives: which side that is, only the ripple knows, and
11857/// [`Project::drop_unplaced`] drops the other. Every other cue is
11858/// [`split_words`]' division.
11859fn cut_pieces(c: &crate::subtitle::Cue, t_us: i64, both_sides: bool) -> Option<Vec<(i64, i64, String)>> {
11860 if both_sides && c.text.split_whitespace().count() == 1 {
11861 let word = c.text.trim().to_string();
11862 return Some(vec![(c.start_us, t_us, word.clone()), (t_us, c.end_us, word)]);
11863 }
11864 split_words(c, t_us)
11865}
11866
11867/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
11868/// dropping what is inside the hole, splitting what straddles it and trimming
11869/// what overlaps an edge. The windows follow the cut by proportion
11870/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
11871fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
11872 sub_clear_with(subs, start, end, &mut |_| (None, None));
11873}
11874
11875/// [`sub_clear`] with the (head, tail) links its pieces carry, as [`clear_with`] has for clips.
11876fn sub_clear_with(subs: &mut Vec<SubClip>, start: u32, end: u32, links: &mut dyn FnMut(Option<u32>) -> (Option<u32>, Option<u32>)) {
11877 let mut out = Vec::with_capacity(subs.len() + 1);
11878 for s in subs.drain(..) {
11879 if s.end() <= start || s.start >= end {
11880 out.push(s);
11881 continue;
11882 }
11883 if s.start < start {
11884 let cut = s.window_at(start);
11885 let (head_link, _) = links(s.link);
11886 let mut head = SubClip {
11887 frames: start - s.start,
11888 link: head_link,
11889 ..s
11890 };
11891 // `window_at` already answers inside the window, and `set_window`
11892 // is the shape that says so once, for every composer, rather than
11893 // leaving each of them to re-derive it.
11894 set_window(&mut head, s.in_us, cut);
11895 out.push(head);
11896 }
11897 if s.end() > end {
11898 let cut = s.window_at(end);
11899 let (_, tail_link) = links(s.link);
11900 let mut tail = SubClip {
11901 start: end,
11902 frames: s.end() - end,
11903 link: tail_link,
11904 ..s
11905 };
11906 set_window(&mut tail, cut, s.out_us);
11907 out.push(tail);
11908 }
11909 }
11910 *subs = out;
11911}
11912
11913/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
11914/// `len`, splitting a placement that straddles `at` so the two halves end up on
11915/// either side of the hole. A `len` of 0 is that split alone, which is what a
11916/// [`Project::split`] over a subtitle lane is.
11917fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
11918 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
11919 let s = subs[idx];
11920 let cut = s.window_at(at);
11921 let mut head = SubClip {
11922 frames: at - s.start,
11923 link: None,
11924 ..s
11925 };
11926 set_window(&mut head, s.in_us, cut);
11927 subs[idx] = head;
11928 let mut tail = SubClip {
11929 start: at,
11930 frames: s.end() - at,
11931 link: None,
11932 ..s
11933 };
11934 set_window(&mut tail, cut, s.out_us);
11935 subs.insert(idx + 1, tail);
11936 }
11937 for s in subs.iter_mut().filter(|s| s.start >= at) {
11938 s.start += len;
11939 }
11940}
11941
11942/// [`joinable`] for a subtitle lane: the first of the two placements a
11943/// [`Project::regroup`] at `frame` would rejoin. What a split could have
11944/// produced and nothing else -- they touch on the timeline, they read the same
11945/// track, and the second one's window carries on where the first's stopped.
11946fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
11947 let idx = subs.iter().position(|s| s.end() == frame)?;
11948 let next = subs.get(idx + 1)?;
11949 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
11950 .then_some(idx)
11951}
11952
11953/// How far one `edge` of the caption at `idx` may travel against its own lane's
11954/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
11955/// rate, which a caption *following* a group's trim does not have to be exact
11956/// about -- its own walls, its own one surviving frame, and nothing that needs
11957/// a clock.
11958fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
11959 let s = &subs[idx];
11960 match edge {
11961 Edge::Start => (idx.checked_sub(1).map_or(0, |p| subs[p].end()), s.end() - 1),
11962 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
11963 }
11964}
11965
11966/// Move one `edge` of `s` to timeline frame `to`, its window following by the
11967/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
11968/// forwards and backwards. The caption a group's trim is carrying has no rate
11969/// of its own and needs none: what one frame of it is worth in microseconds is
11970/// the window it already shows over the frames it already takes.
11971fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
11972 let per_frame = s.window_us() / i64::from(s.frames.max(1));
11973 // The `saturating_mul` keeps a `SubClip` that reached here without a door
11974 // behind it from wrapping the window negative; `set_window` is what keeps
11975 // the result legal rather than merely finite. This is the group-follow twin
11976 // of [`Project::trim_sub`], and it reaches the same field from both edges --
11977 // so a fix that only walled the primary trim's End arm left the head (and
11978 // the whole group path) open.
11979 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
11980 match edge {
11981 Edge::Start => {
11982 set_window(s, s.in_us.saturating_add(by(s.start, to)), s.out_us);
11983 s.frames = s.end() - to;
11984 s.start = to;
11985 }
11986 Edge::End => {
11987 set_window(s, s.in_us, s.out_us.saturating_add(by(s.end(), to)));
11988 s.frames = to - s.start;
11989 }
11990 }
11991 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
11992}
11993
11994/// The grouping invariant, checked in release at [`Project::from_parts`] and
11995/// asserted by the tests after every edit: a link id names **at most one**
11996/// placement per lane -- a clip on a media lane or a caption on a subtitle
11997/// one, whichever carries it. That is all "these move together" can mean now
11998/// that a group is assembled by hand: the members keep their own spans and
11999/// their own offsets, and what binds them is the id alone.
12000///
12001/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
12002/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
12003/// placements of one group may cover different frames -- the offset-preserving
12004/// group a hand builds with [`Project::group_all`], which a drag moves by one
12005/// delta rather than by one span.
12006///
12007/// A link no other lane carries is legal and is not an error: lifting one half
12008/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
12009/// timeline has to load again.
12010/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
12011/// asked by the sweep suite's universal law.
12012#[cfg(test)]
12013pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
12014 links_are_consistent(&p.lanes)
12015}
12016
12017/// What a take is, for [`Project::ungroup`]: the halves of one take read the
12018/// same source over the same frames, so they share these four numbers.
12019type TakeKey = (usize, u32, u32, u32);
12020
12021fn take_key(c: &Clip) -> TakeKey {
12022 (c.source, c.start, c.in_frame, c.out_frame)
12023}
12024
12025fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
12026 let handles = handles(lanes);
12027 for (data, lane) in lanes.iter().zip(&handles) {
12028 for (i, c) in data.clips.iter().enumerate() {
12029 let Some(id) = c.link else { continue };
12030 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
12031 return Err(
12032 format!("link {id} names two clips in the {} lane", lane.label()).into(),
12033 );
12034 }
12035 }
12036 // ...and the same for the captions, in their own list on the same lane:
12037 // a subtitle lane holds no `Clip`, so this is the only list a caption's
12038 // id could be doubled on.
12039 for (i, s) in data.subs.iter().enumerate() {
12040 let Some(id) = s.link else { continue };
12041 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
12042 return Err(
12043 format!("link {id} names two captions in the {} lane", lane.label()).into(),
12044 );
12045 }
12046 }
12047 }
12048 Ok(())
12049}
12050
12051/// Removes the timeline frames `[start, end)` from `clips`: placements inside
12052/// it go, one straddling it is split in two, one overlapping an edge is
12053/// trimmed. Source frames follow the trim, so what is left plays what it always
12054/// played. Leaves the lane sorted and disjoint.
12055///
12056/// A piece the hole cut is no longer the take its group id names -- and both
12057/// halves of a straddled placement carrying that id would be the same id twice
12058/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
12059fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
12060 clear_with(clips, start, end, &mut |_| (None, None));
12061}
12062
12063/// [`clear`] with the links the pieces it leaves carry: `links` gives the (head, tail) ids of a clip
12064/// that straddles the hole. `clear` itself gives both none, the detach rule of a delete.
12065fn clear_with(clips: &mut Vec<Clip>, start: u32, end: u32, links: &mut dyn FnMut(Option<u32>) -> (Option<u32>, Option<u32>)) {
12066 let mut out = Vec::with_capacity(clips.len() + 1);
12067 for c in clips.drain(..) {
12068 // Disjoint from the hole: untouched.
12069 if c.end() <= start || c.start >= end {
12070 out.push(c);
12071 continue;
12072 }
12073 // The head that survives in front of the hole -- as much source as fits
12074 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
12075 // which at real time is that room itself. Never *more*: a head that
12076 // outgrew its room would reach into the hole it is being cut out of,
12077 // which is exactly the overlap a slow clip punched at a frame its rate
12078 // cannot address used to leave (at 0.25x a single source frame is four
12079 // timeline frames, and three frames of room hold none of it). `None`
12080 // there means no remainder at all, and the piece simply goes.
12081 if let Some(keep) = c.fit_source(start.saturating_sub(c.start))
12082 && c.start < start
12083 {
12084 let (head, _) = links(c.link);
12085 let mut piece = Clip {
12086 fade_in: 0,
12087 fade_out: 0,
12088 transition_out: 0,
12089 transition_kind: Default::default(),
12090 link: head,
12091 ..c.clone()
12092 };
12093 // What survives in front plays the window's far end when it is reversed.
12094 match c.reversed {
12095 true => piece.in_frame = c.out_frame - keep.min(c.len()),
12096 false => piece.out_frame = c.in_frame + keep.min(c.len()),
12097 }
12098 out.push(piece);
12099 }
12100 // ...and the tail behind it, which keeps reading up to where it would
12101 // have: measured from its out-point for the head's reason, so what it
12102 // occupies still ends where the whole clip did -- and dropped whole on
12103 // the same `None`.
12104 // A ramp's tail restarts at `end`, so its keys are rebased to that frame
12105 // ([`ramp_keys_from`]) and its room is measured with them.
12106 let tail_keys = if c.speed_keys.is_empty() {
12107 Vec::new()
12108 } else {
12109 ramp_keys_from(&c.speed_keys, end.saturating_sub(c.start))
12110 };
12111 let tail_probe = Clip { speed_keys: tail_keys.clone(), ..c.clone() };
12112 if let Some(keep) = tail_probe.fit_source(c.end().saturating_sub(end))
12113 && c.end() > end
12114 {
12115 let (_, tail) = links(c.link);
12116 let mut piece = Clip {
12117 fade_in: 0,
12118 fade_out: 0,
12119 transition_out: 0,
12120 transition_kind: Default::default(),
12121 start: end,
12122 link: tail,
12123 speed_keys: tail_keys,
12124 ..c.clone()
12125 };
12126 match c.reversed {
12127 true => piece.out_frame = c.in_frame + keep.min(c.len()),
12128 false => piece.in_frame = c.out_frame - keep.min(c.len()),
12129 }
12130 out.push(piece);
12131 }
12132 }
12133 *clips = out;
12134}
12135
12136/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
12137/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
12138/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
12139/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
12140/// the caller.
12141fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
12142 for &i in on {
12143 let clips = &mut lanes[i].clips;
12144 clear(clips, at, at + len);
12145 for c in clips.iter_mut().filter(|c| c.start >= at) {
12146 c.start -= len;
12147 }
12148 debug_assert!(sorted_disjoint(clips));
12149 // The subtitle lanes close the hole with everything else: a caption
12150 // left standing where the picture it belongs to was cut out is the
12151 // desync a lane model exists to make impossible.
12152 let subs = &mut lanes[i].subs;
12153 sub_clear(subs, at, at + len);
12154 for s in subs.iter_mut().filter(|s| s.start >= at) {
12155 s.start -= len;
12156 }
12157 debug_assert!(subs_sorted_disjoint(subs));
12158 }
12159}
12160
12161/// Moves every clip and caption on `lane` that starts at or after `from` by `delta` frames: the
12162/// second half of a ripple trim ([`Project::ripple_trim`]), which closes or opens the hole an edge
12163/// left. No snapshot of its own.
12164fn shift_behind(lane: &mut LaneData, from: u32, delta: i64) {
12165 let step = |s: u32| (i64::from(s) + delta) as u32;
12166 for c in lane.clips.iter_mut().filter(|c| c.start >= from) {
12167 c.start = step(c.start);
12168 }
12169 debug_assert!(sorted_disjoint(&lane.clips));
12170 for s in lane.subs.iter_mut().filter(|s| s.start >= from) {
12171 s.start = step(s.start);
12172 }
12173 debug_assert!(subs_sorted_disjoint(&lane.subs));
12174}
12175
12176/// [`ripple`] for a cut that keeps its takes together: every take it splits keeps its id on the
12177/// piece before the cut, and the pieces after it share one fresh id per take, as the razor's
12178/// split does ([`Project::split_on`]). Only [`Project::cut_regions`] calls it, and that refuses
12179/// any scope that would take one half of a take with it, so every take it splits is whole in scope.
12180fn ripple_keeping_takes(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32, next_link: &mut u32) {
12181 let mut tails: Vec<(u32, u32)> = Vec::new();
12182 let mut links = |old: Option<u32>| -> (Option<u32>, Option<u32>) {
12183 let Some(id) = old else { return (None, None) };
12184 let tail = match tails.iter().find(|(o, _)| *o == id) {
12185 Some(&(_, t)) => t,
12186 None => {
12187 let t = *next_link;
12188 *next_link = next_link.saturating_add(1);
12189 tails.push((id, t));
12190 t
12191 }
12192 };
12193 (Some(id), Some(tail))
12194 };
12195 for &i in on {
12196 let clips = &mut lanes[i].clips;
12197 clear_with(clips, at, at + len, &mut links);
12198 for c in clips.iter_mut().filter(|c| c.start >= at) {
12199 c.start -= len;
12200 }
12201 debug_assert!(sorted_disjoint(clips));
12202 let subs = &mut lanes[i].subs;
12203 sub_clear_with(subs, at, at + len, &mut links);
12204 for s in subs.iter_mut().filter(|s| s.start >= at) {
12205 s.start -= len;
12206 }
12207 debug_assert!(subs_sorted_disjoint(subs));
12208 }
12209}
12210
12211/// Every lane, as the index list the two above take: what "the whole timeline"
12212/// is spelled as, and the scope [`Project::ripple_delete`] and
12213/// [`Project::split`] have always had.
12214fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
12215 (0..lanes.len()).collect()
12216}
12217
12218/// A caller's region list as a batch may use it: sorted by start, empty entries
12219/// dropped, and touching or overlapping entries merged into one.
12220///
12221/// Overlapping regions are the one thing a batch cannot take -- cutting the
12222/// second would cut frames the first already moved -- and a detector handing
12223/// back two that touch means one silence, not two cuts. Merged rather than
12224/// refused: this is arithmetic on a preview, not a user's mistake.
12225fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
12226 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
12227 sorted.sort_by_key(|&(at, _)| at);
12228 let mut out: Vec<(u32, u32)> = Vec::new();
12229 for (at, len) in sorted {
12230 let end = at.saturating_add(len);
12231 match out.last_mut() {
12232 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
12233 _ => out.push((at, len)),
12234 }
12235 }
12236 out
12237}
12238
12239/// Slides everything from `at` on later by `len`, splitting a placement that
12240/// straddles `at` so the two halves end up on either side of the hole. The
12241/// insert half of a rippling paste. The two halves lose the group id for the
12242/// reason [`clear`] gives.
12243fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
12244 if let Some(idx) = splittable(clips, at) {
12245 let mut tail = clips[idx].clone();
12246 // The cut in *source* frames, at the clip's own rate. `splittable` has
12247 // already refused a frame the rate cannot address, which is why
12248 // [`Project::paste`] refuses one too rather than opening room inside a
12249 // clip that cannot be cut there.
12250 let cut_at = split_source(&tail, at).expect("splittable said so");
12251 let (head_speed, tail_speed) = split_keys(&tail, at);
12252 tail.speed_keys = tail_speed;
12253 clips[idx].speed_keys = head_speed;
12254 match tail.reversed {
12255 true => {
12256 tail.out_frame = cut_at;
12257 clips[idx].in_frame = cut_at;
12258 }
12259 false => {
12260 tail.in_frame = cut_at;
12261 clips[idx].out_frame = cut_at;
12262 }
12263 }
12264 tail.start = at;
12265 tail.link = None;
12266 clips[idx].link = None;
12267 clips.insert(idx + 1, tail);
12268 }
12269 for c in clips.iter_mut().filter(|c| c.start >= at) {
12270 c.start += len;
12271 }
12272}
12273
12274/// Absolute, symlink-resolved when the file is reachable; the path as given
12275/// when it is not -- an unreadable path still deserves an index, it simply
12276/// dedups by spelling.
12277pub(crate) fn canonical(path: &Path) -> PathBuf {
12278 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
12279}
12280
12281#[cfg(test)]
12282mod tests {
12283 use super::*;
12284
12285 const FPS: f64 = 30.0;
12286
12287 /// A caption track that ends between two frames places with a window of
12288 /// whole frames: 4.750 s at 30 fps is 143 frames, and its cues keep their
12289 /// times (0.5 s is frame 15, 4.5 s is frame 135) instead of being stretched
12290 /// by 143 / 142.5 as they were when the window was the track's own length.
12291 #[test]
12292 fn a_whole_track_drop_is_not_stretched_by_its_last_frame() {
12293 let sub = SubClip::whole_track(2, 4_750_000, FPS);
12294 assert_eq!((sub.track, sub.start, sub.in_us), (2, 0, 0));
12295 assert_eq!(sub.frames, 143, "the fewest frames that hold the last cue");
12296 assert_eq!(sub.out_us, 4_766_667, "the window is the frames' own length");
12297 let frame_of = |us: i64| f64::from(sub.frames) * us as f64 / sub.window_us() as f64;
12298 for (us, want) in [(500_000i64, 15.0), (750_000, 22.5), (4_500_000, 135.0)] {
12299 assert!((frame_of(us) - want).abs() < 1e-3, "cue at {us} us lands on frame {}", frame_of(us));
12300 }
12301 // The old window (the track's length) put 4.5 s on 135.47 frames.
12302 assert!((4_500_000f64 * 143.0 / 4_750_000.0 - 135.0).abs() > 0.4);
12303 // A track that ends on a frame is that many frames, with no extra one.
12304 let exact = SubClip::whole_track(0, 1_000_000, FPS);
12305 assert_eq!((exact.frames, exact.out_us), (30, 1_000_000));
12306 }
12307 /// Never opened -- `Project` is pure data, so a path that does not exist is
12308 /// simply a path that dedups by spelling.
12309 const FILE: &str = "/nonexistent/a.mp4";
12310 const FILE2: &str = "/nonexistent/b.mp4";
12311
12312 /// A batch is one undo step however many edits it makes, far past the cap; undo takes
12313 /// back the whole batch, and an edit after `end_batch` takes its own step.
12314 #[test]
12315 fn a_batch_is_one_undo_step_past_the_cap() {
12316 let mut p = Project::single(FILE, 1);
12317 let v = p.add_lane(LaneKind::Video);
12318 let base = p.history_len();
12319 p.begin_batch();
12320 for k in 0..150u32 {
12321 assert!(p.place(v, k * 3, clip(k * 3, 0, 3, 0)));
12322 }
12323 p.end_batch();
12324 assert_eq!(p.history_len(), base + 1, "the batch is one step");
12325 assert_eq!(p.lane_clips_pub(v).len(), 150);
12326
12327 assert!(p.undo());
12328 assert!(p.lane_clips_pub(v).is_empty(), "undo takes the whole batch back");
12329 assert_eq!(p.history_len(), base);
12330
12331 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
12332 assert_eq!(p.history_len(), base + 1, "an edit outside a batch is its own step");
12333 }
12334
12335 /// Undo inside a batch starts a fresh step for what follows it, so the edits after it
12336 /// are not lost from the history.
12337 #[test]
12338 fn an_undo_inside_a_batch_opens_a_new_step() {
12339 let mut p = Project::single(FILE, 1);
12340 let v = p.add_lane(LaneKind::Video);
12341 let base = p.history_len();
12342 p.begin_batch();
12343 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
12344 assert!(p.undo());
12345 assert!(p.place(v, 0, clip(0, 0, 4, 0)));
12346 p.end_batch();
12347 assert_eq!(p.history_len(), base + 1);
12348 assert!(p.undo());
12349 assert!(p.lane_clips_pub(v).is_empty());
12350 }
12351
12352 /// A contiguous placement, group id ignored: what most assertions compare.
12353 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
12354 Clip {
12355 speed_keys: Vec::new(),
12356 reversed: false,
12357 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
12358 angle: Default::default(),
12359 fade_in: 0,
12360 fade_out: 0,
12361 transition_out: 0,
12362 transition_kind: Default::default(),
12363 visualizer: 0,
12364 viz_paint: 0,
12365 gain_db: 0.0,
12366 gain_keys: Vec::new(),
12367 pan: 0,
12368 pitch: 0,
12369 transform_keys: Vec::new(),
12370 opacity_keys: Vec::new(),
12371 color_keys: Vec::new(),
12372 effects: Vec::new(),
12373 start,
12374 in_frame,
12375 out_frame,
12376 source,
12377 link: None,
12378 eq: None,
12379 color: None,
12380 transform: None,
12381 fit: FitPolicy::default(),
12382 speed: Speed::NORMAL,
12383 }
12384 }
12385
12386 /// A reversed clip's timeline head is its source out side: a split gives the
12387 /// head the late footage and the tail the early, a trim of the head eats the
12388 /// source's end, and joining the halves gives the one clip back.
12389 #[test]
12390 fn a_reversed_clip_splits_trims_and_joins_from_its_out_side() {
12391 let mut p = Project::single(FILE, 100);
12392 let v = p.add_lane(LaneKind::Video);
12393 let mut c = clip(0, 0, 100, 0);
12394 c.reversed = true;
12395 assert!(p.place(v, 0, c.clone()));
12396 assert!(p.split(30));
12397 let halves = p.lane_clips_pub(v).to_vec();
12398 assert_eq!((halves[0].start, halves[0].in_frame, halves[0].out_frame), (0, 70, 100));
12399 assert_eq!((halves[1].start, halves[1].in_frame, halves[1].out_frame), (30, 0, 70));
12400 assert!(halves.iter().all(|h| h.reversed));
12401 assert!(p.regroup(30), "the halves are one reversed run again");
12402 let one = &p.lane_clips_pub(v)[0];
12403 assert_eq!((one.in_frame, one.out_frame, one.reversed), (0, 100, true));
12404 // Trimming the head by 10 frames drops the source's last 10.
12405 assert!(p.trim(v, 0, Edge::Start, 10, &[100]));
12406 let t = &p.lane_clips_pub(v)[0];
12407 assert_eq!((t.start, t.in_frame, t.out_frame), (10, 0, 90));
12408 }
12409
12410 /// A reversed clip's opacity keys are cut at the source frame the cut lands
12411 /// on, not at the window's low edge, so each half shows what the unsplit clip
12412 /// showed at its own timeline frames.
12413 #[test]
12414 fn a_reversed_cut_splits_opacity_keys_where_the_clip_plays_them() {
12415 let mut p = Project::single(FILE, 100);
12416 let v = p.add_lane(LaneKind::Video);
12417 let mut c = clip(0, 0, 100, 0);
12418 c.reversed = true;
12419 assert!(p.place(v, 0, c));
12420 assert!(p.set_opacity_keys(
12421 v,
12422 0,
12423 vec![
12424 OpacityKey { at: 0, opacity: 0.0, ease: KeyEase::EaseIn },
12425 OpacityKey { at: 99, opacity: 1.0, ease: KeyEase::Linear },
12426 ],
12427 ));
12428 let frames = [0u32, 10, 29, 30, 45, 99];
12429 let whole: Vec<f32> = frames.iter().map(|&f| p.opacity_at(v, 0, f)).collect();
12430 assert!(p.split(30));
12431 for (&f, want) in frames.iter().zip(whole) {
12432 let idx = usize::from(f >= 30);
12433 let got = p.opacity_at(v, idx, f);
12434 assert!((got - want).abs() < 0.01, "frame {f}: {got} against {want}");
12435 }
12436 }
12437
12438 /// Toggling is one undo step, mirrors a key anchored to the footage so the
12439 /// timeline behaviour does not change, and refuses a still.
12440 #[test]
12441 fn set_reverse_is_one_undoable_step_and_mirrors_footage_keys() {
12442 let mut p = Project::single(FILE, 100);
12443 let v = p.add_lane(LaneKind::Video);
12444 assert!(p.place(v, 0, clip(0, 0, 100, 0)));
12445 let steps = p.history_len();
12446 p.set_reverse(v, 0, true).expect("reverse");
12447 assert_eq!(p.history_len(), steps + 1);
12448 assert!(p.reversed_of(v, 0));
12449 p.set_reverse(v, 0, true).expect("already so is a no-op");
12450 assert_eq!(p.history_len(), steps + 1, "no second step");
12451 assert_eq!(source_pos(&p.lane_clips_pub(v)[0], 0).floor() as u32, 99, "the first timeline frame shows the last footage");
12452 assert!(p.undo());
12453 assert!(!p.reversed_of(v, 0));
12454 assert!(p.set_reverse(v, 7, true).is_err(), "no such clip");
12455 }
12456
12457 /// The shape `captions_place` makes: one placement covering a three-cue
12458 /// track, where cue 1 ("second") is exactly frames 93..176 at 30 fps.
12459 fn three_cue_captions() -> (Project, Lane) {
12460 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12461 start_us,
12462 end_us,
12463 text: text.into(),
12464 image: None,
12465 words: Vec::new(),
12466 karaoke: Vec::new(),
12467 };
12468 let mut words = subtitle_track();
12469 words.cues = vec![
12470 cue(0, 3_100_000, "first"),
12471 cue(3_100_000, 5_866_667, "second"),
12472 cue(5_866_667, 9_000_000, "third"),
12473 ];
12474 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12475 let s1 = p.add_lane(LaneKind::Subtitle);
12476 let sub = SubClip {
12477 start: 0,
12478 frames: 270,
12479 track: 0,
12480 in_us: 0,
12481 out_us: 9_000_000,
12482 link: None,
12483 };
12484 p.place_sub(s1, 0, sub).expect("placed");
12485 (p, s1)
12486 }
12487
12488 /// A cut over a span nothing lies in changes nothing: it costs no undo step,
12489 /// keeps the revision, and pushes nothing the batch counter would count.
12490 #[test]
12491 fn a_cut_over_an_empty_span_costs_no_step_and_keeps_the_revision() {
12492 let mut p = Project::single(FILE, 270);
12493 let empty = p.add_lane(LaneKind::Audio);
12494 let (depth, pushes, rev) = (p.history_len(), p.history_pushes(), p.revision());
12495 p.cut_regions(&[(10, 20)], &[empty]).expect("an empty lane is a legal scope");
12496 assert_eq!(p.history_len(), depth, "no undo step");
12497 assert_eq!(p.history_pushes(), pushes, "no snapshot counted");
12498 assert_eq!(p.revision(), rev, "same state, same revision");
12499 p.cut_regions(&[(400, 20)], &[Lane::V1, Lane::A1]).expect("a span past the last clip");
12500 assert_eq!(p.history_len(), depth, "still no undo step");
12501 assert_eq!(p.revision(), rev, "still the same revision");
12502 }
12503
12504 /// A cut that removes something still costs exactly one undo step and a new revision.
12505 #[test]
12506 fn a_real_cut_still_adds_one_step() {
12507 let mut p = Project::single(FILE, 270);
12508 let (depth, rev) = (p.history_len(), p.revision());
12509 p.cut_regions(&[(30, 30)], &[Lane::V1, Lane::A1]).expect("cut");
12510 assert_eq!(p.history_len(), depth + 1, "one undo step");
12511 assert_ne!(p.revision(), rev, "a new state");
12512 }
12513
12514 /// A no-op after the save leaves the saved revision in place, and undoing the
12515 /// real edit back to that save reads as the saved state again.
12516 #[test]
12517 fn undo_back_to_the_saved_point_clears_the_dot_after_a_no_op() {
12518 let mut p = Project::single(FILE, 270);
12519 let empty = p.add_lane(LaneKind::Audio);
12520 p.cut_regions(&[(30, 30)], &[Lane::V1, Lane::A1]).expect("cut");
12521 let saved = p.revision();
12522 p.cut_regions(&[(10, 20)], &[empty]).expect("empty span");
12523 assert_eq!(p.revision(), saved, "a no-op after the save leaves the dot clear");
12524 p.cut_regions(&[(100, 10)], &[Lane::V1, Lane::A1]).expect("a real cut");
12525 assert_ne!(p.revision(), saved, "the real cut moves off the saved state");
12526 assert!(p.undo());
12527 assert_eq!(p.revision(), saved, "undo back to the saved point clears the dot");
12528 }
12529
12530 /// The undo bookkeeping a no-op must leave exactly as it found it.
12531 fn undo_state(p: &Project) -> (usize, u64, usize, u64) {
12532 (p.history_len(), p.revision(), p.redo_len(), p.history_pushes())
12533 }
12534
12535 /// Mutators given arguments that change nothing (the value a setting already
12536 /// holds, an empty list, a move by 0) take no undo step, move no revision and
12537 /// keep the redo branch an edit would have cleared.
12538 #[test]
12539 fn no_op_mutators_leave_the_undo_state_alone() {
12540 let mut p = Project::single(FILE, 270);
12541 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12542 assert!(p.set_enabled(Lane::V1, 0, false));
12543 assert!(p.set_label(Lane::V1, 0, 2));
12544 assert!(p.set_clip_gain(Lane::A1, 0, -6.0));
12545 assert!(p.undo());
12546 let before = undo_state(&p);
12547 assert_eq!(before.2, 1, "the undone gain waits on the redo stack");
12548
12549 // Each call below sets a value the project already holds (or nothing).
12550 p.set_lane_gain_db(Lane::A1, -3.0);
12551 assert_eq!(undo_state(&p), before, "set_lane_gain_db");
12552 p.set_enabled(Lane::V1, 0, false);
12553 assert_eq!(undo_state(&p), before, "set_enabled");
12554 p.set_label(Lane::V1, 0, 2);
12555 assert_eq!(undo_state(&p), before, "set_label");
12556 p.set_clip_gain(Lane::A1, 0, 0.0);
12557 assert_eq!(undo_state(&p), before, "set_clip_gain");
12558 p.set_fade_in(Lane::V1, 0, 0);
12559 assert_eq!(undo_state(&p), before, "set_fade_in");
12560 p.set_fade_out(Lane::V1, 0, 0);
12561 assert_eq!(undo_state(&p), before, "set_fade_out");
12562 let _ = p.set_reverse(Lane::V1, 0, false);
12563 assert_eq!(undo_state(&p), before, "set_reverse");
12564 assert_eq!(p.slip(Lane::V1, 0, 0, SourceWalls::same(&[270])), Some(0));
12565 assert_eq!(undo_state(&p), before, "slip by 0");
12566 p.set_eq(Lane::A1, 0, None);
12567 assert_eq!(undo_state(&p), before, "set_eq");
12568 p.set_color_keys(Lane::V1, 0, Vec::new());
12569 assert_eq!(undo_state(&p), before, "set_color_keys");
12570 p.set_gain_keys(Lane::A1, 0, Vec::new());
12571 assert_eq!(undo_state(&p), before, "set_gain_keys");
12572 p.set_opacity_keys(Lane::V1, 0, Vec::new());
12573 assert_eq!(undo_state(&p), before, "set_opacity_keys");
12574 let _ = p.set_lane_name(Lane::A1, "");
12575 assert_eq!(undo_state(&p), before, "set_lane_name");
12576 p.clear_lane_duck(Lane::A1, 0);
12577 assert_eq!(undo_state(&p), before, "clear_lane_duck");
12578 p.remap_chapters(|f| f);
12579 assert_eq!(undo_state(&p), before, "remap_chapters");
12580 p.remap_markers(|f| f);
12581 assert_eq!(undo_state(&p), before, "remap_markers");
12582 p.add_subtitles_all(&[]);
12583 assert_eq!(undo_state(&p), before, "add_subtitles_all");
12584 p.relink_sources(&[]);
12585 assert_eq!(undo_state(&p), before, "relink_sources");
12586 let _ = p.cut_regions(&[(10, 0)], &[Lane::V1]);
12587 assert_eq!(undo_state(&p), before, "cut_regions of nothing");
12588
12589 // And the redo branch is still there to walk forward.
12590 let depth = p.history_len();
12591 assert!(p.redo(), "the gain comes back");
12592 assert_eq!(p.history_len(), depth + 1, "redo is one step forward");
12593 }
12594
12595 /// Real edits still cost exactly one undo step each, also right after a no-op.
12596 #[test]
12597 fn real_edits_still_add_exactly_one_step_after_no_ops() {
12598 let mut p = Project::single(FILE, 270);
12599 assert!(!p.set_enabled(Lane::V1, 0, true), "already on: nothing to do");
12600 let steps = p.history_len();
12601 let rev = p.revision();
12602 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12603 assert_eq!(p.history_len(), steps + 1, "one step for the gain");
12604 assert_ne!(p.revision(), rev, "a new state");
12605 assert!(p.set_enabled(Lane::V1, 0, false));
12606 assert_eq!(p.history_len(), steps + 2, "one step for the switch");
12607 assert!(p.set_label(Lane::V1, 0, 2));
12608 assert_eq!(p.history_len(), steps + 3, "one step for the label");
12609 assert!(p.set_clip_gain(Lane::A1, 0, -6.0));
12610 assert_eq!(p.history_len(), steps + 4, "one step for the clip gain");
12611 }
12612
12613 /// A no-op right after a real edit does not hide that edit from undo: one undo
12614 /// takes back the real edit, and nothing is left behind to undo next.
12615 #[test]
12616 fn undo_right_after_a_no_op_takes_back_the_real_edit() {
12617 let mut p = Project::single(FILE, 270);
12618 let start = p.revision();
12619 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12620 let edited = p.revision();
12621 p.set_lane_gain_db(Lane::A1, -3.0);
12622 assert_eq!(p.revision(), edited, "the no-op leaves the edited state's revision");
12623 assert!(p.undo());
12624 assert_eq!(p.revision(), start, "undo lands on the state before the edit");
12625 assert_eq!(p.history_len(), 0, "and no phantom step is left");
12626 assert!(!p.undo());
12627 }
12628
12629 /// A no-op between two edits leaves no step behind for the second to stack on.
12630 #[test]
12631 fn a_no_op_between_two_edits_is_not_a_step() {
12632 let mut p = Project::single(FILE, 270);
12633 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12634 p.set_lane_gain_db(Lane::A1, -3.0);
12635 assert!(p.set_enabled(Lane::V1, 0, false));
12636 assert_eq!(p.history_len(), 2, "the two edits, and no more");
12637 assert!(p.undo());
12638 assert!(p.undo());
12639 assert!(!p.undo(), "the no-op is gone for good");
12640 }
12641
12642 /// A no-op never destroys a redo branch: after an undo, a no-op keeps it, and
12643 /// redo still walks forward to the edit that was undone.
12644 #[test]
12645 fn a_no_op_after_undo_keeps_the_redo_branch() {
12646 let mut p = Project::single(FILE, 270);
12647 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12648 let edited = p.revision();
12649 assert!(p.undo());
12650 p.set_lane_gain_db(Lane::A1, 0.0);
12651 assert_eq!(p.redo_len(), 1, "the undone edit is still on the branch");
12652 assert!(p.redo());
12653 assert_eq!(p.revision(), edited, "redo walks back to the same state");
12654 }
12655
12656 /// Inside a batch a no-op adds no step, and a batch with a real edit and no-ops
12657 /// in it is one step.
12658 #[test]
12659 fn no_ops_inside_a_batch_add_no_step() {
12660 let mut p = Project::single(FILE, 270);
12661 let before = undo_state(&p);
12662 p.begin_batch();
12663 p.set_lane_gain_db(Lane::A1, 0.0);
12664 p.set_enabled(Lane::V1, 0, true);
12665 p.end_batch();
12666 assert_eq!(undo_state(&p), before, "an all-no-op batch is no step");
12667
12668 p.begin_batch();
12669 p.set_lane_gain_db(Lane::A1, 0.0);
12670 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12671 p.set_lane_gain_db(Lane::A1, -3.0);
12672 assert!(p.set_enabled(Lane::V1, 0, false));
12673 p.end_batch();
12674 assert_eq!(p.history_len(), before.0 + 1, "the batch is one step");
12675 assert!(p.undo());
12676 assert_eq!(p.revision(), before.1, "undo takes the whole batch back");
12677 assert!(!p.undo());
12678 }
12679
12680 /// At the cap a no-op neither evicts the oldest step nor loses it: the next real
12681 /// edit evicts it as it would have, and every step but that one can be undone.
12682 #[test]
12683 fn a_no_op_at_the_cap_keeps_every_step_it_should() {
12684 let mut p = Project::single(FILE, 400);
12685 for frame in 1..=HISTORY_CAP as u32 {
12686 assert!(p.split(frame));
12687 }
12688 let before = undo_state(&p);
12689 assert_eq!(before.0, HISTORY_CAP);
12690 p.set_enabled(Lane::V1, 0, true);
12691 assert_eq!(undo_state(&p), before, "a no-op at the cap");
12692 assert!(p.split(HISTORY_CAP as u32 + 1));
12693 assert_eq!(p.history_len(), HISTORY_CAP);
12694 let mut steps = 0;
12695 while p.undo() {
12696 steps += 1;
12697 }
12698 assert_eq!(steps, HISTORY_CAP, "every step but the evicted oldest one");
12699 }
12700
12701 /// The cues `s1` shows, as `(text, start_us, end_us)` in timeline order.
12702 fn shown_cues(p: &Project, s1: Lane) -> Vec<(String, i64, i64)> {
12703 p.sub_lane_cue_refs(s1, 30.0)
12704 .into_iter()
12705 .map(|(a, b, t, c)| (p.subtitles()[t].cues[c].text.clone(), a, b))
12706 .collect()
12707 }
12708
12709 /// A cut that covers a whole cue removes it: no zero-length copy, no
12710 /// duplicate, and the cues after it slide back. A cut that covers part of
12711 /// a cue trims it, and a cut spanning two cues trims both.
12712 #[test]
12713 fn a_cut_removes_or_trims_the_cues_it_covers() {
12714 let (mut p, s1) = three_cue_captions();
12715 p.cut_regions(&[(93, 83)], &[s1]).expect("cut the second sentence");
12716 let shown = shown_cues(&p, s1);
12717 assert_eq!(
12718 shown.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
12719 ["first", "third"],
12720 "the covered cue is gone, once: {shown:?}"
12721 );
12722 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12723 assert!((shown[1].1 - 3_100_000).abs() <= 3, "the third cue slides back to the cut: {shown:?}");
12724 assert!((shown[1].2 - shown[1].1 - 3_133_333).abs() <= 3, "third keeps its length: {shown:?}");
12725
12726 // Part of the second cue (frames 100..150) is cut out of the middle.
12727 let (mut p, s1) = three_cue_captions();
12728 p.cut_regions(&[(100, 50)], &[s1]).expect("cut inside the second cue");
12729 let shown = shown_cues(&p, s1);
12730 let total = |text: &str| -> i64 {
12731 shown.iter().filter(|c| c.0 == text).map(|c| c.2 - c.1).sum()
12732 };
12733 // "second" is one word: it keeps the longer side the cut leaves (5.0 s to 5.87 s, 0.87 s), once.
12734 assert!((total("second") - 866_667).abs() <= 3, "second keeps its longer side, once: {shown:?}");
12735 assert_eq!(shown.iter().filter(|c| c.0 == "second").count(), 1, "{shown:?}");
12736 assert!((total("first") - 3_100_000).abs() <= 3, "first is untouched: {shown:?}");
12737 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12738
12739 // A cut from inside the first cue to inside the second.
12740 let (mut p, s1) = three_cue_captions();
12741 p.cut_regions(&[(60, 60)], &[s1]).expect("cut across two cues");
12742 let shown = shown_cues(&p, s1);
12743 let total = |text: &str| -> i64 {
12744 shown.iter().filter(|c| c.0 == text).map(|c| c.2 - c.1).sum()
12745 };
12746 assert!((total("first") - 2_000_000).abs() <= 3, "first keeps its first two seconds: {shown:?}");
12747 assert!((total("second") - 1_866_667).abs() <= 3, "second keeps its last 1.87 s: {shown:?}");
12748 assert!((total("third") - 3_133_333).abs() <= 3, "third is untouched: {shown:?}");
12749 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12750 }
12751
12752 /// A sentence over one placement, nine seconds at 30 fps.
12753 fn sentence_captions() -> (Project, Lane) {
12754 let mut words = subtitle_track();
12755 words.cues = vec![crate::subtitle::Cue {
12756 start_us: 0,
12757 end_us: 9_000_000,
12758 text: "alpha beta gamma delta".into(),
12759 image: None,
12760 words: Vec::new(),
12761 karaoke: Vec::new(),
12762 }];
12763 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12764 let s1 = p.add_lane(LaneKind::Subtitle);
12765 let sub = SubClip { start: 0, frames: 270, track: 0, in_us: 0, out_us: 9_000_000, link: None };
12766 p.place_sub(s1, 0, sub).expect("placed");
12767 (p, s1)
12768 }
12769
12770 /// Cutting the middle of a sentence keeps the words either side of the cut
12771 /// and drops the ones inside it: "beta gamma" lies in frames 90..180 (3 s
12772 /// to 6 s), so only "alpha" and "delta" are left to show. Undo brings the
12773 /// one sentence back as it was.
12774 #[test]
12775 fn a_cut_through_a_sentence_drops_the_words_inside_it() {
12776 let (mut p, s1) = sentence_captions();
12777 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12778 let shown: Vec<String> = shown_cues(&p, s1).into_iter().map(|c| c.0).collect();
12779 assert_eq!(shown, ["alpha", "delta"], "the cut words are gone and the rest stays");
12780
12781 assert!(p.undo(), "the cut is one undo step");
12782 assert_eq!(p.subtitles()[0].cues.len(), 1, "undo restores the one cue");
12783 assert_eq!(p.subtitles()[0].cues[0].text, "alpha beta gamma delta");
12784 }
12785
12786 /// A ripple delete over the same span splits the same way, and so does a
12787 /// split at a point inside a sentence, which divides the words once.
12788 #[test]
12789 fn a_ripple_delete_and_a_split_divide_the_words_too() {
12790 let (mut p, s1) = sentence_captions();
12791 assert!(p.ripple_delete(90, 90));
12792 let shown: Vec<String> = shown_cues(&p, s1).into_iter().map(|c| c.0).collect();
12793 assert_eq!(shown, ["alpha", "delta"], "{shown:?}");
12794
12795 let (mut p, _) = sentence_captions();
12796 assert!(p.split(150), "a frame inside the sentence splits it");
12797 let texts: Vec<String> = p.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
12798 assert_eq!(texts, ["alpha beta", "gamma delta"], "a split at the half divides the words");
12799 }
12800
12801 /// `split_cues_at` divides the cue at the word boundary nearest the point,
12802 /// keeps every piece's time inside the cue, and is one undo step. Where no
12803 /// cue straddles the point it changes nothing and takes no step.
12804 #[test]
12805 fn split_cues_at_divides_the_words_and_is_one_undo_step() {
12806 let (mut p, _) = sentence_captions();
12807 assert!(!p.split_cues_at(0, 0), "a point at the cue's start splits nothing");
12808 assert!(p.split_cues_at(0, 2_250_000));
12809 let cues: Vec<(String, i64, i64)> =
12810 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12811 assert_eq!(
12812 cues,
12813 [("alpha".to_string(), 0, 2_250_000), ("beta gamma delta".to_string(), 2_250_000, 9_000_000)],
12814 "the pieces meet at the point and keep the words either side"
12815 );
12816 assert!(p.undo());
12817 assert_eq!(p.subtitles()[0].cues.len(), 1, "undo restores the sentence");
12818
12819 // "second" is one word: it stays whole on the longer side of 4 s (the tail, 4 s to 5.87 s).
12820 let (mut p, _) = three_cue_captions();
12821 assert!(p.split_cues_at(0, 4_000_000));
12822 let cues: Vec<(String, i64, i64)> =
12823 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12824 assert_eq!(cues.len(), 3, "a one-word cue is not duplicated: {cues:?}");
12825 assert_eq!(cues[1], ("second".to_string(), 4_000_000, 5_866_667));
12826 }
12827
12828 /// A cue with one word cut by an edge keeps its text on the longer piece only
12829 /// (ties: the piece before the edge), so the word is never shown twice.
12830 #[test]
12831 fn a_one_word_cue_cut_by_an_edge_keeps_its_text_on_one_piece() {
12832 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() };
12833 let before = cue(0, 4_000_000);
12834 assert_eq!(
12835 split_words(&before, 3_000_000),
12836 Some(vec![(0, 3_000_000, "Onewordcue".to_string())]),
12837 "the longer piece before the edge keeps the word"
12838 );
12839 assert_eq!(
12840 split_words(&cue(0, 4_000_000), 1_000_000),
12841 Some(vec![(1_000_000, 4_000_000, "Onewordcue".to_string())]),
12842 "the longer piece after the edge keeps the word"
12843 );
12844 assert_eq!(
12845 split_words(&cue(0, 4_000_000), 2_000_000),
12846 Some(vec![(0, 2_000_000, "Onewordcue".to_string())]),
12847 "a tie keeps the word on the piece before"
12848 );
12849 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);
12850 }
12851
12852 /// A cut through a one-word caption ("first", 0 to 3.1 s) at 2 s keeps the
12853 /// word on the longer piece before the cut, and no piece after it shows it.
12854 #[test]
12855 fn a_cut_through_a_one_word_caption_shows_it_once() {
12856 let (mut p, _) = three_cue_captions();
12857 assert!(p.split_cues_at(0, 2_000_000));
12858 let cues: Vec<(String, i64, i64)> =
12859 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12860 assert_eq!(cues[0], ("first".to_string(), 0, 2_000_000), "{cues:?}");
12861 assert_eq!(cues.iter().filter(|c| c.0 == "first").count(), 1, "one copy of the word: {cues:?}");
12862 }
12863
12864 /// Divided cues are written by a save as cue edits and cue adds, so a reopen
12865 /// of the saved project shows the same words, not the sentence it began as.
12866 #[test]
12867 fn divided_cues_survive_a_save_and_reopen() {
12868 let (mut p, s1) = sentence_captions();
12869 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12870 let edits = p.cue_edits().to_vec();
12871 let adds = p.cue_adds().to_vec();
12872 let mut words = subtitle_track();
12873 words.cues = vec![crate::subtitle::Cue {
12874 start_us: 0,
12875 end_us: 9_000_000,
12876 text: "alpha beta gamma delta".into(),
12877 image: None,
12878 words: Vec::new(),
12879 karaoke: Vec::new(),
12880 }];
12881 let reopened = Project::single(FILE, 270)
12882 .with_subtitles(vec![words])
12883 .with_cue_edits(&edits)
12884 .with_cue_adds(&adds);
12885 let texts = |p: &Project| -> Vec<(String, i64, i64)> {
12886 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect()
12887 };
12888 assert_eq!(texts(&reopened), texts(&p), "the reopened cues are the divided ones");
12889 }
12890
12891 /// The rippling delete is the same cut on every lane, so it must leave the
12892 /// same captions as the scoped one: no covered cue survives it either.
12893 #[test]
12894 fn a_ripple_delete_over_a_cue_leaves_no_copy_of_it() {
12895 let (mut p, s1) = three_cue_captions();
12896 assert!(p.ripple_delete(93, 83));
12897 let shown = shown_cues(&p, s1);
12898 assert_eq!(
12899 shown.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
12900 ["first", "third"],
12901 "{shown:?}"
12902 );
12903 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12904 }
12905
12906 /// How many of track `track`'s cues some placement window overlaps: a cue no
12907 /// window overlaps is an orphan, one nothing on the timeline can show.
12908 fn placed_cues_of(p: &Project, track: usize) -> usize {
12909 let windows: Vec<(i64, i64)> = p
12910 .lanes
12911 .iter()
12912 .flat_map(|l| l.subs.iter())
12913 .filter(|s| s.track == track)
12914 .map(|s| (s.in_us, s.out_us))
12915 .collect();
12916 p.subtitles()[track]
12917 .cues
12918 .iter()
12919 .filter(|c| windows.iter().any(|&(a, b)| c.start_us < b && a < c.end_us))
12920 .count()
12921 }
12922
12923 /// A cut through a sentence leaves no orphan. "beta gamma" lies in the cut,
12924 /// so it is removed with its words: the track keeps only "alpha" and
12925 /// "delta", and each is under the placement window that is left.
12926 #[test]
12927 fn a_cut_through_a_sentence_leaves_no_orphan_piece() {
12928 let (mut p, s1) = sentence_captions();
12929 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12930 let texts: Vec<String> = p.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
12931 assert_eq!(texts, ["alpha", "delta"], "the removed middle is not a cue: {texts:?}");
12932 assert_eq!(placed_cues_of(&p, 0), 2, "every cue is under a window");
12933 }
12934
12935 /// A cut that ends inside a one-word cue keeps the part the timeline still
12936 /// shows. "Over" runs 1.0 s to 1.7 s; cutting frames 1.0 s to 1.5 s leaves
12937 /// 1.5 s to 1.7 s on the timeline, so that is the cue that stays, with its
12938 /// word. The removed 1.0 s to 1.5 s piece is dropped.
12939 #[test]
12940 fn a_cut_ending_in_a_one_word_cue_keeps_the_visible_part() {
12941 let mut words = subtitle_track();
12942 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() }];
12943 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12944 let s1 = p.add_lane(LaneKind::Subtitle);
12945 // The file's 1 s to 4 s, played from timeline frame 30 (1.0 s) for 90 frames.
12946 let sub = SubClip { start: 30, frames: 90, track: 0, in_us: 1_000_000, out_us: 4_000_000, link: None };
12947 p.place_sub(s1, 30, sub).expect("placed");
12948 p.cut_regions(&[(30, 15)], &[s1]).expect("cut 1.0 s to 1.5 s");
12949 let cues: Vec<(String, i64, i64)> =
12950 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12951 assert_eq!(cues, [("Over".to_string(), 1_500_000, 1_700_000)], "{cues:?}");
12952 let shown = shown_cues(&p, s1);
12953 assert_eq!(shown.len(), 1, "{shown:?}");
12954 assert_eq!(shown[0].0, "Over");
12955 assert!((shown[0].1 - 1_000_000).abs() <= 3, "the word now starts where the cut ended: {shown:?}");
12956 assert!((shown[0].2 - 1_200_000).abs() <= 3, "and keeps its 0.2 s: {shown:?}");
12957 }
12958
12959 /// Three cuts in a row over a captioned timeline keep the track to the cues
12960 /// the placement shows: after each one every cue is under a window, so the
12961 /// cue count is the placed count.
12962 #[test]
12963 fn three_cuts_keep_the_cue_count_at_the_placed_count() {
12964 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() };
12965 let mut words = subtitle_track();
12966 words.cues = vec![
12967 cue(0, 1_900_000, "a b"),
12968 cue(1_900_000, 4_200_000, "c d e"),
12969 cue(4_200_000, 6_000_000, "f g"),
12970 cue(6_000_000, 8_100_000, "h i j"),
12971 cue(8_100_000, 10_000_000, "k l"),
12972 cue(10_000_000, 12_000_000, "m n"),
12973 ];
12974 let mut p = Project::single(FILE, 360).with_subtitles(vec![words]);
12975 let s1 = p.add_lane(LaneKind::Subtitle);
12976 let sub = SubClip { start: 0, frames: 360, track: 0, in_us: 0, out_us: 12_000_000, link: None };
12977 p.place_sub(s1, 0, sub).expect("placed");
12978 assert_eq!(placed_cues_of(&p, 0), 6);
12979 for (at, len) in [(45, 20), (100, 30), (200, 25)] {
12980 p.cut_regions(&[(at, len)], &[s1]).expect("cut");
12981 let total = p.subtitles()[0].cues.len();
12982 assert_eq!(placed_cues_of(&p, 0), total, "every cue is under a window after a cut: {total} cues");
12983 }
12984 }
12985
12986 /// A cue no placement ever covered is not the cut's to remove. A caption
12987 /// placed over the first part of its track leaves the rest of the cues in
12988 /// the track, so a cut through the placed part keeps them for later.
12989 #[test]
12990 fn a_cue_no_placement_covers_survives_a_cut() {
12991 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() };
12992 let mut words = subtitle_track();
12993 words.cues = vec![cue(0, 2_000_000, "x y"), cue(5_000_000, 7_000_000, "z w")];
12994 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12995 let s1 = p.add_lane(LaneKind::Subtitle);
12996 // Only the first two seconds are placed.
12997 let sub = SubClip { start: 0, frames: 60, track: 0, in_us: 0, out_us: 2_000_000, link: None };
12998 p.place_sub(s1, 0, sub).expect("placed");
12999 p.cut_regions(&[(30, 15)], &[s1]).expect("cut inside the placed part");
13000 let kept = p.subtitles()[0]
13001 .cues
13002 .iter()
13003 .filter(|c| c.text == "z w" && c.start_us == 5_000_000 && c.end_us == 7_000_000)
13004 .count();
13005 assert_eq!(kept, 1, "the unplaced cue stays in the track: {:?}", p.subtitles()[0].cues);
13006 }
13007
13008 /// A caption placement for pure timeline tests: the track window is the
13009 /// same duration as the placement, so assertions can stay in frames.
13010 fn caption(start: u32, frames: u32) -> SubClip {
13011 SubClip {
13012 start,
13013 frames,
13014 track: 0,
13015 in_us: 0,
13016 out_us: i64::from(frames) * 1_000_000,
13017 link: None,
13018 }
13019 }
13020
13021 /// A language retype is one undo step, refused (with no step) for a track
13022 /// that is not there or that already reads it, and a load puts a saved
13023 /// language back over the file's own.
13024 #[test]
13025 fn a_subtitle_language_is_one_undo_step_and_a_load_puts_it_back() {
13026 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track()]);
13027 assert!(p.set_subtitle_language(0, "fra"));
13028 assert_eq!(p.subtitles()[0].language, "fra");
13029 assert!(!p.set_subtitle_language(0, "fra"), "it already reads that: no step");
13030 assert!(!p.set_subtitle_language(5, "fra"), "no such track");
13031 assert!(p.undo());
13032 assert_eq!(p.subtitles()[0].language, "eng", "one step takes it back");
13033
13034 let back = Project::single(FILE, 300)
13035 .with_subtitles(vec![subtitle_track()])
13036 .with_sub_langs(&[(0, "deu".to_string()), (9, "xxx".to_string())]);
13037 assert_eq!(back.subtitles()[0].language, "deu");
13038 }
13039
13040 /// A subtitle palette row for tests that place captions on lanes.
13041 fn subtitle_track() -> SubtitleTrack {
13042 SubtitleTrack {
13043 path: FILE.into(),
13044 track: None,
13045 language: "eng".into(),
13046 name: String::new(),
13047 label: "eng".into(),
13048 cues: Vec::new(),
13049 bitmap: false,
13050 refused: None,
13051 }
13052 }
13053
13054 /// A retyped cue is the track's words, so every placement of that track
13055 /// shows it; a retype that changes nothing, or names no cue, costs no undo
13056 /// step; one undo takes the words and the save list back together; and a
13057 /// removed row's overrides go with it while the others keep their place.
13058 #[test]
13059 fn a_cue_is_trimmed_moved_and_merged_inside_its_neighbours_one_undo_step_each() {
13060 let (mut p, s1) = three_cue_captions();
13061 let times = |p: &Project| -> Vec<(i64, i64)> {
13062 p.subtitles()[0].cues.iter().map(|c| (c.start_us, c.end_us)).collect()
13063 };
13064 assert_eq!(p.cue_room(0, 1), Some((3_100_000, 5_866_667)));
13065 assert!(p.set_cue_times(0, 1, 3_100_000, 5_866_667).is_ok_and(|changed| !changed), "same times, no edit");
13066 assert!(p.set_cue_times(0, 1, 3_000_000, 5_000_000).is_err(), "into the cue before");
13067 assert!(p.set_cue_times(0, 1, 3_100_000, 6_000_000).is_err(), "into the cue after");
13068 assert!(p.set_cue_times(0, 1, 3_100_000, 3_150_000).is_err(), "too short");
13069 assert!(matches!(p.set_cue_times(0, 1, 3_500_000, 5_000_000), Ok(true)));
13070 assert_eq!(times(&p)[1], (3_500_000, 5_000_000));
13071 assert_eq!(p.subtitles()[0].cues[1].text, "second");
13072 assert_eq!(
13073 shown_cues(&p, s1)[1],
13074 ("second".to_string(), 3_500_000, 5_000_000),
13075 "the timeline shows the moved cue"
13076 );
13077 // The file cue leaves and its new times are an added cue: a save keeps both.
13078 assert_eq!(p.cue_adds().len(), 1);
13079 assert!(p.cue_edits().iter().any(|(_, _, t)| t.is_empty()));
13080 // A second trim of the same (now added) cue stays one added entry.
13081 assert!(matches!(p.set_cue_times(0, 1, 3_400_000, 5_000_000), Ok(true)));
13082 assert_eq!(p.cue_adds().len(), 1);
13083 assert_eq!(p.cue_adds()[0].start_us, 3_400_000);
13084
13085 assert_eq!(p.cue_track_us_at(s1, 0, 1, 4_000_000, 30.0), Some(4_000_000));
13086
13087 assert!(p.merge_cue_next(2, 0).is_err(), "no such track");
13088 assert!(p.merge_cue_next(0, 2).is_err(), "nothing after the last");
13089 assert!(p.merge_cue_next(0, 0).is_ok());
13090 assert_eq!(p.subtitles()[0].cues.len(), 2);
13091 assert_eq!(p.subtitles()[0].cues[0].text, "first second");
13092 assert_eq!(times(&p)[0], (0, 5_000_000));
13093
13094 assert!(p.undo(), "the merge goes");
13095 assert_eq!(p.subtitles()[0].cues.len(), 3);
13096 assert!(p.undo(), "the second trim goes");
13097 assert_eq!(times(&p)[1], (3_500_000, 5_000_000));
13098 assert!(p.undo(), "the first trim goes");
13099 assert_eq!(times(&p)[1], (3_100_000, 5_866_667));
13100 assert!(p.cue_adds().is_empty() && p.cue_edits().is_empty());
13101 }
13102
13103 #[test]
13104 fn a_retyped_cue_is_the_tracks_words_and_one_undo_step() {
13105 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
13106 start_us,
13107 end_us,
13108 text: text.into(),
13109 image: None,
13110 words: Vec::new(),
13111 karaoke: Vec::new(),
13112 };
13113 let mut words = subtitle_track();
13114 words.cues = vec![cue(0, 1_000_000, "one"), cue(2_000_000, 3_000_000, "two")];
13115 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), words]);
13116 let s1 = p.add_lane(LaneKind::Subtitle);
13117 // A window of the track's first three seconds, played over three: one
13118 // timeline second is one of the file's, so the cues land where they are.
13119 for at in [0, 100] {
13120 let sub = SubClip {
13121 start: at,
13122 frames: 90,
13123 track: 1,
13124 in_us: 0,
13125 out_us: 3_000_000,
13126 link: None,
13127 };
13128 p.place_sub(s1, at, sub).expect("placed");
13129 }
13130 let texts = |p: &Project| -> Vec<String> {
13131 p.sub_lane_cues(s1, 30.0)
13132 .into_iter()
13133 .map(|c| c.text)
13134 .collect()
13135 };
13136 assert_eq!(texts(&p), ["one", "two", "one", "two"]);
13137
13138 assert!(!p.set_cue_text(1, 0, "one"), "the same words are no edit");
13139 assert!(!p.set_cue_text(1, 9, "x"), "a cue that is not there");
13140 assert!(!p.set_cue_text(7, 0, "x"), "a track that is not there");
13141 assert!(p.set_cue_text(1, 1, "TWO\nlines"));
13142 assert_eq!(
13143 texts(&p),
13144 ["one", "TWO\nlines", "one", "TWO\nlines"],
13145 "both placements show the retyped words"
13146 );
13147 assert_eq!(p.cue_edits(), [(1, 1, "TWO\nlines".to_string())]);
13148
13149 let refs = p.sub_lane_cue_refs(s1, 30.0);
13150 let drawn = p.sub_lane_cues(s1, 30.0);
13151 assert_eq!(refs.len(), drawn.len(), "one ref for each cue drawn");
13152 for (&(start, end, track, cue_idx), c) in refs.iter().zip(&drawn) {
13153 assert_eq!((start, end), (c.start_us, c.end_us));
13154 assert_eq!(p.subtitles()[track].cues[cue_idx].text, c.text);
13155 }
13156
13157 assert!(p.undo(), "one step back");
13158 assert_eq!(texts(&p), ["one", "two", "one", "two"]);
13159 assert!(
13160 p.cue_edits().is_empty(),
13161 "the save list goes back with the words"
13162 );
13163 assert!(p.redo());
13164 assert_eq!(texts(&p)[1], "TWO\nlines");
13165
13166 // The row above the edited one comes off: the edit moves down with its
13167 // track, and still names the cue it changed.
13168 p.remove_subtitles(0).expect("nothing is placed on it");
13169 assert_eq!(p.cue_edits(), [(0, 1, "TWO\nlines".to_string())]);
13170 assert_eq!(texts(&p)[1], "TWO\nlines");
13171 }
13172
13173 /// A deleted cue is gone from every placement of its track, and no placement
13174 /// moves. Deleting cue 1 and then cue 0 (by the indices a listing shows
13175 /// after each) leaves the file's third cue; a retype after the deletes lands
13176 /// on that cue's file index; and a reload of the same file, with the saved
13177 /// overrides put back, shows exactly what the session showed.
13178 #[test]
13179 fn a_deleted_cue_leaves_the_track_and_survives_a_reload() {
13180 let file_words = || {
13181 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
13182 start_us,
13183 end_us,
13184 text: text.into(),
13185 image: None,
13186 words: Vec::new(),
13187 karaoke: Vec::new(),
13188 };
13189 let mut words = subtitle_track();
13190 words.cues = vec![
13191 cue(0, 1_000_000, "one"),
13192 cue(2_000_000, 3_000_000, "two"),
13193 cue(4_000_000, 5_000_000, "three"),
13194 ];
13195 words
13196 };
13197 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), file_words()]);
13198 let s1 = p.add_lane(LaneKind::Subtitle);
13199 let sub = SubClip { start: 0, frames: 150, track: 1, in_us: 0, out_us: 5_000_000, link: None };
13200 p.place_sub(s1, 0, sub).expect("placed");
13201 let texts = |p: &Project| -> Vec<String> {
13202 p.sub_lane_cues(s1, 30.0).into_iter().map(|c| c.text).collect()
13203 };
13204 assert_eq!(texts(&p), ["one", "two", "three"]);
13205
13206 assert!(p.delete_cue(1, 1), "cue 1 (\"two\") goes");
13207 assert!(!p.delete_cue(1, 9), "a cue that is not there");
13208 assert_eq!(texts(&p), ["one", "three"]);
13209 assert_eq!((p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].frames), (0, 150), "nothing moves");
13210 assert_eq!(p.cue_edits(), [(1, 1, String::new())]);
13211
13212 // Cue 1 is now "three"; its file index is 2, which the save names.
13213 assert!(p.set_cue_text(1, 1, "THREE"));
13214 assert_eq!(texts(&p), ["one", "THREE"]);
13215 assert_eq!(p.cue_edits(), [(1, 1, String::new()), (1, 2, "THREE".to_string())]);
13216
13217 // Empty text is a removal, not a blank cue: "one" goes.
13218 assert!(p.set_cue_text(1, 0, ""));
13219 assert_eq!(texts(&p), ["THREE"]);
13220 assert_eq!(
13221 p.cue_edits(),
13222 [(1, 1, String::new()), (1, 2, "THREE".to_string()), (1, 0, String::new())]
13223 );
13224
13225 // A reload: the file's three cues, the saved overrides put back.
13226 let saved = p.cue_edits().to_vec();
13227 let mut reopened =
13228 Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), file_words()]).with_cue_edits(&saved);
13229 let s1r = reopened.add_lane(LaneKind::Subtitle);
13230 reopened.place_sub(s1r, 0, SubClip { start: 0, frames: 150, track: 1, in_us: 0, out_us: 5_000_000, link: None }).expect("placed");
13231 let got: Vec<String> = reopened.sub_lane_cues(s1r, 30.0).into_iter().map(|c| c.text).collect();
13232 assert_eq!(got, ["THREE"], "the reload shows what the session did");
13233 assert_eq!(reopened.cue_edits(), saved.as_slice(), "and saves the same list");
13234
13235 // Undo takes back the last removal, then the retype, then the first removal.
13236 assert!(p.undo());
13237 assert_eq!(texts(&p), ["one", "THREE"]);
13238 assert!(p.undo());
13239 assert_eq!(texts(&p), ["one", "three"]);
13240 assert!(p.undo());
13241 assert_eq!(texts(&p), ["one", "two", "three"]);
13242 }
13243
13244 /// A cue a window edge shortened to under [`CUT_SLIVER_FRAMES`] is no cue;
13245 /// a cue that was short in the file, and whole, stays one.
13246 #[test]
13247 fn a_cut_sliver_under_four_frames_is_dropped_and_a_short_cue_is_not() {
13248 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
13249 start_us,
13250 end_us,
13251 text: text.into(),
13252 image: None,
13253 words: Vec::new(),
13254 karaoke: Vec::new(),
13255 };
13256 let mut words = subtitle_track();
13257 words.cues = vec![
13258 cue(0, 1_000_000, "whole"),
13259 // Shortened by the window's end at 1.1 s: 0.1 s, three frames.
13260 cue(1_000_000, 2_000_000, "edge"),
13261 // Two frames long in the file itself, inside the window.
13262 cue(1_000_000, 1_066_667, "born"),
13263 ];
13264 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), words]);
13265 let s1 = p.add_lane(LaneKind::Subtitle);
13266 let sub = SubClip { start: 0, frames: 33, track: 1, in_us: 0, out_us: 1_100_000, link: None };
13267 p.place_sub(s1, 0, sub).expect("placed");
13268 let shown: Vec<String> = p.sub_lane_cues(s1, 30.0).into_iter().map(|c| c.text).collect();
13269 assert_eq!(shown, ["whole", "born"], "the three-frame edge is no cue: {shown:?}");
13270 }
13271
13272 /// A recognisable equalizer setting: one peak band, `n` telling two of them
13273 /// apart -- which is what makes the table's dedup and its prune visible.
13274 fn band_at(n: u32) -> EqParams {
13275 EqParams {
13276 bands: vec![crate::eq::Band {
13277 freq_hz: 1000.0,
13278 gain_db: f64::from(n) as f32 * 1.5,
13279 q: 0.707,
13280 kind: crate::eq::BandKind::Peak,
13281 }],
13282 }
13283 }
13284
13285 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
13286 /// for the colour table.
13287 fn grade_at(n: u32) -> ColorParams {
13288 ColorParams {
13289 brightness: f64::from(n) as f32 * 0.05,
13290 ..Default::default()
13291 }
13292 }
13293
13294 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
13295 /// twin for the transform table.
13296 fn transform_at(n: u32) -> TransformParams {
13297 TransformParams {
13298 pos_x: f64::from(n) as f32 * 0.05,
13299 ..Default::default()
13300 }
13301 }
13302
13303 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
13304 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
13305 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
13306 }
13307
13308 /// Every lane with its group ids blanked, for comparing shape.
13309 fn shape(p: &Project) -> Vec<Vec<Clip>> {
13310 p.lanes()
13311 .into_iter()
13312 .map(|l| {
13313 p.lane(l)
13314 .iter()
13315 .map(|c| Clip {
13316 link: None,
13317 ..c.clone()
13318 })
13319 .collect()
13320 })
13321 .collect()
13322 }
13323
13324 /// The *source frame* every timeline frame reads, per lane -- the traversal
13325 /// a player performs. Deliberately not the clip index: a split changes which
13326 /// clip a frame belongs to, and nothing else.
13327 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
13328 (0..p.timeline_frames() + 2)
13329 .map(|f| {
13330 p.lanes()
13331 .into_iter()
13332 .map(|l| p.map(l, f).map(|(_, source)| source))
13333 .collect()
13334 })
13335 .collect()
13336 }
13337
13338 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
13339 /// fixture. Built through `split` so the constructor path is exercised too.
13340 fn three() -> Project {
13341 let mut p = Project::single(FILE, 9);
13342 assert!(p.split(3));
13343 assert!(p.split(5));
13344 assert_eq!(
13345 shape(&p),
13346 [
13347 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
13348 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
13349 ]
13350 );
13351 p
13352 }
13353
13354 #[test]
13355 fn single_is_the_whole_file_on_both_lanes() {
13356 let p = Project::single(FILE, 150);
13357 assert_eq!(p.clips().len(), 1);
13358 assert_eq!(p.lane(Lane::A1).len(), 1);
13359 assert_eq!(p.timeline_frames(), 150);
13360 assert_eq!(p.clip_spans(), vec![(0, 150)]);
13361 // grouped: video and audio carry the same link
13362 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
13363 assert!(p.clips()[0].link.is_some());
13364 // degenerate mapping: timeline == source
13365 assert_eq!(p.map_timeline(0), Some((0, 0)));
13366 assert_eq!(p.map_timeline(149), Some((0, 149)));
13367 assert_eq!(p.map_timeline(150), None);
13368 // never-empty invariant survives a bogus frame count
13369 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
13370 }
13371
13372 #[test]
13373 fn split_cuts_every_lane_and_regroups_it_back() {
13374 let mut p = Project::single(FILE, 9);
13375 let before = traversal(&p);
13376 let before_shape = shape(&p);
13377
13378 assert!(p.split(4));
13379 for l in p.lanes() {
13380 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
13381 }
13382 // The two sides are two groups, one per side, matching across the lanes.
13383 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
13384 assert_eq!(v[0].link, a[0].link);
13385 assert_eq!(v[1].link, a[1].link);
13386 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
13387 // A split changes no mapping, in either lane.
13388 assert_eq!(traversal(&p), before, "a split moves nothing");
13389
13390 assert!(p.regroup(4), "the inverse rejoins them");
13391 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
13392 assert_eq!(traversal(&p), before);
13393 assert_eq!(
13394 p.lane(Lane::V1)[0].link,
13395 p.lane(Lane::A1)[0].link,
13396 "and the rejoined clip is one group again"
13397 );
13398 }
13399
13400 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
13401 /// the very first frame of a fade-in, unity at its last, equal-power
13402 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
13403 /// at all.
13404 #[test]
13405 fn clip_gain_set_clamps_refuses_and_undoes() {
13406 let mut p = Project::single(FILE, 150);
13407 let a1 = Lane::new(LaneKind::Audio, 0);
13408 assert_eq!(p.clip_gain(a1, 0), Some(0.0));
13409 assert!(p.set_clip_gain(a1, 0, -6.0));
13410 assert_eq!(p.clip_gain(a1, 0), Some(-6.0));
13411 assert!(p.set_clip_gain(a1, 0, -100.0));
13412 assert_eq!(p.clip_gain(a1, 0), Some(-60.0), "clamped to the floor");
13413 assert!(!p.set_clip_gain(a1, 0, -60.0), "the same value is no step");
13414 assert!(!p.set_clip_gain(a1, 0, f32::NAN), "not finite");
13415 assert!(
13416 !p.set_clip_gain(Lane::V1, 0, -3.0),
13417 "a video clip takes no gain"
13418 );
13419 assert!(!p.set_clip_gain(a1, 5, -3.0), "no clip there");
13420 assert!(p.set_clip_gain(a1, 0, 30.0));
13421 assert_eq!(p.clip_gain(a1, 0), Some(24.0), "clamped to the ceiling");
13422 assert!(p.undo());
13423 assert_eq!(p.clip_gain(a1, 0), Some(-60.0));
13424 assert!(p.undo());
13425 assert_eq!(p.clip_gain(a1, 0), Some(-6.0));
13426 assert!(p.undo());
13427 assert_eq!(p.clip_gain(a1, 0), Some(0.0));
13428 }
13429
13430 #[test]
13431 fn gain_rides_the_envelope_and_a_split_carries_it_to_both_halves() {
13432 let mut p = Project::single(FILE, 150);
13433 let a1 = Lane::new(LaneKind::Audio, 0);
13434 assert!(p.set_clip_gain(a1, 0, -6.0));
13435 let fade = p.audio_fades_from(0, 30.0)[0][0]
13436 .clone()
13437 .expect("a gained clip has an envelope");
13438 assert!((fade.gain - 0.5012).abs() < 1e-3, "-6 dB is a linear 0.501");
13439 assert!(
13440 (fade.gain_at(75) - fade.gain).abs() < 1e-6,
13441 "no ramps: the gain alone"
13442 );
13443 assert!(p.split(60));
13444 assert_eq!(p.lane(a1).len(), 2);
13445 for c in p.lane(a1) {
13446 assert_eq!(c.gain_db, -6.0, "both halves keep the gain");
13447 }
13448 }
13449
13450 #[test]
13451 fn gain_envelope_is_linear_in_db_and_holds_at_both_ends() {
13452 let keys = [GainKey::new(10, -12.0), GainKey::new(20, 0.0)];
13453 assert_eq!(
13454 gain_keys_db_at(&keys, 15.0),
13455 -6.0,
13456 "the midpoint is the midpoint of the dB"
13457 );
13458 assert_eq!(gain_keys_db_at(&keys, 10.0), -12.0, "exact at a point");
13459 assert_eq!(gain_keys_db_at(&keys, 20.0), 0.0, "exact at the last point");
13460 assert_eq!(
13461 gain_keys_db_at(&keys, 0.0),
13462 -12.0,
13463 "held before the first point"
13464 );
13465 assert_eq!(
13466 gain_keys_db_at(&keys, 99.0),
13467 0.0,
13468 "held after the last point"
13469 );
13470 assert_eq!(gain_keys_db_at(&[], 5.0), 0.0, "no points is unity");
13471 let three = [
13472 GainKey::new(0, 0.0),
13473 GainKey::new(10, -20.0),
13474 GainKey::new(30, -20.0),
13475 ];
13476 assert_eq!(gain_keys_db_at(&three, 5.0), -10.0);
13477 assert_eq!(
13478 gain_keys_db_at(&three, 20.0),
13479 -20.0,
13480 "a flat run stays flat"
13481 );
13482 }
13483
13484 #[test]
13485 fn gain_keys_are_sorted_clamped_capped_and_refused_where_they_must_be() {
13486 let mut p = Project::single(FILE, 150);
13487 let a1 = Lane::new(LaneKind::Audio, 0);
13488 assert!(p.set_gain_keys(
13489 a1,
13490 0,
13491 vec![GainKey::new(30, -20.0), GainKey::new(0, 0.0)]
13492 ));
13493 assert_eq!(
13494 p.gain_keys_of(a1, 0),
13495 &[GainKey::new(0, 0.0), GainKey::new(30, -20.0)],
13496 "sorted by source frame"
13497 );
13498 assert!(
13499 !p.set_gain_keys(
13500 a1,
13501 0,
13502 vec![GainKey::new(5, 1.0), GainKey::new(5, 2.0)]
13503 ),
13504 "two points at one source frame are refused"
13505 );
13506 assert!(
13507 !p.set_gain_keys(Lane::V1, 0, vec![GainKey::new(0, 0.0)]),
13508 "a video clip takes no envelope"
13509 );
13510 assert!(!p.set_gain_keys(a1, 9, Vec::new()), "no such clip");
13511 assert!(p.set_gain_keys(a1, 0, vec![GainKey::new(0, 100.0)]));
13512 assert_eq!(p.gain_keys_of(a1, 0)[0].db, MAX_CLIP_GAIN_DB, "clamped");
13513 assert!(
13514 !p.set_gain_keys(a1, 0, vec![GainKey::new(0, 100.0)]),
13515 "an envelope already exactly so changes nothing, and costs no undo"
13516 );
13517 assert!(!p.set_gain_keys(
13518 a1,
13519 0,
13520 vec![GainKey::new(0, f32::NAN)]
13521 ));
13522 let over: Vec<GainKey> = (0..=MAX_GAIN_KEYS as u32)
13523 .map(|at| GainKey::new(at, 0.0))
13524 .collect();
13525 assert!(!p.set_gain_keys(a1, 0, over), "257 points is over the cap");
13526 let full: Vec<GainKey> = (0..MAX_GAIN_KEYS as u32)
13527 .map(|at| GainKey::new(at, 0.0))
13528 .collect();
13529 assert!(p.set_gain_keys(a1, 0, full), "256 is the cap itself");
13530 let extra = GainKey::new(9_999, 0.0);
13531 assert!(
13532 !p.add_gain_key(a1, 0, extra),
13533 "a 257th point through add is refused"
13534 );
13535 assert!(
13536 p.add_gain_key(a1, 0, GainKey::new(3, -3.0)),
13537 "a replacement still fits"
13538 );
13539 }
13540
13541 #[test]
13542 fn gain_keys_add_replace_remove_and_undo_each_take_one_step() {
13543 let mut p = Project::single(FILE, 150);
13544 let a1 = Lane::new(LaneKind::Audio, 0);
13545 assert!(p.add_gain_key(a1, 0, GainKey::new(0, 0.0)));
13546 assert!(p.add_gain_key(a1, 0, GainKey::new(30, -20.0)));
13547 assert!(
13548 p.add_gain_key(a1, 0, GainKey::new(30, -3.0)),
13549 "same frame replaces"
13550 );
13551 assert_eq!(
13552 p.gain_keys_of(a1, 0),
13553 &[GainKey::new(0, 0.0), GainKey::new(30, -3.0)]
13554 );
13555 assert!(
13556 !p.add_gain_key(a1, 0, GainKey::new(30, -3.0)),
13557 "the point already there changes nothing"
13558 );
13559 assert!(p.remove_gain_key(a1, 0, 0));
13560 assert!(!p.remove_gain_key(a1, 0, 0), "no point left at 0");
13561 assert_eq!(p.gain_keys_of(a1, 0), &[GainKey::new(30, -3.0)]);
13562 assert!(p.undo());
13563 assert_eq!(p.gain_keys_of(a1, 0).len(), 2, "the removal undone");
13564 assert!(p.undo());
13565 assert_eq!(
13566 p.gain_keys_of(a1, 0),
13567 &[GainKey::new(0, 0.0), GainKey::new(30, -20.0)],
13568 "the replacement undone"
13569 );
13570 assert!(p.undo());
13571 assert_eq!(p.gain_keys_of(a1, 0), &[GainKey::new(0, 0.0)]);
13572 assert!(p.undo());
13573 assert!(p.gain_keys_of(a1, 0).is_empty(), "back to flat");
13574 assert!(!p.undo(), "and no step is left to take");
13575 }
13576
13577 #[test]
13578 fn gain_db_at_maps_timeline_to_source_through_in_point_and_speed() {
13579 let mut p = Project::single(FILE, 150);
13580 let a1 = Lane::new(LaneKind::Audio, 0);
13581 assert!(p.set_gain_keys(
13582 a1,
13583 0,
13584 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)]
13585 ));
13586 assert!((p.gain_db_at(a1, 0, 50).unwrap() + 10.0).abs() < 1e-4);
13587 assert_eq!(
13588 p.gain_db_at(Lane::V1, 0, 50),
13589 None,
13590 "a video lane has no envelope"
13591 );
13592 assert_eq!(p.gain_db_at(a1, 3, 50), None, "no such clip");
13593 assert!(p.set_speed(a1, 0, Speed::from_permille(2000)).is_ok());
13594 assert!(
13595 (p.gain_db_at(a1, 0, 20).unwrap() + 8.0).abs() < 1e-3,
13596 "at 2x, timeline frame 20 plays source 40"
13597 );
13598 assert!(p.set_clip_gain(a1, 0, -6.0));
13599 assert!(
13600 (p.gain_db_at(a1, 0, 20).unwrap() + 14.0).abs() < 1e-3,
13601 "clip gain adds"
13602 );
13603 }
13604
13605 #[test]
13606 fn split_keeps_the_gain_curve_on_both_halves() {
13607 let mut p = Project::single(FILE, 150);
13608 let a1 = Lane::new(LaneKind::Audio, 0);
13609 assert!(p.set_gain_keys(
13610 a1,
13611 0,
13612 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)]
13613 ));
13614 let before: Vec<f32> = (0..150).map(|t| p.gain_db_at(a1, 0, t).unwrap()).collect();
13615 assert!(p.split(60));
13616 assert_eq!(p.lane(a1).len(), 2);
13617 for c in p.lane(a1) {
13618 assert_eq!(
13619 c.gain_keys,
13620 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)],
13621 "both halves keep every point"
13622 );
13623 }
13624 let after: Vec<f32> = (0..150)
13625 .map(|t| p.gain_db_at(a1, usize::from(t >= 60), t).unwrap())
13626 .collect();
13627 assert_eq!(before, after, "the curve is unchanged by the cut");
13628 }
13629
13630 #[test]
13631 fn gain_envelope_rides_the_fade_in_timeline_frames_and_scales_to_audio() {
13632 let mut p = Project::single(FILE, 150);
13633 let a1 = Lane::new(LaneKind::Audio, 0);
13634 assert!(p.set_gain_keys(
13635 a1,
13636 0,
13637 vec![GainKey::new(0, 0.0), GainKey::new(30, -20.0)]
13638 ));
13639 let fade = p.lane_fades_from(a1, 0, 30.0)[0]
13640 .clone()
13641 .expect("an enveloped clip has a fade");
13642 let minus_ten = 10f32.powf(-10.0 / 20.0);
13643 assert!(
13644 (fade.gain_at(15) - minus_ten).abs() < 1e-4,
13645 "frame 15 is -10 dB, which is {}",
13646 fade.gain_at(15)
13647 );
13648 assert!(
13649 (fade.gain_at(45) - 0.1).abs() < 1e-4,
13650 "held at -20 dB past the last point"
13651 );
13652 let scaled = fade.clone().scaled(1000.0);
13653 assert!(
13654 (scaled.gain_at(15_000) - fade.gain_at(15)).abs() < 1e-4,
13655 "audio frames"
13656 );
13657 }
13658
13659 #[test]
13660 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
13661 let f = Fade {
13662 elapsed: 0,
13663 fade_in: 10,
13664 fade_out: 10,
13665 total: 40,
13666 gain: 1.0,
13667 pan: (1.0, 1.0),
13668 curve: None,
13669 };
13670 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
13671 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
13672 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
13673 assert!(
13674 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
13675 "equal-power midpoint is sin(pi/4)"
13676 );
13677 assert_eq!(
13678 f.gain_at(20),
13679 1.0,
13680 "unchanged in the body, past either ramp"
13681 );
13682 // The fade-out is the same curve, mirrored, counting down from the
13683 // clip's end: unity at the frame the ramp starts, the same
13684 // equal-power midpoint, and -- since `total` itself is one past the
13685 // clip's last valid frame -- the very last frame is one step short of
13686 // the silence a fade-in's own frame `0` lands on exactly.
13687 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
13688 assert!(
13689 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
13690 "the fade-out's own equal-power midpoint"
13691 );
13692 assert!(
13693 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
13694 "one step short of silence at the clip's last playable frame"
13695 );
13696 }
13697
13698 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
13699 /// not adjacent, and otherwise sets the shared edge's fades and nothing
13700 /// else.
13701 #[test]
13702 fn crossfade_only_joins_adjacent_audio_clips() {
13703 let mut p = Project::single(FILE, 20);
13704 assert!(p.split(10));
13705 assert!(!p.crossfade(Lane::V1, 0, 5), "video is not an audio lane");
13706 assert!(!p.crossfade(Lane::A1, 1, 5), "there is no clip after idx 1");
13707 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
13708 let a = p.lane(Lane::A1);
13709 assert_eq!(a[0].fade_out, 5);
13710 assert_eq!(a[1].fade_in, 5);
13711 assert_eq!(a[0].fade_in, 0);
13712 assert_eq!(a[1].fade_out, 0);
13713
13714 // A gap between two clips is not adjacency, even on an audio lane.
13715 let mut p2 = Project::single(FILE, 1);
13716 let a2 = p2.add_lane(LaneKind::Audio);
13717 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
13718 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
13719 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
13720 }
13721
13722 /// The rule [`Project::write_split`] follows for the edge the razor makes:
13723 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
13724 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
13725 /// mirror image.
13726 #[test]
13727 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
13728 let mut p = Project::single(FILE, 20);
13729 assert!(p.set_fade_in(Lane::V1, 0, 15));
13730 assert!(p.set_fade_out(Lane::V1, 0, 15));
13731 assert!(p.split(5));
13732 let v = p.lane(Lane::V1);
13733 assert_eq!(
13734 v[0].fade_in, 5,
13735 "the left half's kept fade-in, clamped to 5 frames"
13736 );
13737 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
13738 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
13739 assert_eq!(
13740 v[1].fade_out, 15,
13741 "the right half's kept fade-out, unclamped: 15 frames fit in 15"
13742 );
13743 }
13744
13745 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
13746 /// no successor, and two clips that do not touch, and otherwise clamps
13747 /// the dissolve to the shorter of the two clips it spans.
13748 #[test]
13749 fn set_transition_out_only_dissolves_adjacent_video_clips() {
13750 let mut p = Project::single(FILE, 20);
13751 assert!(p.split(15), "a short 5-frame tail to clamp against");
13752 assert!(
13753 !p.set_transition_out(Lane::A1, 0, 5),
13754 "audio is not a video lane"
13755 );
13756 assert!(
13757 !p.set_transition_out(Lane::V1, 1, 5),
13758 "there is no clip after idx 1"
13759 );
13760 assert!(
13761 p.set_transition_out(Lane::V1, 0, 100),
13762 "the two halves are adjacent"
13763 );
13764 assert_eq!(
13765 p.transition_out_of(Lane::V1, 0),
13766 5,
13767 "clamped to the shorter neighbour's 5 frames"
13768 );
13769
13770 // A gap between two clips is not adjacency, even on the video lane.
13771 let mut p2 = Project::single(FILE, 1);
13772 let v2 = p2.add_lane(LaneKind::Video);
13773 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
13774 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
13775 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
13776 }
13777
13778 /// The two transition doors' bool is the WEAK shape, stated here as
13779 /// behaviour rather than left as something a front-end has to know: both
13780 /// answer "these two clips are adjacent", and both snapshot and clamp --
13781 /// so a write that lands the value the join already carries is still
13782 /// reported as a write. The step it pushed changed nothing, so it is settled
13783 /// away and costs no undo step. The front-end's before/after comparison
13784 /// (`Player::transition_edges`) still decides what it shows.
13785 #[test]
13786 fn a_transition_door_says_yes_to_a_write_that_moved_nothing() {
13787 let mut p = Project::single(FILE, 20);
13788 assert!(p.split(10), "two halves to join");
13789 assert!(p.set_transition_out(Lane::V1, 0, 5), "the dissolve lands");
13790 assert!(p.crossfade(Lane::A1, 0, 5), "the crossfade lands");
13791 let history = p.history_len();
13792
13793 // The very same numbers again: nothing moved, and both doors report a
13794 // write anyway.
13795 assert!(
13796 p.set_transition_out(Lane::V1, 0, 5),
13797 "set_transition_out answers 'the clips are adjacent', not 'the \
13798 dissolve moved', so a no-op reads as a write"
13799 );
13800 assert!(
13801 p.crossfade(Lane::A1, 0, 5),
13802 "crossfade answers the same way for the same reason"
13803 );
13804 assert_eq!(
13805 p.history_len(),
13806 history,
13807 "and neither spent an undo step: a write that changed nothing is settled away"
13808 );
13809
13810 // What did not move -- the comparison the front-end makes: both edges
13811 // a crossfade writes, and the dissolve itself.
13812 let a = p.lane(Lane::A1);
13813 assert_eq!((a[0].fade_out, a[1].fade_in), (5, 5), "unchanged");
13814 assert_eq!(p.transition_out_of(Lane::V1, 0), 5, "unchanged");
13815
13816 // And a refusal still answers no, so the arm is not simply always on:
13817 // the last clip has no successor to dissolve into.
13818 assert!(
13819 !p.set_transition_out(Lane::V1, 1, 5),
13820 "no neighbour end to end"
13821 );
13822 }
13823
13824 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
13825 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
13826 /// only the half that kept the clip's original *end* keeps the dissolve,
13827 /// re-clamped to its own now-shorter length; the head the cut just made
13828 /// has no successor to dissolve into and starts flat.
13829 #[test]
13830 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
13831 let mut p = Project::single(FILE, 20);
13832 assert!(
13833 !p.set_transition_out(Lane::V1, 0, 0),
13834 "one clip on the lane, no successor to dissolve into yet"
13835 );
13836 // Give the clip a dissolve by hand, then cut it in two.
13837 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
13838 assert!(p.split(5));
13839 let v = p.lane(Lane::V1);
13840 assert_eq!(
13841 v[0].transition_out, 0,
13842 "the cut edge it made has no successor"
13843 );
13844 assert_eq!(
13845 v[1].transition_out, 15,
13846 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
13847 );
13848 }
13849
13850 /// The music video's own path: the take comes apart into halves that carry
13851 /// ids of their own, one undo puts it back, and two clips over the same
13852 /// frames become one take again by hand.
13853 #[test]
13854 fn a_take_comes_apart_and_goes_back_together() {
13855 let mut p = Project::single(FILE, 9);
13856 let one = p.clips()[0].link.expect("a fresh project is one take");
13857 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
13858
13859 // A third lane in the same group -- and the merge case with it: a
13860 // placement is in no group, and grouping it in leaves *one* group.
13861 let v2 = p.add_lane(LaneKind::Video);
13862 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
13863 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
13864 p.group(Lane::V1, 0, v2, 0)
13865 .expect("the same frames, one lane over");
13866 let id = p.clips()[0].link.expect("still a group");
13867 assert!(
13868 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
13869 "one id over the three, not two groups sharing a span"
13870 );
13871 links_are_consistent(&p.lanes).expect("one id, one span");
13872
13873 // Detached by the sound: every half of the group, not only the two.
13874 assert!(p.ungroup(Lane::A1, 0));
13875 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
13876 assert!(
13877 ids.iter().all(Option::is_some),
13878 "a half keeps an id of its own"
13879 );
13880 assert!(
13881 ids.iter()
13882 .enumerate()
13883 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
13884 "and no two halves are the same group any more: {ids:?}"
13885 );
13886 links_are_consistent(&p.lanes).expect("a lone id is legal");
13887
13888 // One snapshot for the whole detach.
13889 assert!(p.undo());
13890 assert!(
13891 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
13892 "one undo puts the whole group back"
13893 );
13894
13895 // And back together by hand: the two the pointer named, and only them.
13896 assert!(p.ungroup(Lane::V1, 0));
13897 p.group(Lane::V1, 0, Lane::A1, 0)
13898 .expect("both cover [0, 9)");
13899 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
13900 assert_ne!(
13901 p.lane(v2)[0].link,
13902 p.lane(Lane::V1)[0].link,
13903 "the third half stayed detached"
13904 );
13905 links_are_consistent(&p.lanes).expect("one id, one span");
13906 }
13907
13908 /// What a group may not be, and what a detach has nothing to take apart --
13909 /// none of which may cost an undo step.
13910 #[test]
13911 fn a_group_is_one_span_and_one_clip_per_lane() {
13912 let mut p = three();
13913 let before = shape(&p);
13914 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
13915
13916 assert!(
13917 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
13918 "two clips of one lane are never one take"
13919 );
13920 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
13921 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
13922 assert!(
13923 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
13924 "{spans}"
13925 );
13926 assert!(
13927 spans.contains("trim them to matching bounds first"),
13928 "{spans}"
13929 );
13930 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
13931
13932 // A half nothing else is grouped with is already detached, a placement
13933 // is in no group at all, and an index that is not there has nothing to
13934 // detach either.
13935 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
13936 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
13937 assert!(p.lift(Lane::A1, 0));
13938 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
13939 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
13940
13941 // Two undos, one per edit: not one of the refusals pushed a snapshot.
13942 assert!(p.undo());
13943 assert!(p.undo());
13944 assert_eq!(shape(&p), before);
13945 }
13946
13947 /// Where a re-rate puts a playhead: the scene under the cursor stays the
13948 /// scene under the cursor, measured the way a viewer would -- the source
13949 /// frame playing at the playhead is the same frame after the write, at
13950 /// every playhead position the re-rate can catch one.
13951 #[test]
13952 fn a_re_rate_keeps_the_frame_under_the_playhead() {
13953 let caption = |start: u32, frames: u32| SubClip {
13954 start,
13955 frames,
13956 track: 0,
13957 in_us: 0,
13958 out_us: i64::from(frames) * 1_000_000,
13959 link: None,
13960 };
13961 let track = || SubtitleTrack {
13962 path: FILE.into(),
13963 track: None,
13964 language: "eng".into(),
13965 name: String::new(),
13966 label: "eng".into(),
13967 cues: Vec::new(),
13968 bitmap: false,
13969 refused: None,
13970 };
13971 // A group of a 300-frame clip and a caption offset 30 frames into it.
13972 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
13973 let s1 = p.add_lane(LaneKind::Subtitle);
13974 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
13975 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13976
13977 // The frame playing at `at`: which clip, and which source frame of it.
13978 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
13979 p.span_at(Lane::V1, at).and_then(|s| s.from)
13980 };
13981
13982 // Inside the held clip: the source frame under the playhead is the
13983 // same one after the re-rate, at 2x and at half speed both.
13984 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
13985 let at = 120;
13986 let before = playing(&p, at).expect("a clip under the playhead");
13987 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
13988 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
13989 .expect("room for it");
13990 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
13991 assert_eq!(before, after, "{what}: the same source frame plays");
13992 // ...and the write itself is untouched by the question.
13993 assert!(p.undo(), "{what}: one step back");
13994 }
13995
13996 // Past the group -- the clip ends at 300 and the caption at 270, so
13997 // from 300 on nothing is re-timed under the playhead: unmoved.
13998 for at in [300u32, 301, 1_000] {
13999 assert_eq!(
14000 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
14001 Some(at),
14002 "at {at}: outside every member, unmoved"
14003 );
14004 }
14005 // The boundary is exact: the held clip's own last frame (299) maps
14006 // to its new one (149 -- the last frame inside [0, 150), where the
14007 // shrunken clip's last source frame plays), and its first stays put.
14008 assert_eq!(
14009 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
14010 Some(149)
14011 );
14012 assert_eq!(
14013 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
14014 Some(0)
14015 );
14016 // A spot the caption shares with the clip maps by the clip (it is
14017 // what is *playing* there): the held clip's own proportion, which on
14018 // this fixture is also its head.
14019 assert_eq!(
14020 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
14021 Some(45),
14022 "the clip under the caption owns the spot"
14023 );
14024 }
14025
14026 /// A playhead inside another clip member of the group: that member keeps
14027 /// its own head, so the mapping is by its proportion and not the held
14028 /// clip's -- and the frame under the cursor is still the frame that was.
14029 #[test]
14030 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
14031 let mut p = Project::single(FILE, 300);
14032 // A second clip, grouped with the first but starting 300 later: the
14033 // head the group shares and its own differ by exactly that.
14034 let v2 = p.add_lane(LaneKind::Video);
14035 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
14036 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
14037 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
14038
14039 let at = 450; // inside the second member, 150 past its head
14040 let before = p.span_at(v2, at).and_then(|s| s.from);
14041 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
14042 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
14043 .expect("room for it");
14044 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
14045 assert_eq!(before, after, "the second member's own frame plays");
14046 // ...and the mapping itself: 150 past its head halves, the head stays.
14047 assert_eq!(mapped, Some(375));
14048 }
14049
14050 /// The link counter a load seeds sits past every id the file names,
14051 /// captions included: a hand-grouped caption may carry the highest id there
14052 /// is, and a counter that read the clips alone would hand it to the next
14053 /// group that asked -- silently grouping the caption with clips it never
14054 /// met.
14055 #[test]
14056 fn the_link_counter_sits_past_a_caption_only_id() {
14057 let track = || SubtitleTrack {
14058 path: FILE.into(),
14059 track: None,
14060 language: "eng".into(),
14061 name: String::new(),
14062 label: "eng".into(),
14063 cues: Vec::new(),
14064 bitmap: false,
14065 refused: None,
14066 };
14067 let mut p = Project::single(FILE, 9);
14068 p.add_lane(LaneKind::Subtitle);
14069 let caption = SubClip {
14070 start: 0,
14071 frames: 6,
14072 track: 0,
14073 in_us: 0,
14074 out_us: 6_000_000,
14075 // The highest id in the file, and only a caption carries it.
14076 link: Some(1),
14077 };
14078 let mut p = p
14079 .with_subtitles(vec![track()])
14080 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
14081 .expect("a caption may carry the file's highest id");
14082
14083 // A new group on lanes the caption is not on mints the next id -- which
14084 // must not be the caption's.
14085 let v2 = p.add_lane(LaneKind::Video);
14086 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
14087 p.group_all(&[(Lane::V1, 0), (v2, 0)])
14088 .expect("the clips group");
14089 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
14090 assert_ne!(minted, 1, "the caption's id is not re-issued to clips");
14091 assert_eq!(
14092 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
14093 Some(1),
14094 "the caption keeps its own group"
14095 );
14096 assert!(links_are_consistent(&p.lanes).is_ok());
14097 }
14098
14099 /// A rate re-times the caption members of the group by the ratio it gives
14100 /// the held clip: the span on the timeline compresses about the held clip's
14101 /// head, the words' own window untouched -- and one undo puts it back.
14102 #[test]
14103 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
14104 let caption = |start: u32, frames: u32| SubClip {
14105 start,
14106 frames,
14107 track: 0,
14108 in_us: 0,
14109 out_us: i64::from(frames) * 1_000_000,
14110 link: None,
14111 };
14112 let track = || SubtitleTrack {
14113 path: FILE.into(),
14114 track: None,
14115 language: "eng".into(),
14116 name: String::new(),
14117 label: "eng".into(),
14118 cues: Vec::new(),
14119 bitmap: false,
14120 refused: None,
14121 };
14122 let grouped = || {
14123 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14124 let s1 = p.add_lane(LaneKind::Subtitle);
14125 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
14126 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14127 (p, s1)
14128 };
14129
14130 // An aligned take, doubled: the caption plays in half the frames.
14131 let (mut p, s1) = grouped();
14132 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
14133 .expect("room for it");
14134 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
14135 let s = p.sub_lane(s1)[0];
14136 assert_eq!(
14137 (s.start, s.frames),
14138 (0, 45),
14139 "same words, half the timeline"
14140 );
14141 assert_eq!(
14142 (s.in_us, s.out_us),
14143 (0, 90_000_000),
14144 "the window is untouched"
14145 );
14146 assert!(links_are_consistent(&p.lanes).is_ok());
14147 assert!(p.undo());
14148 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
14149
14150 // An offset group, slowed to half: the caption's *offset from the held
14151 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
14152 // 0.5x, and still ends where the clip does.
14153 let (mut p, s1) = grouped();
14154 p.lift_sub(s1, 0);
14155 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
14156 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14157 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
14158 .expect("room for it");
14159 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
14160 let s = p.sub_lane(s1)[0];
14161 assert_eq!(
14162 (s.start, s.frames),
14163 (60, 120),
14164 "the offset doubles with the clip"
14165 );
14166 assert_eq!(
14167 s.end(),
14168 p.lane(Lane::V1)[0].end(),
14169 "still ends with the clip"
14170 );
14171
14172 // A stretch that runs the caption into its neighbour is refused, by
14173 // lane and frame, and costs no undo step.
14174 let (mut p, s1) = grouped();
14175 p.lift_sub(s1, 0);
14176 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
14177 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
14178 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14179 let history = p.history.len();
14180 let err = p
14181 .set_speed(Lane::V1, 0, Speed::from_permille(500))
14182 .unwrap_err()
14183 .to_string();
14184 assert!(
14185 err.contains(
14186 "the S1 caption at frame 0 would run to frame 180 and the next starts at 95"
14187 ),
14188 "{err}"
14189 );
14190 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
14191 }
14192
14193 /// The silence scan's speed-up re-times the captions on a scoped lane with
14194 /// everything else: the piece inside the region plays in the region's new
14195 /// frames, and what sits behind the region slides up with the clips.
14196 #[test]
14197 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
14198 let caption = |start: u32, frames: u32| SubClip {
14199 start,
14200 frames,
14201 track: 0,
14202 in_us: 0,
14203 out_us: i64::from(frames) * 1_000_000,
14204 link: None,
14205 };
14206 let track = || SubtitleTrack {
14207 path: FILE.into(),
14208 track: None,
14209 language: "eng".into(),
14210 name: String::new(),
14211 label: "eng".into(),
14212 cues: Vec::new(),
14213 bitmap: false,
14214 refused: None,
14215 };
14216 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14217 let s1 = p.add_lane(LaneKind::Subtitle);
14218 // Words over the region [30, 60) and words behind it.
14219 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
14220 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
14221
14222 // The region [30, 60) plays at 4x: 30 frames become 8, everything
14223 // behind slides up 22.
14224 // The scope is what the card's Take row says, caption lane included.
14225 p.speed_regions(
14226 &[(30, 30)],
14227 Speed::from_permille(4000),
14228 &[Lane::V1, Lane::A1, s1],
14229 )
14230 .expect("the region speeds up");
14231 let subs = p.sub_lane(s1);
14232 assert_eq!(
14233 (subs[0].start, subs[0].frames),
14234 (30, 8),
14235 "the piece inside plays in the region's new frames"
14236 );
14237 assert_eq!(
14238 (subs[1].start, subs[1].frames),
14239 (38, 30),
14240 "the piece behind slides up by what the region gave back"
14241 );
14242 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
14243 }
14244
14245 /// [`Project::speeded_playhead`]'s caption arm fires only when the
14246 /// playhead is inside a caption member and outside every clip member --
14247 /// a shape every other fixture avoids by keeping its caption inside the
14248 /// held clip. Here the caption overhangs the clip's tail, and the
14249 /// playhead standing in that overhang is answered by the caption's own
14250 /// piece: it scales about the held clip's head by the held clip's own
14251 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
14252 #[test]
14253 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
14254 let caption = |start: u32, frames: u32| SubClip {
14255 start,
14256 frames,
14257 track: 0,
14258 in_us: 0,
14259 out_us: i64::from(frames) * 1_000_000,
14260 link: None,
14261 };
14262 let track = || SubtitleTrack {
14263 path: FILE.into(),
14264 track: None,
14265 language: "eng".into(),
14266 name: String::new(),
14267 label: "eng".into(),
14268 cues: Vec::new(),
14269 bitmap: false,
14270 refused: None,
14271 };
14272 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14273 let s1 = p.add_lane(LaneKind::Subtitle);
14274 // The caption spans [80, 100) -- ten frames past the clip's own end
14275 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
14276 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
14277 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14278 // At 2x the clip halves to 45 frames; the overhang frame 95, which
14279 // no clip member's old span reaches, is the caption's own question:
14280 // half of 95 is 47.5, rounded to 48.
14281 assert_eq!(
14282 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
14283 Some(48),
14284 "the overhang frame answers through the caption's own piece"
14285 );
14286 }
14287
14288 /// `write_speed` and `speeded_playhead` are two questions of the SAME
14289 /// map ([`map`]'s architecture law): a caption's landed span comes from
14290 /// the map's own ends, and the playhead standing at the caption's own
14291 /// last frame before the write has to land exactly where the write put
14292 /// it -- across clip lengths and rates that round differently, and an
14293 /// odd-length caption straddling the clip's own tail edge, the corner
14294 /// where `write_speed` used to answer a frame short.
14295 #[test]
14296 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
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 for &len in &[90u32, 91, 177, 300, 301] {
14316 for &permille in &[500u16, 2000, 2500, 3000] {
14317 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
14318 let s1 = p.add_lane(LaneKind::Subtitle);
14319 // An odd-length caption straddling the clip's tail edge: its
14320 // own last frame lands past the held clip.
14321 let c_start = len.saturating_sub(3);
14322 p.place_sub(s1, c_start, caption(c_start, 7))
14323 .expect("placed");
14324 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14325 let speed = Speed::from_permille(permille);
14326 let last = c_start + 7 - 1;
14327 let mapped = p
14328 .speeded_playhead(Lane::V1, 0, speed, last)
14329 .expect("the caption is there");
14330 if p.set_speed(Lane::V1, 0, speed).is_err() {
14331 continue; // a refusal changes nothing: not this law's cell
14332 }
14333 let landed = p.sub_lane(s1)[0];
14334 if permille >= 1000 {
14335 // A speed-up compresses the timeline: many old frames
14336 // share one new frame, so the caption's own last old
14337 // frame lands flush with the write's own boundary --
14338 // the exact law [`write_speed`]'s worked drift-fix case
14339 // is stated against.
14340 assert_eq!(
14341 mapped,
14342 landed.end() - 1,
14343 "len {len} permille {permille}: the playhead at the caption's own \
14344 last frame lands where the write actually put it"
14345 );
14346 } else {
14347 // A slow-down expands it: one old frame becomes several
14348 // new ones, and `apply` answers where that frame's own
14349 // block *starts*, not where the caption's last new
14350 // frame (the end of that same block) sits -- a
14351 // one-frame gap inherent to the piece's own semantics,
14352 // not a drift between the two callers. Both still have
14353 // to agree the answer sits inside the caption the write
14354 // actually landed.
14355 assert!(
14356 (landed.start..landed.end()).contains(&mapped),
14357 "len {len} permille {permille}: the playhead lands inside the \
14358 caption the write actually put ({landed:?}), got {mapped}"
14359 );
14360 }
14361 }
14362 }
14363 }
14364
14365 /// A grouped caption's cues re-time with its clip: the placement's window
14366 /// crossed the timeline at its own proportion before any rate, and a
14367 /// re-rate changes that proportion (the frames compress, the window does
14368 /// not). A cue eight seconds into a window played at 2x crosses the screen
14369 /// four seconds in -- and at unity every cue lands exactly where it always
14370 /// did, byte for byte.
14371 #[test]
14372 fn a_grouped_captions_cues_re_time_with_its_clip() {
14373 let track = SubtitleTrack {
14374 path: FILE.into(),
14375 track: None,
14376 language: "eng".into(),
14377 name: String::new(),
14378 label: "eng".into(),
14379 cues: vec![crate::subtitle::Cue {
14380 start_us: 8_000_000,
14381 end_us: 9_000_000,
14382 text: "late line".into(),
14383 image: None,
14384 words: Vec::new(),
14385 karaoke: Vec::new(),
14386 }],
14387 bitmap: false,
14388 refused: None,
14389 };
14390 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
14391 let s1 = p.add_lane(LaneKind::Subtitle);
14392 // Ten seconds of the track over ten seconds of timeline: unity.
14393 p.place_sub(
14394 s1,
14395 0,
14396 SubClip {
14397 start: 0,
14398 frames: 300,
14399 track: 0,
14400 in_us: 0,
14401 out_us: 10_000_000,
14402 link: None,
14403 },
14404 )
14405 .expect("placed");
14406
14407 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
14408 let unity = p.sub_lane_cues(s1, FPS);
14409 assert_eq!(
14410 unity
14411 .iter()
14412 .map(|c| (c.start_us, c.end_us, &*c.text))
14413 .collect::<Vec<_>>(),
14414 [(8_000_000, 9_000_000, "late line")],
14415 "a unity placement maps exactly as it always did"
14416 );
14417
14418 // Grouped with the clip and re-rated to 2x: the same window now crosses
14419 // in half the time, so the cue at 8s of it lands 4s in.
14420 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14421 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
14422 .expect("room for it");
14423 let re_timed = p.sub_lane_cues(s1, FPS);
14424 assert_eq!(
14425 re_timed
14426 .iter()
14427 .map(|c| (c.start_us, c.end_us))
14428 .collect::<Vec<_>>(),
14429 [(4_000_000, 4_500_000)],
14430 "the cue crosses with the clip's new rate"
14431 );
14432 }
14433
14434 /// A video arriving on a timeline of words mutates none of them: the
14435 /// import's rippling insert used to open room on the subtitle lanes too,
14436 /// splitting a caption it landed inside and sliding the rest behind the
14437 /// video -- the hand asked for an add, and got a cut it never made. The
14438 /// words keep their own clock; co-travel is what a group is for.
14439 #[test]
14440 fn an_arriving_clip_never_touches_the_captions() {
14441 let caption = |start: u32, frames: u32| SubClip {
14442 start,
14443 frames,
14444 track: 0,
14445 in_us: i64::from(start) * 1_000_000 / 30,
14446 out_us: i64::from(start + frames) * 1_000_000 / 30,
14447 link: None,
14448 };
14449 let track = || SubtitleTrack {
14450 path: FILE.into(),
14451 track: None,
14452 language: "eng".into(),
14453 name: String::new(),
14454 label: "eng".into(),
14455 cues: Vec::new(),
14456 bitmap: false,
14457 refused: None,
14458 };
14459 // A timeline of words alone: 60 frames of caption, no media clips.
14460 let mut p = Project::single(FILE, 60).with_subtitles(vec![track()]);
14461 for l in [Lane::V1, Lane::A1] {
14462 while !p.lane(l).is_empty() {
14463 p.lift(l, 0);
14464 }
14465 }
14466 let s1 = p.add_lane(LaneKind::Subtitle);
14467 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
14468 let before = p.sub_lane(s1).to_vec();
14469
14470 // The video lands BEFORE the caption's span: nothing moves.
14471 let vid = clip(0, 0, 30, 0);
14472 assert!(p.paste(0, vid.clone()), "the video goes down at the head");
14473 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
14474
14475 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
14476 // byte the placement the hand made.
14477 assert!(p.paste(15, vid), "a second video lands inside the caption");
14478 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
14479 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
14480 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
14481 assert!(links_are_consistent(&p.lanes).is_ok());
14482 }
14483
14484 /// The region's caption pieces re-time by mapped boundaries forced apart:
14485 /// rounding start and length independently can land two cues on one frame,
14486 /// and the artifact is clamped -- one frame each, in order, none past the
14487 /// region's new end -- never an overlap on the lane.
14488 #[test]
14489 fn a_regions_caption_pieces_never_round_onto_one_another() {
14490 let caption = |start: u32, frames: u32| SubClip {
14491 start,
14492 frames,
14493 track: 0,
14494 in_us: 0,
14495 out_us: i64::from(frames) * 1_000_000,
14496 link: None,
14497 };
14498 let track = |n| SubtitleTrack {
14499 path: FILE.into(),
14500 track: None,
14501 language: "eng".into(),
14502 name: String::new(),
14503 label: format!("eng{n}"),
14504 cues: Vec::new(),
14505 bitmap: false,
14506 refused: None,
14507 };
14508 // Three lanes, one repro shape each: adjacent one-frame cues, a
14509 // three-frame pair, and the region's last cue against the first
14510 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
14511 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
14512 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
14513 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
14514 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
14515 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
14516 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
14517 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
14518 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
14519
14520 let mut scope = vec![Lane::V1, Lane::A1];
14521 scope.extend(lanes.iter().copied());
14522 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
14523 .expect("the region speeds up");
14524 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
14525 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
14526 p.sub_lane(lane)
14527 .iter()
14528 .map(|s| (s.start, s.frames))
14529 .collect()
14530 };
14531 assert_eq!(
14532 spans(&p, lanes[0]),
14533 [(5, 1), (6, 1)],
14534 "one frame each, in order"
14535 );
14536 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
14537 // and the walk pushes the second to where the first ends.
14538 assert_eq!(
14539 spans(&p, lanes[1]),
14540 [(3, 1), (4, 2)],
14541 "forced apart, kept in order"
14542 );
14543 // The last cue of the region ends exactly where the region now does
14544 // (frame 15), and the caption behind it lands on that same frame:
14545 // touching, never overlapping.
14546 assert_eq!(
14547 spans(&p, lanes[2]),
14548 [(14, 1), (15, 15)],
14549 "the cue ends with the region"
14550 );
14551 for &lane in &lanes {
14552 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
14553 }
14554 }
14555
14556 /// The scope law names a caption half too: a scoped cut that would move one
14557 // track of a group whose caption sits outside the scope is refused.
14558 #[test]
14559 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
14560 let caption = |start: u32, frames: u32| SubClip {
14561 start,
14562 frames,
14563 track: 0,
14564 in_us: 0,
14565 out_us: i64::from(frames) * 1_000_000,
14566 link: None,
14567 };
14568 let track = || SubtitleTrack {
14569 path: FILE.into(),
14570 track: None,
14571 language: "eng".into(),
14572 name: String::new(),
14573 label: "eng".into(),
14574 cues: Vec::new(),
14575 bitmap: false,
14576 refused: None,
14577 };
14578 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14579 let s1 = p.add_lane(LaneKind::Subtitle);
14580 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
14581 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14582
14583 // The subtitle lane is not in the scope, so the group's caption half
14584 // sits outside it: refused, in the law's own words.
14585 let err = p
14586 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
14587 .unwrap_err()
14588 .to_string();
14589 assert!(
14590 err.contains("is one take with the S1 caption at frame 0"),
14591 "{err}"
14592 );
14593
14594 // ...and with the caption's lane in the scope, the cut carries it:
14595 // the words over the hole go, and the words behind slide up.
14596 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
14597 .expect("the whole group is in the scope");
14598 let subs = p.sub_lane(s1);
14599 assert_eq!(
14600 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
14601 [(0, 10), (10, 75)],
14602 "the caption is cut and shifted with the clips"
14603 );
14604 }
14605
14606 /// The caption a hand groups: `group_all` over clips *and* a caption, the
14607 /// mates riding along, the offsets kept, the refusals in words.
14608 #[test]
14609 fn a_hand_built_group_holds_clips_and_a_caption() {
14610 let caption = |start: u32, frames: u32| SubClip {
14611 start,
14612 frames,
14613 track: 0,
14614 in_us: 0,
14615 out_us: i64::from(frames) * 1_000_000,
14616 link: None,
14617 };
14618 let track = || SubtitleTrack {
14619 path: FILE.into(),
14620 track: None,
14621 language: "eng".into(),
14622 name: String::new(),
14623 label: "eng".into(),
14624 cues: Vec::new(),
14625 bitmap: false,
14626 refused: None,
14627 };
14628 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14629 let v2 = p.add_lane(LaneKind::Video);
14630 let s1 = p.add_lane(LaneKind::Subtitle);
14631 // A layer at its own offset, and a caption over the head of the take.
14632 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
14633 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
14634
14635 // Too few, one lane twice, and an index that is not there: words, no
14636 // snapshot.
14637 let history = p.history.len();
14638 assert!(
14639 p.group_all(&[])
14640 .unwrap_err()
14641 .to_string()
14642 .contains("two placements or more")
14643 );
14644 assert!(
14645 p.group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
14646 .unwrap_err()
14647 .to_string()
14648 .contains("V1 is picked twice")
14649 );
14650 assert!(
14651 p.group_all(&[(Lane::V1, 0), (s1, 9)])
14652 .unwrap_err()
14653 .to_string()
14654 .contains("no subtitle 9")
14655 );
14656 assert_eq!(p.history.len(), history, "refusals cost no undo step");
14657
14658 // The group: the picture, the layer, and the caption -- and the sound
14659 // the picture was already grouped with comes along unasked.
14660 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
14661 .expect("three picks, three lanes");
14662 let id = p.lane(Lane::V1)[0].link.expect("grouped");
14663 for lane in [Lane::V1, Lane::A1, v2] {
14664 assert_eq!(
14665 p.lane(lane)[0].link,
14666 Some(id),
14667 "{} rides along",
14668 lane.label()
14669 );
14670 }
14671 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
14672 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
14673 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
14674 assert!(links_are_consistent(&p.lanes).is_ok());
14675 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
14676
14677 // ...and one undo takes it apart again.
14678 assert!(p.undo());
14679 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
14680
14681 // Detach names a caption like it names a clip: every member an id of
14682 // its own, which is never `None` (see `ungroup`).
14683 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
14684 assert!(p.ungroup(s1, 0));
14685 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
14686 assert!(loose_sub.is_some() && loose_clip.is_some());
14687 assert_ne!(loose_sub, loose_clip);
14688 assert!(links_are_consistent(&p.lanes).is_ok());
14689 }
14690
14691 /// Two captions on one sub lane, each already grouped with a *different*
14692 /// clip: `group_all` over both those clips would merge the two existing
14693 /// groups into one id and leave both captions on `s1` carrying it --
14694 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
14695 /// group closes. Refused by name, and nothing moves.
14696 #[test]
14697 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
14698 let caption = |start: u32, frames: u32| SubClip {
14699 start,
14700 frames,
14701 track: 0,
14702 in_us: 0,
14703 out_us: i64::from(frames) * 1_000_000,
14704 link: None,
14705 };
14706 let track = || SubtitleTrack {
14707 path: FILE.into(),
14708 track: None,
14709 language: "eng".into(),
14710 name: String::new(),
14711 label: "eng".into(),
14712 cues: Vec::new(),
14713 bitmap: false,
14714 refused: None,
14715 };
14716 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14717 let v2 = p.add_lane(LaneKind::Video);
14718 let s1 = p.add_lane(LaneKind::Subtitle);
14719 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
14720 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
14721 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
14722 // V1 grouped with the first caption, v2 with the second -- two
14723 // separate groups, each already one member per lane.
14724 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14725 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
14726 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
14727
14728 let history = p.history.len();
14729 let err = p
14730 .group_all(&[(Lane::V1, 0), (v2, 0)])
14731 .unwrap_err()
14732 .to_string();
14733 assert!(err.contains("one placement per lane"), "{err}");
14734 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
14735 assert_eq!(
14736 p.lane(Lane::V1)[0].link,
14737 v1_link,
14738 "the first group untouched"
14739 );
14740 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
14741 assert!(links_are_consistent(&p.lanes).is_ok());
14742 }
14743
14744 /// A split hands the caption of a group the same ids it hands the clips:
14745 /// the left halves keep the group, the right halves share a fresh one.
14746 #[test]
14747 fn a_split_cuts_a_grouped_caption_with_its_clips() {
14748 let caption = |start: u32, frames: u32| SubClip {
14749 start,
14750 frames,
14751 track: 0,
14752 in_us: 0,
14753 out_us: i64::from(frames) * 1_000_000,
14754 link: None,
14755 };
14756 let track = || SubtitleTrack {
14757 path: FILE.into(),
14758 track: None,
14759 language: "eng".into(),
14760 name: String::new(),
14761 label: "eng".into(),
14762 cues: Vec::new(),
14763 bitmap: false,
14764 refused: None,
14765 };
14766 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14767 let s1 = p.add_lane(LaneKind::Subtitle);
14768 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
14769 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14770 let take = p.lane(Lane::V1)[0].link.expect("the group id");
14771
14772 assert!(p.split(4));
14773 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
14774 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
14775 assert_eq!(left.frames, 4);
14776 assert_eq!(
14777 right.link,
14778 p.lane(Lane::V1)[1].link,
14779 "the caption's tail shares the clips' fresh id"
14780 );
14781 assert_ne!(right.link, Some(take));
14782 assert!(links_are_consistent(&p.lanes).is_ok());
14783
14784 // Regroup at the seam restores the take, caption included.
14785 assert!(p.regroup(4));
14786 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
14787 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
14788 }
14789
14790 /// Deleting a member of a hand-built group takes the group: every
14791 /// member's own span out of its own lane, hole closed -- the lanes may
14792 /// end up out of step, which is what one undo restores together.
14793 #[test]
14794 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
14795 let caption = |start: u32, frames: u32| SubClip {
14796 start,
14797 frames,
14798 track: 0,
14799 in_us: 0,
14800 out_us: i64::from(frames) * 1_000_000,
14801 link: None,
14802 };
14803 let track = || SubtitleTrack {
14804 path: FILE.into(),
14805 track: None,
14806 language: "eng".into(),
14807 name: String::new(),
14808 label: "eng".into(),
14809 cues: Vec::new(),
14810 bitmap: false,
14811 refused: None,
14812 };
14813 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14814 let s1 = p.add_lane(LaneKind::Subtitle);
14815 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
14816 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14817 // A neighbour on a lane the group does not touch.
14818 let v2 = p.add_lane(LaneKind::Video);
14819 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
14820
14821 // By the picture or by the caption, the same whole-group delete.
14822 assert!(p.delete_sub_in(s1, 0));
14823 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
14824 assert!(
14825 p.sub_lane(s1).is_empty(),
14826 "the caption's span left its lane"
14827 );
14828 assert_eq!(
14829 p.lane(v2)[0].start,
14830 10,
14831 "a lane the group does not touch stays"
14832 );
14833 assert!(links_are_consistent(&p.lanes).is_ok());
14834 assert!(p.undo(), "one step puts the group back");
14835 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
14836 }
14837
14838 /// The delete law, one statement for every anchor: a caption deleted
14839 /// WITH its group ripples its lane exactly as its clip siblings do --
14840 /// the hole closes and what follows slides up -- while a caption lifted
14841 /// alone leaves its gap, as it always has. And the delete of a grouped
14842 /// clip takes the group from whichever member was clicked.
14843 #[test]
14844 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
14845 let caption = |start: u32, frames: u32| SubClip {
14846 start,
14847 frames,
14848 track: 0,
14849 in_us: 0,
14850 out_us: i64::from(frames) * 1_000_000,
14851 link: None,
14852 };
14853 let track = || SubtitleTrack {
14854 path: FILE.into(),
14855 track: None,
14856 language: "eng".into(),
14857 name: String::new(),
14858 label: "eng".into(),
14859 cues: Vec::new(),
14860 bitmap: false,
14861 refused: None,
14862 };
14863 // V+A+S grouped, with a second caption BEHIND the group's caption:
14864 // closing the hole is what the second caption's position says.
14865 let group = || {
14866 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14867 let s1 = p.add_lane(LaneKind::Subtitle);
14868 p.place_sub(s1, 30, caption(30, 30))
14869 .expect("the group's caption");
14870 p.place_sub(s1, 90, caption(90, 30))
14871 .expect("the caption behind");
14872 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14873 (p, s1)
14874 };
14875
14876 // Deleted by the picture: all three lanes close.
14877 let (mut p, s1) = group();
14878 assert!(p.delete_in(Lane::V1, 0));
14879 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
14880 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
14881 assert_eq!(
14882 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
14883 [60],
14884 "the caption's lane closed by its own span: the follower slid up"
14885 );
14886 assert!(p.undo(), "one step");
14887 assert_eq!(
14888 p.sub_lane(s1).len(),
14889 2,
14890 "both captions back, offsets and all"
14891 );
14892
14893 // By the sound: the same whole-group delete.
14894 let (mut p, s1) = group();
14895 assert!(p.delete_in(Lane::A1, 0));
14896 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
14897 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
14898
14899 // By the caption itself: the same again.
14900 let (mut p, s1) = group();
14901 assert!(p.delete_sub_in(s1, 0));
14902 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
14903 assert_eq!(
14904 p.sub_lane(s1)[0].start,
14905 60,
14906 "closed from the caption's own door"
14907 );
14908 assert!(links_are_consistent(&p.lanes).is_ok());
14909
14910 // A caption lifted ALONE still leaves its gap: the ungrouped law,
14911 // unchanged.
14912 let (mut p, s1) = group();
14913 assert!(p.ungroup(s1, 0), "the caption stands alone");
14914 assert!(p.lift_sub(s1, 0));
14915 assert_eq!(
14916 p.sub_lane(s1)[0].start,
14917 90,
14918 "the follower stayed put: a lone caption's lift is a gap"
14919 );
14920 }
14921
14922 /// Dragging a grouped caption carries its clips, one delta for all of them
14923 /// -- and a caption in no group refuses an overlap exactly as it always did.
14924 #[test]
14925 fn dragging_a_grouped_caption_carries_its_group() {
14926 let caption = |start: u32, frames: u32| SubClip {
14927 start,
14928 frames,
14929 track: 0,
14930 in_us: 0,
14931 out_us: i64::from(frames) * 1_000_000,
14932 link: None,
14933 };
14934 let track = || SubtitleTrack {
14935 path: FILE.into(),
14936 track: None,
14937 language: "eng".into(),
14938 name: String::new(),
14939 label: "eng".into(),
14940 cues: Vec::new(),
14941 bitmap: false,
14942 refused: None,
14943 };
14944 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14945 let s1 = p.add_lane(LaneKind::Subtitle);
14946 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
14947 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14948
14949 // Same lane, further along: everyone moves by the same eight frames.
14950 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
14951 assert_eq!(p.sub_lane(s1)[0].start, 10);
14952 assert_eq!(
14953 p.lane(Lane::V1)[0].start,
14954 8,
14955 "the clip follows by the delta"
14956 );
14957 assert!(links_are_consistent(&p.lanes).is_ok());
14958
14959 // ...and an ungrouped caption is the caption it always was.
14960 assert!(p.ungroup(s1, 0));
14961 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
14962 let s1 = q.add_lane(LaneKind::Subtitle);
14963 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
14964 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
14965 assert!(
14966 q.move_sub(s1, 0, s1, 3)
14967 .unwrap_err()
14968 .to_string()
14969 .contains("already covers")
14970 );
14971 }
14972
14973 /// A trim carries a group's caption by the same delta as its clips, clamped
14974 /// to the caption's own walls -- the offsets between the members survive.
14975 #[test]
14976 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
14977 let caption = |start: u32, frames: u32| SubClip {
14978 start,
14979 frames,
14980 track: 0,
14981 in_us: 0,
14982 out_us: i64::from(frames) * 1_000_000,
14983 link: None,
14984 };
14985 let track = || SubtitleTrack {
14986 path: FILE.into(),
14987 track: None,
14988 language: "eng".into(),
14989 name: String::new(),
14990 label: "eng".into(),
14991 cues: Vec::new(),
14992 bitmap: false,
14993 refused: None,
14994 };
14995 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14996 let s1 = p.add_lane(LaneKind::Subtitle);
14997 // The caption sits two frames into the take and ends one early. The
14998 // source runs past the clip, or there is no tail to pull out.
14999 let src = &[20];
15000 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
15001 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
15002
15003 // The tail goes out by three: the clip to 12, the caption to 11.
15004 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
15005 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
15006 assert_eq!(
15007 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
15008 (2, 11),
15009 "the caption follows by the delta"
15010 );
15011 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
15012
15013 // The head comes in by two: everyone's start moves two along.
15014 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
15015 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
15016 assert!(links_are_consistent(&p.lanes).is_ok());
15017 }
15018
15019 #[test]
15020 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
15021 let mut p = three();
15022 let before = shape(&p);
15023 assert!(!p.split(0), "timeline 0 has nothing before it");
15024 assert!(!p.split(3), "existing boundary");
15025 assert!(!p.split(5), "existing boundary");
15026 assert!(!p.split(9), "one past the last frame");
15027 assert!(!p.split(1_000));
15028 assert_eq!(shape(&p), before);
15029 // one undo lands before the *second* split, so the refusals pushed nothing
15030 assert!(p.undo());
15031 assert_eq!(p.clips().len(), 2, "refused splits push no history");
15032
15033 // ...and a frame that is a gap in both lanes has nothing to split.
15034 let mut p = three();
15035 assert!(p.lift(Lane::V1, 1));
15036 assert!(p.lift(Lane::A1, 1));
15037 assert!(!p.split(4), "a gap is not a clip");
15038 }
15039
15040 #[test]
15041 fn regroup_refuses_what_a_split_could_not_have_made() {
15042 let mut p = three();
15043 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
15044 assert!(p.regroup(5));
15045 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
15046 // A boundary with a gap on one side, and one where the sources do not
15047 // meet, are both refused.
15048 let mut p = three();
15049 assert!(p.lift(Lane::V1, 1));
15050 assert!(p.lift(Lane::A1, 1));
15051 assert!(!p.regroup(3), "nothing starts at 3 any more");
15052 let mut p = three();
15053 for l in p.lanes() {
15054 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
15055 }
15056 assert!(!p.regroup(3), "source 100 does not follow source 3");
15057 assert!(!p.regroup(0), "nothing ends at 0");
15058 assert!(!p.regroup(1_000));
15059 }
15060
15061 #[test]
15062 fn map_and_spans_sweep_every_boundary() {
15063 let p = three();
15064 assert_eq!(p.timeline_frames(), 9);
15065 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
15066 // contiguous source here, so the clip index is what actually moves
15067 let expect = [
15068 (0, (0, 0)),
15069 (1, (0, 1)),
15070 (2, (0, 2)),
15071 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
15072 (4, (1, 4)),
15073 (5, (2, 5)),
15074 (6, (2, 6)),
15075 (7, (2, 7)),
15076 (8, (2, 8)),
15077 ];
15078 for (t, want) in expect {
15079 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
15080 }
15081 assert_eq!(p.map_timeline(9), None);
15082 // A span is the rest of the clip from where it was asked about.
15083 assert_eq!(
15084 p.span_at(Lane::V1, 6),
15085 Some(Span {
15086 reverse: false,
15087 ramp: None,
15088 start: 6,
15089 len: 3,
15090 from: Some((0, 6)),
15091 speed: Speed::NORMAL,
15092 pitch: 0,
15093 })
15094 );
15095 assert_eq!(p.span_at(Lane::V1, 9), None);
15096 }
15097
15098 /// The fit policy is one byte *in* the clip rather than an index into a
15099 /// table like the eq and the grade: there is nothing for a table to share.
15100 /// It costs the clip nothing at all -- the fields before it (a `usize`
15101 /// source and two `Option<u16>`s) already left the struct padded to 40
15102 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
15103 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
15104 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
15105 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
15106 /// words after it pads out to the next multiple of 8: 56 bytes total.
15107 /// The transform index is a third `Option<u16>`, same reason as the eq and
15108 /// colour ones before it -- it lands in bytes already spent on padding, so
15109 /// the struct still costs 56.
15110 /// The visualizer look is the first field whose own width outgrows the
15111 /// padding it lands in: it is a `u64` (a strand colour needs bytes above
15112 /// the clip's own four), so the words after it come to 60 and the
15113 /// alignment rounds them to 64 -- one word more than a clip used to cost.
15114 /// Since the gain envelope (`gain_db` plus the `gain_keys` `Vec`, 24 bytes
15115 /// of pointer, length and capacity) the clip is 96 bytes and no longer
15116 /// `Copy`; the `Vec` is what the copy-cost comment above no longer covers.
15117 /// The placement keys (`transform_keys`, a second `Vec`) take it to 120.
15118 /// The fit policy itself is still one byte: it sits in the padding among
15119 /// the other fields, and the total is the 224 (144 before the opacity and colour keys' `Vec`s,
15120 /// 192 before the effects stack's)
15121 /// rounded up to the alignment of 8, so removing it would not shrink the clip.
15122 /// This asserts the one-byte enum and the exact size, so any further growth
15123 /// shows up here first.
15124 #[test]
15125 fn a_fit_policy_costs_the_clip_no_word() {
15126 assert_eq!(std::mem::size_of::<FitPolicy>(), 1);
15127 assert_eq!(
15128 std::mem::size_of::<Clip>(),
15129 224,
15130 "Clip changed size: {} bytes",
15131 std::mem::size_of::<Clip>()
15132 );
15133 }
15134
15135 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
15136 /// anything in `three()` so it is recognisable wherever it lands.
15137 const PASTED: Clip = Clip {
15138 speed_keys: Vec::new(),
15139 reversed: false,
15140 stabilise: None, deinterlace: Deinterlace::Frame, mark: ClipMark { label: 0, off: false },
15141 angle: Angle { video: 0, audio: None },
15142 fade_in: 0,
15143 fade_out: 0,
15144 transition_out: 0,
15145 transition_kind: crate::transitions::TransitionKind::Dissolve,
15146 visualizer: 0,
15147 viz_paint: 0,
15148 gain_db: 0.0,
15149 gain_keys: Vec::new(),
15150 pan: 0,
15151 transform_keys: Vec::new(),
15152 opacity_keys: Vec::new(),
15153 color_keys: Vec::new(),
15154 effects: Vec::new(),
15155 start: 0,
15156 in_frame: 100,
15157 out_frame: 102,
15158 source: 0,
15159 link: None,
15160 eq: None,
15161 color: None,
15162 transform: None,
15163 fit: FitPolicy::Fit,
15164 speed: Speed::NORMAL,
15165 pitch: 0,
15166 };
15167
15168 #[test]
15169 fn paste_mid_clip_splits_around_it() {
15170 let mut p = three();
15171 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
15172 assert_eq!(p.timeline_frames(), 11);
15173 assert_eq!(
15174 shape(&p)[0],
15175 vec![
15176 clip(0, 0, 3, 0),
15177 clip(3, 3, 5, 0),
15178 clip(5, 5, 6, 0),
15179 clip(6, 100, 102, 0),
15180 clip(8, 6, 9, 0),
15181 ]
15182 );
15183 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
15184 // The pasted frames are exactly where they were asked for, and the
15185 // split-off remainder resumes after them.
15186 assert_eq!(p.map_timeline(6), Some((3, 100)));
15187 assert_eq!(p.map_timeline(7), Some((3, 101)));
15188 assert_eq!(p.map_timeline(8), Some((4, 6)));
15189 }
15190
15191 /// A set pasted from a take keeps the take: the picture and the sound copied
15192 /// together come back on one fresh link, and not the one they came from.
15193 #[test]
15194 fn paste_set_relinks_the_copied_take() {
15195 let mut p = Project::single(FILE, 40);
15196 let video = p.lane(Lane::V1)[0].clone();
15197 let sound = p.lane(Lane::A1)[0].clone();
15198 assert_eq!(video.link, sound.link, "the take starts linked");
15199 assert!(p.paste_set(50, &[(Lane::V1, video.clone()), (Lane::A1, sound.clone())]));
15200 let (v, a) = (p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
15201 assert!(v.is_some() && v == a, "the pasted pair is one take again");
15202 assert_ne!(v, video.link, "on a link of its own, not the source's");
15203 assert!(links_are_consistent(&p.lanes).is_ok());
15204 }
15205
15206 #[test]
15207 fn paste_at_boundary_zero_and_end() {
15208 let mut p = three();
15209 assert!(p.paste(3, PASTED), "existing boundary: no split");
15210 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
15211 assert_eq!(p.map_timeline(3), Some((1, 100)));
15212
15213 let mut p = three();
15214 assert!(p.paste(0, PASTED));
15215 assert_eq!(p.map_timeline(0), Some((0, 100)));
15216 assert_eq!(p.map_timeline(2), Some((1, 0)));
15217
15218 // At the end: appended, there being nothing in front to leave black.
15219 let mut p = three();
15220 assert!(p.paste(9, PASTED));
15221 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
15222 // Past it: down on the frame it was asked for, black in front of it --
15223 // a row let go on the open bed lands under the ghost that promised it.
15224 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
15225 assert!(p.paste(1_000, PASTED));
15226 assert_eq!(p.timeline_frames(), 1_002);
15227 assert_eq!(
15228 p.lane(Lane::V1).last().expect("the pasted clip").start,
15229 1_000
15230 );
15231 assert_eq!(
15232 p.lane(Lane::A1).last().expect("its other half").start,
15233 1_000
15234 );
15235
15236 // An empty clip is the one thing refused, and it pushes no history.
15237 let mut p = three();
15238 assert!(!p.paste(4, clip(0, 7, 7, 0)));
15239 assert_eq!(p.clips().len(), 3);
15240 }
15241
15242 /// The data-loss paste: a clip of a source with no picture used to land on
15243 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
15244 /// carried it was refused on the way back in ("a box with a larger size").
15245 #[test]
15246 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
15247 let mut p = three();
15248 let wav = p.import("/nonexistent/song.wav", 0);
15249 let copied = Clip {
15250 fade_in: 0,
15251 fade_out: 0,
15252 transition_out: 0,
15253 transition_kind: Default::default(),
15254 visualizer: 0,
15255 viz_paint: 0,
15256 gain_db: 0.0,
15257 source: wav,
15258 ..PASTED
15259 };
15260 assert!(p.paste(3, copied));
15261 // The room is opened on every lane, or the two would slide apart...
15262 assert_eq!(p.timeline_frames(), 11);
15263 assert_eq!(
15264 shape(&p)[0],
15265 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
15266 "the video lane got room and nothing else"
15267 );
15268 // ...but the clip itself only reaches the lane that can play it.
15269 assert_eq!(
15270 shape(&p)[1],
15271 vec![
15272 clip(0, 0, 3, 0),
15273 clip(3, 100, 102, wav),
15274 clip(5, 3, 5, 0),
15275 clip(7, 5, 9, 0)
15276 ]
15277 );
15278 // A source with a picture is unchanged: still the grouped pair.
15279 let mut p = three();
15280 assert!(p.paste(3, PASTED));
15281 assert_eq!(shape(&p)[0], shape(&p)[1]);
15282 }
15283
15284 /// A hand-written file may hold a clip that ends at the very last frame
15285 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
15286 /// to wrap its start round to the front of the lane: an overlap in debug, a
15287 /// project no reload would accept in release.
15288 #[test]
15289 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
15290 let far = clip(u32::MAX - 90, 0, 90, 0);
15291 let parts = |c: Clip| {
15292 Project::from_parts(
15293 vec![Source::new(FILE, 0)],
15294 two(vec![c.clone()], vec![c]),
15295 Vec::new(),
15296 Vec::new(),
15297 Vec::new(),
15298 )
15299 .expect("valid parts")
15300 };
15301 let mut p = parts(far.clone());
15302 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
15303 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
15304 assert!(!p.undo(), "...and pushes no history either");
15305 assert!(
15306 !p.paste(u32::MAX, PASTED),
15307 "appending has nowhere to go either: the timeline ends at the last frame"
15308 );
15309 // With room for exactly those frames the same paste is taken.
15310 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
15311 assert!(p.paste(0, PASTED));
15312 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
15313 }
15314
15315 #[test]
15316 fn paste_undoes_in_one_step() {
15317 let mut p = three();
15318 let before = shape(&p);
15319 assert!(p.paste(6, PASTED));
15320 assert!(p.undo());
15321 assert_eq!(shape(&p), before, "a paste is one undo step");
15322 }
15323
15324 #[test]
15325 fn a_copy_outlives_the_clip_it_came_from() {
15326 let mut p = three();
15327 let copied = p.clips()[1].clone(); // [3,5)
15328 assert!(p.delete(1));
15329 // Just a frame range: the source is still on disk either way.
15330 assert!(p.paste(0, copied));
15331 assert_eq!(p.map_timeline(0), Some((0, 3)));
15332 assert_eq!(p.timeline_frames(), 9);
15333 }
15334
15335 #[test]
15336 fn delete_closes_the_gap_on_both_lanes() {
15337 let mut p = three();
15338 assert!(p.delete(1));
15339 assert_eq!(p.timeline_frames(), 7);
15340 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
15341 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
15342 // timeline 3 used to be source 3; the gap closed so it is source 5 now
15343 assert_eq!(p.map_timeline(3), Some((1, 5)));
15344 assert_eq!(p.map_timeline(6), Some((1, 8)));
15345 assert_eq!(p.map_timeline(7), None);
15346 }
15347
15348 #[test]
15349 fn delete_first_last_and_only() {
15350 let mut p = three();
15351 assert!(p.delete(0));
15352 assert_eq!(p.map_timeline(0), Some((0, 3)));
15353 assert_eq!(p.timeline_frames(), 6);
15354
15355 let mut p = three();
15356 assert!(p.delete(2));
15357 assert_eq!(p.timeline_frames(), 5);
15358 assert_eq!(p.map_timeline(4), Some((1, 4)));
15359
15360 assert!(!p.delete(2), "index past the end");
15361 assert!(p.delete(1));
15362 assert!(p.delete(0), "and the last remaining clip goes too");
15363 assert_eq!(p.clips().len(), 0);
15364 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
15365 assert!(!p.delete(0), "there is nothing left to delete");
15366 assert!(p.undo(), "one gesture, one undo");
15367 assert_eq!(p.clips().len(), 1);
15368 }
15369
15370 /// The offset model's point: one lane loses a clip, the other does not move.
15371 #[test]
15372 fn a_lift_leaves_a_gap_and_moves_nothing() {
15373 let mut p = three();
15374 let video_before = shape(&p)[0].clone();
15375 assert!(p.lift(Lane::A1, 1));
15376 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
15377 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
15378 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
15379 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
15380 assert_eq!(p.map(Lane::A1, 4), None);
15381 assert_eq!(
15382 p.span_at(Lane::A1, 3),
15383 Some(Span {
15384 reverse: false,
15385 ramp: None,
15386 start: 3,
15387 len: 2,
15388 from: None,
15389 speed: Speed::NORMAL,
15390 pitch: 0,
15391 })
15392 );
15393 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
15394 assert!(p.undo());
15395 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
15396 }
15397
15398 #[test]
15399 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
15400 let mut p = three();
15401 assert!(p.lift(Lane::A1, 2));
15402 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
15403 assert_eq!(
15404 p.span_at(Lane::A1, 5),
15405 Some(Span {
15406 reverse: false,
15407 ramp: None,
15408 start: 5,
15409 len: 4,
15410 from: None,
15411 speed: Speed::NORMAL,
15412 pitch: 0,
15413 }),
15414 "the audio lane holds silence to the end of the picture"
15415 );
15416 assert_eq!(p.span_at(Lane::A1, 9), None);
15417 // Every lane covers the timeline exactly, gaps included.
15418 for l in p.lanes() {
15419 let spans = p.spans_from(l, 0);
15420 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
15421 assert_eq!(spans[0].start, 0);
15422 }
15423 }
15424
15425 /// The timeline is emptiable: the last placement comes off like any other,
15426 /// the project holds "nothing on any lane" as a state, and one undo per
15427 /// gesture brings it back.
15428 #[test]
15429 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
15430 let mut p = Project::single(FILE, 9);
15431 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
15432 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
15433 assert_eq!(p.timeline_frames(), 0);
15434 assert_eq!(p.composite_span_at(0), None, "nothing to show");
15435 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
15436 assert!(!p.lift(Lane::A1, 0), "index past the end");
15437 assert!(p.undo(), "and the last lift comes back");
15438 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
15439 // A saved-and-loaded empty timeline is a project like any other, and it
15440 // still names the file its frame rate came from.
15441 assert!(p.lift(Lane::V1, 0));
15442 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
15443 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
15444 let back = Project::from_parts(sources, lanes, eq, color, Vec::new())
15445 .expect("an empty project loads");
15446 assert_eq!(back.timeline_frames(), 0);
15447 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
15448 }
15449
15450 /// What a keyboard selection walks: one answer per lane, gaps included --
15451 /// the composite's own answer is one lane's and cannot say what the audio
15452 /// lane holds under the same playhead.
15453 #[test]
15454 fn lane_clip_at_answers_for_each_lane_separately() {
15455 let mut p = Project::single(FILE, 9);
15456 assert!(p.split(3), "both lanes split");
15457 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
15458 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
15459 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
15460 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
15461 // A gap on one lane leaves the other's clip selectable there.
15462 assert!(p.lift(Lane::A1, 0));
15463 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
15464 assert_eq!(
15465 p.lane_clip_at(Lane::A1, 3),
15466 Some(0),
15467 "indices moved with it"
15468 );
15469 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
15470 // A lane that is not there is not a panic.
15471 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
15472 }
15473
15474 #[test]
15475 fn place_overwrites_only_its_own_lane() {
15476 let mut p = three();
15477 let audio_before = shape(&p)[1].clone();
15478 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
15479 // is trimmed, nothing shifts.
15480 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
15481 assert_eq!(
15482 shape(&p)[0],
15483 vec![
15484 clip(0, 0, 3, 0),
15485 clip(3, 3, 4, 0),
15486 clip(4, 100, 102, 0),
15487 clip(6, 6, 9, 0),
15488 ]
15489 );
15490 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
15491 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
15492
15493 // Placed inside one clip, it splits it in two.
15494 let mut p = Project::single(FILE, 9);
15495 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
15496 assert_eq!(
15497 shape(&p)[0],
15498 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
15499 );
15500 // ...and placed past the end it makes a gap, which is the whole point.
15501 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
15502 assert_eq!(p.timeline_frames(), 22);
15503 assert_eq!(
15504 p.span_at(Lane::V1, 9),
15505 Some(Span {
15506 reverse: false,
15507 ramp: None,
15508 start: 9,
15509 len: 11,
15510 from: None,
15511 speed: Speed::NORMAL,
15512 pitch: 0,
15513 })
15514 );
15515 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
15516 }
15517
15518 /// A file with sound let go over a further video track: both halves go down,
15519 /// on the same frames, and the audio row is added when the `+ V` button left
15520 /// the project without one. One undo takes the lane and both clips back.
15521 #[test]
15522 fn a_take_placed_on_a_layer_lands_with_its_sound() {
15523 let mut p = three();
15524 let v2 = p.add_lane(LaneKind::Video);
15525 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
15526
15527 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
15528 let a2 = Lane::new(LaneKind::Audio, 1);
15529 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
15530 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
15531 assert_eq!(p.lane(v2)[0].start, 4);
15532 assert_eq!(p.lane(v2)[0].end(), 6);
15533 assert_eq!(
15534 p.lane(v2)[0].link,
15535 p.lane(a2)[0].link,
15536 "one take, not two placements"
15537 );
15538 assert!(p.lane(v2)[0].link.is_some());
15539 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
15540 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
15541
15542 // The pair overwrites its own two lanes and nothing else, exactly as a
15543 // one-lane place does.
15544 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
15545 assert_eq!(p.lane(v2), p.lane(a2));
15546 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
15547 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
15548
15549 assert!(p.undo(), "one step for the second pair");
15550 assert_eq!(p.lane(v2).len(), 1);
15551 assert!(p.undo(), "one step for the first pair *and* its lane");
15552 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
15553 assert!(p.lane(v2).is_empty());
15554
15555 // Refusals cost nothing: sound placed alone is `place`'s door.
15556 assert!(
15557 !p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)),
15558 "audio lane"
15559 );
15560 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
15561 assert!(
15562 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
15563 "a lane that is not there"
15564 );
15565 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
15566 }
15567
15568 /// The drag between tracks: let go at the frames it already covers the clip
15569 /// keeps them, one undo takes it back, and every way it can be refused
15570 /// leaves the project untouched.
15571 #[test]
15572 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
15573 let v2 = Lane::new(LaneKind::Video, 1);
15574 let mut p = three();
15575 assert_eq!(p.add_lane(LaneKind::Video), v2);
15576 let before = shape(&p);
15577
15578 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
15579 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
15580 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
15581 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
15582 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
15583 // One snapshot: a single undo, and the lane list survives it.
15584 assert!(p.undo());
15585 assert_eq!(shape(&p), before);
15586
15587 // A lane that is not there, the lane and frame it is already at, an
15588 // index that is not there, and a move across kinds: all refused,
15589 // nothing changed.
15590 let history = p.history.len();
15591 for (from, idx, to, start) in [
15592 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
15593 (Lane::V1, 1, Lane::V1, 3),
15594 (Lane::V1, 9, v2, 3),
15595 (Lane::V1, 1, Lane::A1, 3),
15596 (Lane::A1, 1, v2, 3),
15597 ] {
15598 assert!(
15599 !p.move_clip(from, idx, to, start),
15600 "{from:?} {idx} -> {to:?} at {start}"
15601 );
15602 }
15603 assert_eq!(shape(&p), before);
15604 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
15605
15606 // Landing on another clip is refused rather than overwriting it: the
15607 // pointer named the lane, never the take already sitting there.
15608 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
15609 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
15610 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
15611 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
15612 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
15613 }
15614
15615 /// A lane's name is a label: the address is unchanged, it is one undo step, an
15616 /// empty name clears it, a lane's removal takes it along, and a clip's deinterlace
15617 /// choice survives a split, a copy and an undo.
15618 #[test]
15619 fn lane_names_and_deinterlace_follow_the_usual_edit_rules() {
15620 let sources = vec![Source::new(FILE, 0)];
15621 let lanes = vec![(LaneKind::Video, vec![clip(0, 0, 10, 0)]), (LaneKind::Audio, vec![clip(0, 0, 10, 0)])];
15622 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15623 assert_eq!(p.set_lane_name(Lane::V1, " Interview "), Ok(true));
15624 assert_eq!(p.lane_name(Lane::V1), Some("Interview"));
15625 assert_eq!(p.lane_title(Lane::V1), "Interview");
15626 assert_eq!(p.lane_title(Lane::A1), "A1");
15627 assert_eq!(p.set_lane_name(Lane::V1, "Interview"), Ok(false), "no change, no history");
15628 assert!(p.set_lane_name(Lane::V1, &"x".repeat(MAX_LANE_NAME_CHARS + 1)).is_err());
15629 assert!(p.set_lane_name(Lane::V1, "a\nb").is_err());
15630 assert_eq!(p.set_lane_name(Lane::S1, "x"), Ok(false), "no such lane");
15631 assert!(p.undo());
15632 assert_eq!(p.lane_name(Lane::V1), None);
15633 assert!(p.redo());
15634 assert_eq!(p.lane_names(), vec!["Interview".to_string(), String::new()]);
15635 assert_eq!(p.set_lane_name(Lane::V1, " "), Ok(true), "blank clears");
15636 assert_eq!(p.lane_name(Lane::V1), None);
15637
15638 assert!(p.set_deinterlace(Lane::V1, 0, Deinterlace::Field));
15639 assert!(!p.set_deinterlace(Lane::V1, 0, Deinterlace::Field));
15640 assert!(!p.set_deinterlace(Lane::A1, 0, Deinterlace::Off), "video clips only");
15641 assert!(p.split(5));
15642 assert_eq!(p.deinterlace_of(Lane::V1, 0), Deinterlace::Field);
15643 assert_eq!(p.deinterlace_of(Lane::V1, 1), Deinterlace::Field, "both halves keep it");
15644 assert!(p.undo() && p.undo());
15645 assert_eq!(p.deinterlace_of(Lane::V1, 0), Deinterlace::Frame);
15646 assert!(p.redo());
15647 let copy = p.lane(Lane::V1)[0].clone();
15648 assert_eq!(copy.deinterlace, Deinterlace::Field, "a copy carries it");
15649 }
15650
15651 /// The drag *along* a track, which is the one every other editor has: the
15652 /// clip lands on the frame the pointer let it go at, and stops dead against
15653 /// the neighbour rather than overwriting it.
15654 #[test]
15655 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
15656 let sources = vec![Source::new(FILE, 0)];
15657 let lanes = vec![
15658 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
15659 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
15660 ];
15661 let mut p =
15662 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15663 let before = shape(&p);
15664
15665 // Into the gap, exactly where it was let go -- nothing else moves.
15666 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
15667 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
15668 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
15669 // Dragged past the clip in front of it: clamped to its wall, laid end
15670 // to end with it, never over it.
15671 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
15672 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
15673 // One undo per drag, and both of them together are the state it started
15674 // in -- the frames each clip plays never changed.
15675 assert!(p.undo() && p.undo());
15676 assert_eq!(shape(&p), before);
15677
15678 // A drop that changes nothing is a click, not an edit.
15679 let history = p.history.len();
15680 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
15681 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
15682 }
15683
15684 /// A move lands on any empty frames of its lane, jumping over the clips
15685 /// between -- where a drag only slides up to the first one it meets.
15686 #[test]
15687 fn a_move_jumps_over_clips_to_empty_frames() {
15688 let sources = vec![Source::new(FILE, 0)];
15689 let lanes = vec![
15690 (LaneKind::Video, vec![clip(0, 0, 4, 0), clip(6, 4, 8, 0), clip(12, 8, 12, 0)]),
15691 (LaneKind::Audio, vec![clip(0, 0, 4, 0)]),
15692 ];
15693 let mut p =
15694 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15695
15696 // [0,4) to [16,20): past the clip at 6 and the clip at 12, both empty
15697 // frames of the lane -- a move, not an insert, so nothing else shifts.
15698 assert!(p.move_clip(Lane::V1, 0, Lane::V1, 16));
15699 assert_eq!(
15700 shape(&p)[0],
15701 vec![clip(6, 4, 8, 0), clip(12, 8, 12, 0), clip(16, 0, 4, 0)]
15702 );
15703 // A gap of two frames (10..12) is too narrow for a four-frame clip: refused.
15704 let before = shape(&p);
15705 assert!(!p.move_clip(Lane::V1, 2, Lane::V1, 10), "no gap that wide");
15706 assert_eq!(shape(&p), before);
15707 }
15708
15709 /// A linked take jumps as one: its partner on the audio lane must be free
15710 /// at the same frames, and where it is not the drop is clamped to the
15711 /// partner's wall rather than overlapping it.
15712 #[test]
15713 fn a_linked_take_jumps_only_where_its_partner_is_free() {
15714 let link = |mut c: Clip| {
15715 c.link = Some(7);
15716 c
15717 };
15718 let sources = vec![Source::new(FILE, 0)];
15719 let lanes = vec![
15720 (LaneKind::Video, vec![link(clip(0, 0, 4, 0)), clip(12, 4, 8, 0)]),
15721 (LaneKind::Audio, vec![link(clip(0, 0, 4, 0))]),
15722 ];
15723 let mut p =
15724 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15725 let v2 = p.add_lane(LaneKind::Video);
15726
15727 // Both halves free at [20,24): the take lands there, partner included.
15728 assert!(p.move_clip(Lane::V1, 0, v2, 20));
15729 assert_eq!(p.lane(v2).iter().map(|c| c.start).collect::<Vec<_>>(), [20]);
15730 assert_eq!(p.lane(Lane::A1)[0].start, 20, "partner moves the same distance");
15731 assert_eq!(p.lane(Lane::A1)[0].link, Some(7));
15732
15733 // A partner blocked at [22,26) on the audio lane: the drop stops at the
15734 // frame where the partner meets nothing, never over the blocker.
15735 let sources = vec![Source::new(FILE, 0)];
15736 let lanes = vec![
15737 (LaneKind::Video, vec![link(clip(0, 0, 4, 0))]),
15738 (LaneKind::Audio, vec![link(clip(0, 0, 4, 0)), clip(22, 0, 4, 0)]),
15739 ];
15740 let mut p =
15741 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15742 let v2 = p.add_lane(LaneKind::Video);
15743 assert!(p.move_clip(Lane::V1, 0, v2, 20));
15744 assert_eq!(p.lane(v2)[0].start, 18, "clamped to the partner's wall");
15745 assert_eq!(p.lane(Lane::A1)[0].start, 18);
15746 assert_eq!(p.lane(Lane::A1)[1].start, 22, "the blocker is not moved");
15747 }
15748
15749 /// A drag carries the whole take: the sound half travels exactly as far as
15750 /// the picture does, and the tighter of their two walls stops both.
15751 #[test]
15752 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
15753 let mut p = three();
15754 assert!(
15755 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
15756 "room to the right"
15757 );
15758 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
15759 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
15760 // Something in the sound's way, and nothing at all in the picture's.
15761 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
15762 let before = shape(&p);
15763
15764 // Let go over empty frames on both lanes: the take lands there whole,
15765 // jumping the blocker that lies between.
15766 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
15767 assert!(p.lane(Lane::V1).iter().any(|c| c.start == 30));
15768 assert!(p.lane(Lane::A1).iter().any(|c| c.start == 30), "sound came with it");
15769 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15770 assert!(p.undo());
15771 assert_eq!(shape(&p), before, "one undo for the whole take");
15772
15773 // Let go on the sound's blocker: the take stops against it, picture
15774 // and sound alike, short of the frame the pointer named.
15775 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 9), "dropped on the blocker");
15776 assert!(p.lane(Lane::V1).iter().any(|c| c.start == 8), "stopped where the sound did");
15777 assert!(p.lane(Lane::A1).iter().any(|c| c.start == 8), "and the sound came with it");
15778 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15779 assert!(p.undo());
15780 assert_eq!(shape(&p), before, "one undo for the whole take");
15781 }
15782
15783 /// The drag that does both at once -- another lane *and* another frame --
15784 /// which is what a pointer let go over a lane always names.
15785 #[test]
15786 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
15787 let v2 = Lane::new(LaneKind::Video, 1);
15788 let mut p = three();
15789 assert_eq!(p.add_lane(LaneKind::Video), v2);
15790
15791 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
15792 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
15793 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
15794 assert_eq!(
15795 p.lane(Lane::A1)[2].start,
15796 20,
15797 "its sound travelled the same distance"
15798 );
15799 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15800 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
15801 }
15802
15803 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
15804 /// [`three`] cuts up all nine of its frames.
15805 const SRC: &[u32] = &[9];
15806
15807 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
15808 /// else on the lane moves, and every wall stops the edge rather than
15809 /// refusing the gesture.
15810 #[test]
15811 fn trimming_the_tail_stops_at_every_wall() {
15812 let mut p = three();
15813
15814 // Pulled in: a gap opens behind it and the clip after it stays put.
15815 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
15816 assert_eq!(
15817 shape(&p)[0],
15818 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
15819 );
15820 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
15821 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
15822
15823 // ...and back out, no further than the clip behind it.
15824 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
15825 assert_eq!(
15826 shape(&p)[0][1],
15827 clip(3, 3, 5, 0),
15828 "stopped at the neighbour"
15829 );
15830 assert!(
15831 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
15832 "already at the wall"
15833 );
15834
15835 // One frame of clip always survives, however far back the pointer went.
15836 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
15837 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
15838
15839 // The last clip has no neighbour, so what stops it is the file: nine
15840 // frames is nine frames.
15841 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
15842 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
15843 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
15844 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
15845 // A source nobody told us the length of may not grow at all -- an
15846 // out-point past the end of a file is a save that will not open again.
15847 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
15848 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
15849 }
15850
15851 /// The head pulled in takes the in-point with it -- what stays plays what it
15852 /// always played -- and stops at the source's own first frame.
15853 #[test]
15854 fn trimming_the_head_moves_the_in_point() {
15855 let mut p = three();
15856 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
15857 assert_eq!(
15858 shape(&p)[0][0],
15859 clip(2, 2, 3, 0),
15860 "two frames off the front"
15861 );
15862 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
15863 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
15864 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
15865 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
15866 // One frame survives here too.
15867 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
15868 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
15869
15870 // A clip that does not begin at its source's first frame: its head goes
15871 // back to source frame 0 and not one frame further.
15872 let mut p = Project::single(FILE, 9);
15873 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
15874 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
15875 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
15876 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
15877 }
15878
15879 /// A clip whose in-point is *past* its own start -- what a ripple delete
15880 /// leaves, the piece in front of it gone and this one slid back to frame 0
15881 /// carrying the in-point the cut gave it. Its head has more source behind it
15882 /// than the timeline has room for, and the timeline's own first frame is the
15883 /// wall: asking is not an overflow, and the answer is 0.
15884 #[test]
15885 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
15886 let mut p = Project::single(FILE, 9);
15887 assert!(p.split(5));
15888 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
15889 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
15890
15891 assert_eq!(
15892 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
15893 Some((0, 3)),
15894 "back to frame 0 at most, and one frame of clip always survives"
15895 );
15896 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
15897 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
15898 assert_eq!(
15899 shape(&p)[0],
15900 vec![clip(2, 7, 9, 0)],
15901 "the in-point followed"
15902 );
15903 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
15904 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
15905 }
15906
15907 /// A still is trimmed from its head exactly as it is from its tail: it has
15908 /// no earlier frame to walk an in-point back to, so the wall is the length
15909 /// the caller's table allows it, measured back from the tail. Measured from
15910 /// the in-point -- which a placed picture has at 0 -- its left edge could
15911 /// never be dragged outwards at all.
15912 #[test]
15913 fn a_stills_head_stretches_out_like_its_tail() {
15914 const STILL: &str = "/nonexistent/card.png";
15915 /// What a still is held to, as `PlaybackSession` fills the table in.
15916 const CAP: &[u32] = &[60];
15917
15918 let mut p = Project::single(STILL, 20);
15919 assert!(p.lift(Lane::A1, 0), "a picture is silent");
15920 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
15921 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
15922
15923 // A source with no entry in the table may not grow, here as at the tail.
15924 assert_eq!(
15925 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
15926 Some((100, 119)),
15927 "a length nobody told us buys no head room"
15928 );
15929 assert_eq!(
15930 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
15931 Some((60, 119)),
15932 "back to a whole cap's worth, one frame of clip surviving"
15933 );
15934 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
15935 assert_eq!(
15936 shape(&p)[0][0],
15937 clip(80, 0, 40, 0),
15938 "twenty frames longer, and still read from the source's first frame"
15939 );
15940 // Past the cap is clamped, exactly as the tail is -- not refused.
15941 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
15942 assert_eq!(
15943 shape(&p)[0][0],
15944 clip(60, 0, 60, 0),
15945 "a cap's worth, no more"
15946 );
15947 // ...and the clip in front is the nearer wall of the two: no head trim
15948 // may open an overlap.
15949 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
15950 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
15951 assert_eq!(
15952 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
15953 Some((85, 119)),
15954 "up to the neighbour's last frame and not over it"
15955 );
15956 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
15957 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
15958 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
15959 }
15960
15961 /// An end edge that runs out of source names the source's tail as its
15962 /// wall, and the same edge stopped by the clip after it does not -- and the
15963 /// walls are the ones `trim_room` gives, not a second computation.
15964 #[test]
15965 fn trim_walls_name_the_source_tail_or_the_neighbour() {
15966 let mut p = Project::single(FILE, 9);
15967 assert_eq!(
15968 p.trim_walls(Lane::V1, 0, Edge::End, SRC),
15969 Some(TrimWalls {
15970 lo: 1,
15971 hi: 9,
15972 lo_media: false,
15973 hi_media: true,
15974 }),
15975 "the whole source, and it runs out at its tail"
15976 );
15977 assert_eq!(
15978 p.trim_walls(Lane::V1, 0, Edge::End, SRC)
15979 .map(|w| (w.lo, w.hi)),
15980 p.trim_room(Lane::V1, 0, Edge::End, SRC),
15981 );
15982
15983 assert!(p.split(5));
15984 assert_eq!(
15985 p.trim_walls(Lane::V1, 0, Edge::End, SRC),
15986 Some(TrimWalls {
15987 lo: 1,
15988 hi: 5,
15989 lo_media: false,
15990 hi_media: false,
15991 }),
15992 "the source has more, but the next piece is nearer"
15993 );
15994 assert_eq!(
15995 p.trim_walls(Lane::V1, 1, Edge::End, SRC),
15996 Some(TrimWalls {
15997 lo: 6,
15998 hi: 9,
15999 lo_media: false,
16000 hi_media: true,
16001 }),
16002 "the last piece runs to the source's tail"
16003 );
16004 assert_eq!(
16005 p.trim_walls(Lane::V1, 2, Edge::End, SRC),
16006 None,
16007 "no such clip"
16008 );
16009 }
16010
16011 /// A start edge that drags back to the source's first frame names that
16012 /// head as its wall; one stopped by the piece in front of it does not.
16013 #[test]
16014 fn trim_walls_name_the_source_head_or_the_neighbour() {
16015 let mut p = Project::single(FILE, 9);
16016 assert!(p.split(5));
16017 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
16018 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
16019 assert_eq!(
16020 p.trim_walls(Lane::V1, 0, Edge::Start, SRC),
16021 Some(TrimWalls {
16022 lo: 0,
16023 hi: 3,
16024 lo_media: true,
16025 hi_media: false,
16026 }),
16027 "frame 0 is the head's first frame, and the clip's own minimum is the other wall"
16028 );
16029
16030 let mut p = Project::single(FILE, 9);
16031 assert!(p.split(5));
16032 assert_eq!(
16033 p.trim_walls(Lane::V1, 1, Edge::Start, SRC),
16034 Some(TrimWalls {
16035 lo: 5,
16036 hi: 8,
16037 lo_media: false,
16038 hi_media: false,
16039 }),
16040 "the head has room back to 0, but the piece in front stops it at 5"
16041 );
16042 }
16043
16044 /// A still has no media limit: its head and tail reach as far as the cap
16045 /// says, and that reach is never reported as the source's end.
16046 #[test]
16047 fn a_still_never_reports_media() {
16048 const STILL: &str = "/nonexistent/card.png";
16049 const CAP: &[u32] = &[60];
16050
16051 let mut p = Project::single(STILL, 20);
16052 assert!(p.lift(Lane::A1, 0), "a picture is silent");
16053 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
16054 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
16055
16056 assert_eq!(
16057 p.trim_walls(Lane::V1, 0, Edge::Start, CAP),
16058 Some(TrimWalls {
16059 lo: 60,
16060 hi: 119,
16061 lo_media: false,
16062 hi_media: false,
16063 }),
16064 );
16065 assert_eq!(
16066 p.trim_walls(Lane::V1, 0, Edge::End, CAP),
16067 Some(TrimWalls {
16068 lo: 101,
16069 hi: 160,
16070 lo_media: false,
16071 hi_media: false,
16072 }),
16073 );
16074 }
16075
16076 /// Linked halves trim as one: a link is one span on however many lanes, so
16077 /// the sound follows the picture's edge -- and the tightest wall of the two
16078 /// is what stops both.
16079 #[test]
16080 fn linked_halves_trim_together() {
16081 let mut p = three();
16082 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
16083 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
16084
16085 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
16086 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
16087 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
16088 assert!(
16089 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
16090 "either half drags it"
16091 );
16092 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
16093 links_are_consistent(&p.lanes).expect("one id per lane, one span");
16094
16095 // Something in the way on the *audio* lane stops the picture's tail as
16096 // well: the group can only go as far as its tightest member.
16097 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
16098 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
16099 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
16100 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
16101 links_are_consistent(&p.lanes).expect("still one span");
16102 }
16103
16104 /// An overwrite that cuts through a take on both of its lanes leaves the take whole: the head
16105 /// and the tail of the cut each keep one id shared across the lanes, so a trim of either lane
16106 /// still drags the other. A cut that would leave one lane's half without its partner detaches.
16107 #[test]
16108 fn an_overwrite_through_a_take_keeps_the_take_whole() {
16109 let mut p = three();
16110 assert!(p.edit_from_source(SourceEdit::Overwrite, 6, &[(Lane::V1, clip(0, 0, 2, 0)), (Lane::A1, clip(0, 0, 2, 0))]).is_ok());
16111 let head = p.lane(Lane::V1)[2].link;
16112 assert!(head.is_some(), "the head of the cut is still one take");
16113 assert_eq!(p.lane(Lane::A1)[2].link, head, "and so is the sound's head");
16114 assert_eq!(p.lane(Lane::V1)[4].link, p.lane(Lane::A1)[4].link, "the tail is one take too");
16115 assert!(p.lane(Lane::V1)[4].link.is_some());
16116 assert_ne!(p.lane(Lane::V1)[4].link, head, "the tail is a take of its own");
16117 links_are_consistent(&p.lanes).expect("one id per lane, one span");
16118
16119 // The head's sound follows the picture's trim, as it does everywhere else.
16120 assert!(p.trim(Lane::V1, 0, Edge::End, 2, SRC));
16121 assert_eq!(p.lane(Lane::A1)[0].end(), 2, "the sound followed the picture");
16122 links_are_consistent(&p.lanes).expect("still one span");
16123 }
16124
16125 /// A take that loses its last partner is detached: the survivor keeps an id
16126 /// that no other placement shares (a lone id, which the front-ends draw as
16127 /// detached), whichever edit took the partner away -- a lift, a split on some
16128 /// lanes -- and one undo puts the take back exactly.
16129 #[test]
16130 fn a_take_down_to_one_member_is_detached() {
16131 let mut p = three();
16132 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
16133 assert_eq!(p.lane(Lane::A1)[2].link, Some(link));
16134
16135 assert!(p.lift(Lane::V1, 2));
16136 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "the survivor keeps its id");
16137 assert!(p.undo());
16138 assert_eq!(p.lane(Lane::V1)[2].link, Some(link), "undo restores the picture's link");
16139 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "and the sound's");
16140
16141 // A split on the picture lane only: every half of the take is detached
16142 // (a fresh id of its own), in one snapshot.
16143 let history = p.history.len();
16144 assert!(p.split_on(7, &[Lane::V1]));
16145 assert_eq!(p.history.len(), history + 1, "one snapshot for the whole split");
16146 let ids: Vec<Option<u32>> = vec![
16147 p.lane(Lane::V1)[2].link,
16148 p.lane(Lane::V1)[3].link,
16149 p.lane(Lane::A1)[2].link,
16150 ];
16151 assert!(ids.iter().all(Option::is_some), "each half is detached: {ids:?}");
16152 assert!(ids[0] != ids[1] && ids[0] != ids[2] && ids[1] != ids[2], "{ids:?}");
16153 links_are_consistent(&p.lanes).expect("no two members share an id");
16154 assert!(p.undo());
16155 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "undo restores the take");
16156 assert_eq!(p.lane(Lane::V1)[2].link, Some(link));
16157 }
16158
16159 /// `swap` trades two placements of one lane: the first takes the second's
16160 /// start, the one between them ripples by the length difference, and the
16161 /// second lands where the first was (moved by that difference). The span
16162 /// keeps its length; a grouped placement refuses; one undo puts it back.
16163 #[test]
16164 fn swap_trades_two_clips_and_ripples_the_difference() {
16165 let mut p = Project::single(FILE, 1);
16166 let v = p.add_lane(LaneKind::Video);
16167 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
16168 assert!(p.place(v, 3, clip(3, 3, 5, 0)));
16169 assert!(p.place(v, 5, clip(5, 5, 9, 0)));
16170 // [0,3) len 3 and [5,9) len 4 trade places; the middle [3,5) moves by +1.
16171 assert!(p.swap(v, 0, 2));
16172 let got: Vec<(u32, u32, u32)> = p
16173 .lane(v)
16174 .iter()
16175 .map(|c| (c.start, c.frames(), c.in_frame))
16176 .collect();
16177 assert_eq!(got, vec![(0, 4, 5), (4, 2, 3), (6, 3, 0)]);
16178 assert!(p.undo());
16179 assert_eq!(p.lane(v)[0].start, 0);
16180 assert_eq!(p.lane(v)[0].frames(), 3, "one undo puts the order back");
16181
16182 // A grouped placement is not swapped apart.
16183 let mut t = three();
16184 assert!(!t.swap(Lane::V1, 0, 2), "the take is moved as a take");
16185 assert!(!t.swap(Lane::V1, 1, 1), "same clip");
16186 }
16187
16188 /// A clip whose link no other clip shares (what `ungroup` leaves) swaps like any other.
16189 #[test]
16190 fn swap_moves_a_detached_clip_but_not_a_take() {
16191 let mut p = three();
16192 assert!(p.ungroup(Lane::V1, 0) && p.ungroup(Lane::V1, 2), "both ends are detached first");
16193 assert!(p.lane(Lane::V1)[0].link.is_some(), "the lone link stays");
16194 assert!(p.swap(Lane::V1, 0, 2), "a lone link is not a take");
16195 assert_eq!(p.lane(Lane::V1)[0].in_frame, 5, "the later clip took the head");
16196 assert!(p.undo());
16197 // Clip 1 on V1 is still in its take with A1, so a swap that includes it is refused.
16198 let mut t = three();
16199 assert!(t.ungroup(Lane::V1, 0));
16200 assert!(!t.swap(Lane::V1, 0, 1), "a take still moves as a take");
16201 assert!(t.swap_in_place(Lane::V1, 0, 1).is_err(), "a take still moves as a take");
16202 }
16203
16204 /// The non-rippling swap: the two clips trade heads, the shorter leaves a gap
16205 /// where it was, and nothing between them moves. A clip moving into the slot
16206 /// the other vacates is allowed -- the check is on the finished positions.
16207 #[test]
16208 fn swap_in_place_exchanges_heads_and_moves_nothing_else() {
16209 let mut p = Project::single(FILE, 1);
16210 let v = p.add_lane(LaneKind::Video);
16211 assert!(p.place(v, 0, clip(0, 0, 2, 0)));
16212 assert!(p.place(v, 4, clip(4, 4, 5, 0)));
16213 assert!(p.place(v, 9, clip(9, 9, 12, 0)));
16214 p.swap_in_place(v, 0, 2).expect("the longer clip fits the 0..4 space");
16215 let got: Vec<(u32, u32, u32)> = p
16216 .lane(v)
16217 .iter()
16218 .map(|c| (c.start, c.frames(), c.in_frame))
16219 .collect();
16220 assert_eq!(got, vec![(0, 3, 9), (4, 1, 4), (9, 2, 0)]);
16221 assert!(p.undo());
16222 assert_eq!(p.lane(v)[0].in_frame, 0, "one undo restores the lane");
16223 assert_eq!(p.lane(v)[2].start, 9);
16224 }
16225
16226 /// A longer clip that cannot fit its new head is refused by name, and the lane
16227 /// is untouched -- nothing is half-swapped.
16228 #[test]
16229 fn swap_in_place_refuses_a_clip_that_would_overlap_by_name() {
16230 let mut p = Project::single(FILE, 1);
16231 let v = p.add_lane(LaneKind::Video);
16232 assert!(p.place(v, 0, clip(0, 0, 2, 0)));
16233 assert!(p.place(v, 2, clip(2, 2, 3, 0)));
16234 assert!(p.place(v, 4, clip(4, 4, 8, 0)));
16235 let before: Vec<(u32, u32)> = p.lane(v).iter().map(|c| (c.start, c.frames())).collect();
16236 let err = p.swap_in_place(v, 0, 2).expect_err("the 4-frame clip does not fit 0..2");
16237 assert!(err.to_string().contains("clip 1"), "names the clip in the way: {err}");
16238 let after: Vec<(u32, u32)> = p.lane(v).iter().map(|c| (c.start, c.frames())).collect();
16239 assert_eq!(before, after, "a refusal changes nothing");
16240 assert!(p.swap_in_place(v, 1, 1).is_err(), "the same clip twice");
16241 }
16242
16243 /// `ungroup` takes a whole take apart: each member gets an id of its own,
16244 /// so the take is no longer a group, and one undo puts it back.
16245 #[test]
16246 fn ungroup_gives_each_member_its_own_id() {
16247 let mut p = three();
16248 assert!(p.ungroup(Lane::A1, 2));
16249 assert_ne!(p.lane(Lane::A1)[2].link, p.lane(Lane::V1)[2].link);
16250 assert!(p.undo());
16251 assert!(p.lane(Lane::V1)[2].link.is_some(), "undo puts the take back");
16252 }
16253
16254 /// The bug this guards: grouping a take's picture with a clip from another
16255 /// take merges all four into one id, and ungrouping the picture must hand
16256 /// each take back whole -- not detach both halves of the first take too.
16257 #[test]
16258 fn ungroup_of_a_member_of_a_merged_group_keeps_its_take() {
16259 let v2 = Lane::new(LaneKind::Video, 1);
16260 let a2 = Lane::new(LaneKind::Audio, 1);
16261 let mut p = Project::single(FILE, 9);
16262 p.add_lane(LaneKind::Video);
16263 let other = p.lane(Lane::V1)[0].clone();
16264 assert!(p.place_take(v2, 20, other));
16265 let all = |p: &Project| -> Vec<Vec<Clip>> { p.lanes().iter().map(|&l| p.lane(l).to_vec()).collect() };
16266 let before = all(&p);
16267
16268 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16269 assert_eq!(p.lane(Lane::A1)[0].link, p.lane(v2)[0].link, "one group of four");
16270 assert!(p.ungroup(Lane::V1, 0));
16271 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the first take is still linked");
16272 assert_eq!(p.lane(v2)[0].link, p.lane(a2)[0].link, "the second take is still linked");
16273 assert_ne!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "and the two takes are apart");
16274
16275 // One undo is the merged group, and a second one the state before it.
16276 assert!(p.undo());
16277 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "the merge is back");
16278 assert!(p.undo());
16279 assert_eq!(all(&p), before, "undo is exact");
16280 }
16281
16282 /// A caption grouped onto a whole take: ungrouping the caption takes the
16283 /// caption off and leaves the take linked, the same as a loose clip would.
16284 #[test]
16285 fn ungroup_of_a_caption_on_a_take_keeps_the_take() {
16286 let mut p = Project::single(FILE, 9).with_subtitles(vec![subtitle_track()]);
16287 let subs = p.add_lane(LaneKind::Subtitle);
16288 let caption = SubClip { start: 0, frames: 9, track: 0, in_us: 0, out_us: 300_000, link: None };
16289 p.place_sub(subs, 0, caption).expect("the caption goes down");
16290 p.group_all(&[(Lane::V1, 0), (subs, 0)]).expect("a clip and a caption are a group");
16291 assert!(p.ungroup(subs, 0));
16292 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the take is still linked");
16293 let cap = p.sub_lane(subs)[0].link;
16294 assert!(cap.is_some() && cap != p.lane(Lane::V1)[0].link, "the caption is a half of its own");
16295 }
16296
16297 /// A take grouped with one loose clip: ungrouping the take's picture
16298 /// detaches the loose clip and leaves the take linked, and ungrouping the
16299 /// loose clip does the same from the other side.
16300 #[test]
16301 fn ungroup_of_a_take_with_a_loose_clip_detaches_only_the_loose_clip() {
16302 let v2 = Lane::new(LaneKind::Video, 1);
16303 let loose = |p: &Project| Clip { link: None, ..p.lane(Lane::V1)[0].clone() };
16304 let mut p = Project::single(FILE, 9);
16305 p.add_lane(LaneKind::Video);
16306 let mut clip = loose(&p);
16307 clip.start = 20;
16308 assert!(p.place(v2, 20, clip.clone()));
16309
16310 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16311 assert!(p.ungroup(v2, 0));
16312 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the take is still linked");
16313 assert!(p.lane(v2)[0].link.is_some() && p.lane(v2)[0].link != p.lane(Lane::V1)[0].link);
16314 assert!(p.undo());
16315
16316 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16317 assert!(p.ungroup(Lane::V1, 0));
16318 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "from the picture too");
16319 assert_ne!(p.lane(v2)[0].link, p.lane(Lane::V1)[0].link);
16320 assert!(links_are_consistent(&p.lanes).is_ok());
16321 }
16322
16323 /// A whole drag is one undo step -- the front-end commits once, at the
16324 /// release -- and an edge asked to stay where it is costs none at all.
16325 #[test]
16326 fn a_trim_is_one_undo_step() {
16327 let mut p = three();
16328 let before = shape(&p);
16329 let history = p.history.len();
16330
16331 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
16332 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
16333 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
16334 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
16335 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
16336 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
16337
16338 assert!(p.undo());
16339 assert_eq!(shape(&p), before, "both halves back, in one step");
16340 }
16341
16342 /// A moved half stays in its group: a link names a span, not a lane, so the
16343 /// picture on `V2` is still the same take as the sound under it on `A1`.
16344 #[test]
16345 fn move_clip_keeps_the_group() {
16346 let v2 = Lane::new(LaneKind::Video, 1);
16347 let mut p = three();
16348 p.add_lane(LaneKind::Video);
16349 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
16350 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
16351 assert!(p.move_clip(Lane::V1, 1, v2, 3));
16352 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
16353 links_are_consistent(&p.lanes).expect("one id per lane, one span");
16354 assert_eq!(
16355 p.lane(v2)[0].start,
16356 p.lane(Lane::A1)[1].start,
16357 "and still covers the same span as its sound"
16358 );
16359 }
16360
16361 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
16362 /// head of a lane, between two clips, inside a clip, past the last one,
16363 /// and on a lane holding nothing at all.
16364 #[test]
16365 fn gap_at_finds_the_hole_a_frame_sits_in() {
16366 let mut p = Project::single(FILE, 1);
16367 let v = p.add_lane(LaneKind::Video);
16368 // Empty lane: nothing before and nothing after -- not a gap, since
16369 // there is nothing to ripple toward.
16370 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
16371
16372 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
16373 // Before the only clip: the gap runs from the timeline's own head.
16374 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
16375 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
16376 // Inside the clip: not a gap.
16377 assert_eq!(p.gap_at(v, 5), None);
16378 assert_eq!(p.gap_at(v, 7), None);
16379 // Past the only clip: the open end of the lane, not a gap -- there is
16380 // nothing after it to slide back.
16381 assert_eq!(p.gap_at(v, 8), None);
16382 assert_eq!(p.gap_at(v, 100), None);
16383
16384 assert!(
16385 p.place(v, 12, clip(12, 0, 2, 0)),
16386 "a second clip at [12,14)"
16387 );
16388 // Between the two: the gap [8,12).
16389 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
16390 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
16391 assert_eq!(p.gap_at(v, 14), None, "still the open end");
16392
16393 assert!(
16394 p.place(v, 8, clip(8, 0, 4, 0)),
16395 "fills [8,12) exactly, meeting both neighbours"
16396 );
16397 assert_eq!(
16398 p.gap_at(v, 8),
16399 None,
16400 "adjacent clips leave no frame to name a gap"
16401 );
16402 assert_eq!(p.gap_at(v, 11), None);
16403 }
16404
16405 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
16406 /// menu named: the clip after the gap slides back on that lane, a clip on
16407 /// another lane at the very same frame range does not move, and the whole
16408 /// close is one press of undo.
16409 #[test]
16410 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
16411 let mut p = Project::single(FILE, 1);
16412 let v = p.add_lane(LaneKind::Video);
16413 let a = p.add_lane(LaneKind::Audio);
16414 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
16415 assert!(
16416 p.place(a, 0, clip(0, 0, 3, 0)),
16417 "A clip at [0,3) -- outside the video lane's gap and this scope"
16418 );
16419 let before = shape(&p);
16420 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
16421 assert_eq!((start, len), (0, 5));
16422 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
16423 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
16424 assert_eq!(
16425 p.lane(a)[0].start,
16426 0,
16427 "the untouched lane's clip did not move"
16428 );
16429 assert!(p.undo(), "one press undoes the whole close");
16430 assert_eq!(shape(&p), before, "back to exactly where it was");
16431 }
16432
16433 /// A clip carrying an explicit link id -- what a
16434 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
16435 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
16436 /// already builds inline.
16437 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
16438 Clip {
16439 speed_keys: Vec::new(),
16440 reversed: false,
16441 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
16442 angle: Default::default(),
16443 fade_in: 0,
16444 fade_out: 0,
16445 transition_out: 0,
16446 transition_kind: Default::default(),
16447 visualizer: 0,
16448 viz_paint: 0,
16449 gain_db: 0.0,
16450 gain_keys: Vec::new(),
16451 pan: 0,
16452 pitch: 0,
16453 transform_keys: Vec::new(),
16454 opacity_keys: Vec::new(),
16455 color_keys: Vec::new(),
16456 effects: Vec::new(),
16457 start,
16458 in_frame,
16459 out_frame,
16460 source: 0,
16461 link: Some(link),
16462 eq: None,
16463 color: None,
16464 transform: None,
16465 fit: FitPolicy::default(),
16466 speed: Speed::NORMAL,
16467 }
16468 }
16469
16470 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
16471 /// bordered by a linked take whose `A1` half is empty across the very
16472 /// same stretch widens the scope to both lanes, so the ripple carries the
16473 /// take rather than tearing it -- and one undo puts both halves back.
16474 #[test]
16475 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
16476 let sources = vec![Source::new(FILE, 0)];
16477 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16478 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16479 let mut p = Project::from_parts(
16480 sources,
16481 two(video, audio),
16482 Vec::new(),
16483 Vec::new(),
16484 Vec::new(),
16485 )
16486 .expect("valid parts");
16487 let before = shape(&p);
16488 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16489 assert_eq!(
16490 p.gap_at(Lane::A1, 3),
16491 Some((3, 2)),
16492 "the same stretch is empty on A1 too"
16493 );
16494
16495 let scope = p
16496 .gap_take_scope(Lane::V1, 3, 2)
16497 .expect("a matching gap on both halves widens the scope");
16498 assert_eq!(scope.len(), 2, "the take's other lane joins");
16499 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
16500
16501 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
16502 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
16503 assert_eq!(
16504 p.lane(Lane::A1)[1].start,
16505 3,
16506 "A1's far half rode along, in sync"
16507 );
16508 assert!(p.undo(), "one press undoes the whole close");
16509 assert_eq!(shape(&p), before, "back to exactly where it was");
16510 }
16511
16512 /// The real design question: a take whose gap is not the *same size* on
16513 /// both lanes cannot ripple by one number without pulling a lane's clip
16514 /// out from under the other's sync -- refused by name, with the frame
16515 /// naming which lane is out of step, rather than silently taking real
16516 /// media off the shorter side.
16517 #[test]
16518 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
16519 let sources = vec![Source::new(FILE, 0)];
16520 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16521 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
16522 // shorter than V1's [3,5) -- a legal offset-preserving group, and
16523 // still one take.
16524 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
16525 let p = Project::from_parts(
16526 sources,
16527 two(video, audio),
16528 Vec::new(),
16529 Vec::new(),
16530 Vec::new(),
16531 )
16532 .expect("valid parts");
16533 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16534 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
16535
16536 let err = p
16537 .gap_take_scope(Lane::V1, 3, 2)
16538 .expect_err("a mismatched gap cannot ripple by one number")
16539 .to_string();
16540 assert!(err.contains("A1"), "{err}");
16541 assert!(err.contains("out of sync"), "{err}");
16542 }
16543
16544 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
16545 /// there -- cannot close without cutting that audio out from under
16546 /// nothing asked to touch it: refused, not widened silently past.
16547 #[test]
16548 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
16549 let sources = vec![Source::new(FILE, 0)];
16550 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16551 // A1 plays through the whole span as one continuous clip, sharing
16552 // V1's first-half link: nothing empty at frame 3 there at all.
16553 let audio = vec![linked(0, 0, 9, 1)];
16554 let p = Project::from_parts(
16555 sources,
16556 two(video, audio),
16557 Vec::new(),
16558 Vec::new(),
16559 Vec::new(),
16560 )
16561 .expect("valid parts");
16562 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16563 assert_eq!(
16564 p.gap_at(Lane::A1, 3),
16565 None,
16566 "A1 plays through, no gap there"
16567 );
16568
16569 let err = p
16570 .gap_take_scope(Lane::V1, 3, 2)
16571 .expect_err("a solid partner cannot ripple with the gap")
16572 .to_string();
16573 assert!(err.contains("A1"), "{err}");
16574 assert!(err.contains("out of sync"), "{err}");
16575 }
16576
16577 /// The sweep is the single-gap close repeated on one lane, but measured once
16578 /// and applied from the right. The differing gap lengths here expose a
16579 /// front-to-back bug: the last clip would be cut against a stale frame after
16580 /// the first gap shifted it.
16581 #[test]
16582 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
16583 let mut p = Project::single(FILE, 1);
16584 let v = p.add_lane(LaneKind::Video);
16585 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
16586 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
16587 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
16588 let before = shape(&p);
16589
16590 assert_eq!(p.gap_count(v), 3);
16591 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
16592 assert_eq!(report.closed, 3);
16593 assert!(report.skipped.is_empty());
16594 assert_eq!(
16595 p.lane(v),
16596 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
16597 "all gaps closed without eating source frames"
16598 );
16599 assert!(p.undo(), "one undo for the whole sweep");
16600 assert_eq!(shape(&p), before);
16601 }
16602
16603 /// Empty, already-contiguous and tail-only lanes are not controls that do
16604 /// work. A single clip with a head gap does close, because there is a real
16605 /// placement to ripple back.
16606 #[test]
16607 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
16608 let mut p = Project::single(FILE, 9);
16609 let v = p.add_lane(LaneKind::Video);
16610 let history = p.history.len();
16611 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
16612 assert_eq!(
16613 report,
16614 GapSweep::default(),
16615 "an empty lane has no bounded gap"
16616 );
16617 assert_eq!(p.history.len(), history, "no undo step for a no-op");
16618
16619 let mut p = Project::single(FILE, 9);
16620 let v = p.add_lane(LaneKind::Video);
16621 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
16622 let before = shape(&p);
16623 let report = p
16624 .close_all_gaps_on_lane(v)
16625 .expect("single clip lane exists");
16626 assert_eq!(report.closed, 1, "the head gap closes");
16627 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
16628 assert!(p.undo());
16629 assert_eq!(shape(&p), before);
16630
16631 let mut p = Project::single(FILE, 9);
16632 let history = p.history.len();
16633 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
16634 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
16635 assert_eq!(p.history.len(), history);
16636
16637 let mut p = Project::single(FILE, 9);
16638 let v = p.add_lane(LaneKind::Video);
16639 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
16640 let history = p.history.len();
16641 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
16642 assert_eq!(
16643 report,
16644 GapSweep::default(),
16645 "the open-ended tail is not closed"
16646 );
16647 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
16648 assert_eq!(p.history.len(), history);
16649 }
16650
16651 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
16652 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
16653 /// while V1's [6,9) has only [6,8) empty on A1.
16654 #[test]
16655 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
16656 let sources = vec![Source::new(FILE, 0)];
16657 let video = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(9, 9, 11, 0)];
16658 let audio = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(8, 8, 11, 0)];
16659 let mut p = Project::from_parts(
16660 sources,
16661 two(video, audio),
16662 Vec::new(),
16663 Vec::new(),
16664 Vec::new(),
16665 )
16666 .expect("valid parts");
16667 let before = shape(&p);
16668
16669 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
16670 assert_eq!(report.closed, 1);
16671 assert_eq!(report.skipped.len(), 1);
16672 assert_eq!(report.skipped[0].start, 6);
16673 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
16674 assert!(
16675 report.skipped[0].reason.contains("out of sync"),
16676 "{report:?}"
16677 );
16678
16679 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
16680 assert_eq!(
16681 p.lane(Lane::A1)[1].start,
16682 2,
16683 "and its other half stayed in sync"
16684 );
16685 assert_eq!(
16686 p.lane(Lane::V1)[2].start,
16687 7,
16688 "the skipped later gap remains"
16689 );
16690 assert_eq!(
16691 p.lane(Lane::A1)[2].start,
16692 6,
16693 "A1's shorter gap remains shorter"
16694 );
16695 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
16696 assert!(p.undo(), "one undo restores every closed gap");
16697 assert_eq!(shape(&p), before);
16698 }
16699
16700 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
16701 /// their own caption storage: head gaps and gaps between cues count, an
16702 /// empty lane and the tail after the last cue do not.
16703 #[test]
16704 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
16705 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
16706 let s = p.add_lane(LaneKind::Subtitle);
16707 assert_eq!(
16708 p.gap_at(s, 0),
16709 None,
16710 "an empty subtitle lane has nothing to close"
16711 );
16712
16713 p.place_sub(s, 5, caption(0, 3))
16714 .expect("single cue at [5,8)");
16715 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
16716 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
16717 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
16718 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
16719
16720 p.place_sub(s, 12, caption(0, 2))
16721 .expect("second cue at [12,14)");
16722 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
16723 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
16724 assert_eq!(
16725 p.gap_at(s, 14),
16726 None,
16727 "tail after the last cue is still open-ended"
16728 );
16729 }
16730
16731 /// Closing a caption gap ripples the subtitle lane only. It is not a media
16732 /// take close, so the video and audio lanes keep their frame positions.
16733 #[test]
16734 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
16735 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
16736 let s = p.add_lane(LaneKind::Subtitle);
16737 p.place_sub(s, 5, caption(0, 3))
16738 .expect("single cue at [5,8)");
16739 let before_clips = shape(&p);
16740 let before_subs = p.sub_lane(s).to_vec();
16741
16742 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
16743 assert_eq!((start, len), (0, 5));
16744 p.cut_regions(&[(start, len)], &[s])
16745 .expect("caption lane gap closes");
16746
16747 assert_eq!(shape(&p), before_clips, "media lanes did not move");
16748 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
16749 assert!(p.undo(), "one undo restores the caption close");
16750 assert_eq!(shape(&p), before_clips);
16751 assert_eq!(p.sub_lane(s), before_subs);
16752 }
16753
16754 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
16755 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
16756 /// history entry for empty or already-contiguous lanes.
16757 #[test]
16758 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
16759 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
16760 let s = p.add_lane(LaneKind::Subtitle);
16761 let history = p.history.len();
16762 let report = p
16763 .close_all_gaps_on_lane(s)
16764 .expect("empty subtitle lane exists");
16765 assert_eq!(
16766 report,
16767 GapSweep::default(),
16768 "empty subtitle lane has no bounded gap"
16769 );
16770 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
16771
16772 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
16773 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
16774 p.place_sub(s, 14, caption(0, 1))
16775 .expect("middle gap [9,14), tail after 15");
16776 let before = p.sub_lane(s).to_vec();
16777
16778 assert_eq!(p.gap_count(s), 3);
16779 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
16780 assert_eq!(report.closed, 3);
16781 assert!(report.skipped.is_empty());
16782 assert_eq!(
16783 p.sub_lane(s),
16784 &[caption(0, 2), caption(2, 2), caption(4, 1)],
16785 "all bounded caption gaps closed without touching windows"
16786 );
16787 assert!(p.undo(), "one undo restores every caption gap");
16788 assert_eq!(p.sub_lane(s), before);
16789
16790 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
16791 let s = p.add_lane(LaneKind::Subtitle);
16792 p.place_sub(s, 0, caption(0, 3))
16793 .expect("contiguous at the head");
16794 let history = p.history.len();
16795 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
16796 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
16797 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
16798 assert_eq!(p.history.len(), history);
16799 }
16800
16801 #[test]
16802 fn ripple_delete_spans_partial_clips() {
16803 let mut p = three();
16804 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
16805 assert!(p.ripple_delete(2, 4));
16806 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
16807 assert_eq!(shape(&p)[1], shape(&p)[0]);
16808 assert_eq!(p.timeline_frames(), 5);
16809 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
16810 assert!(p.undo());
16811 assert_eq!(shape(&p), shape(&three()));
16812 // One that takes everything is a delete like any other: the timeline
16813 // empties, and the undo it cost brings it back whole.
16814 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
16815 assert_eq!(p.timeline_frames(), 0);
16816 assert!(
16817 !p.ripple_delete(0, 100),
16818 "and a delete with nothing left to take is not an undo step"
16819 );
16820 assert!(p.undo());
16821 assert_eq!(shape(&p), shape(&three()));
16822 }
16823
16824 /// A ripple trim closes the hole its trim leaves: the head cut from the middle clip goes, the
16825 /// clip keeps its start, and the last clip moves up by as much; an end edge moves what follows.
16826 #[test]
16827 fn ripple_trim_closes_the_hole_it_leaves() {
16828 let mut p = three();
16829 assert!(p.ripple_trim(Lane::V1, 1, Edge::Start, 4, &[9]));
16830 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 4, 5, 0), clip(4, 5, 9, 0)]);
16831 assert_eq!(shape(&p)[1], shape(&p)[0], "the linked audio moves with it");
16832 assert!(p.undo());
16833 assert_eq!(shape(&p), shape(&three()));
16834 assert!(p.ripple_trim(Lane::V1, 1, Edge::End, 4, &[9]));
16835 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(4, 5, 9, 0)]);
16836 }
16837
16838 /// Undo says the newest step's name and Redo the one it took back, and the names
16839 /// walk back and forth with the steps they belong to.
16840 #[test]
16841 fn labels_follow_undo_and_redo() {
16842 let mut p = Project::single(FILE, 270);
16843 let mark = p.step_mark();
16844 assert!(p.split(100));
16845 p.name_step(mark, "Split");
16846 let mark = p.step_mark();
16847 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16848 p.name_step(mark, "Volume");
16849 assert_eq!(p.undo_label(), Some("Volume"));
16850 assert_eq!(p.redo_label(), None);
16851
16852 assert!(p.undo());
16853 assert_eq!(p.undo_label(), Some("Split"));
16854 assert_eq!(p.redo_label(), Some("Volume"));
16855 assert!(p.undo());
16856 assert_eq!(p.undo_label(), None, "nothing left to take back");
16857 assert_eq!(p.redo_label(), Some("Split"));
16858
16859 assert!(p.redo());
16860 assert_eq!(p.redo_label(), Some("Volume"));
16861 assert!(p.redo());
16862 assert_eq!(p.redo_label(), None);
16863 assert_eq!(p.undo_label(), Some("Volume"));
16864 }
16865
16866 /// A name goes only on a step the named action pushed: an action that changed
16867 /// nothing, and one that pushed nothing at all, leave the step under them alone.
16868 #[test]
16869 fn a_no_op_takes_no_name_and_drops_none() {
16870 let mut p = Project::single(FILE, 270);
16871 assert!(p.split(100));
16872 let mark = p.step_mark();
16873 assert!(!p.set_lane_gain_db(Lane::A1, 0.0), "already at 0 dB");
16874 assert_eq!(p.undo_label(), None, "the unnamed split is still the newest step");
16875 p.name_step(mark, "Volume");
16876 assert_eq!(p.undo_label(), None, "the no-op pushed nothing to name");
16877
16878 let mark = p.step_mark();
16879 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16880 assert!(!p.set_lane_gain_db(Lane::A1, -3.0), "a repeat is a no-op");
16881 assert_eq!(p.undo_label(), None, "the real edit is unnamed so far");
16882 p.name_step(mark, "Volume");
16883 assert_eq!(p.undo_label(), Some("Volume"));
16884 assert_eq!(p.history_len(), 2);
16885 }
16886
16887 /// A step that names itself and then gets settled as a no-op carries its name away
16888 /// with it: the step under it keeps its own.
16889 #[test]
16890 fn a_settled_no_op_drops_its_name_with_its_step() {
16891 let mut p = Project::single(FILE, 270);
16892 let mark = p.step_mark();
16893 assert!(p.split(100));
16894 p.name_step(mark, "Split");
16895 let mark = p.step_mark();
16896 assert!(!p.set_lane_gain_db(Lane::A1, 0.0));
16897 assert_eq!(p.undo_label(), Some("Split"), "the no-op on top is not the step");
16898 p.name_step(mark, "Volume");
16899 assert_eq!(p.undo_label(), Some("Split"));
16900 assert_eq!(p.history_len(), 1);
16901 assert_eq!(p.redo_len(), 0);
16902 }
16903
16904 /// Names ride with their steps through the cap: the oldest step goes, every step kept
16905 /// still says what it did, and the one taken back stays named after a redo.
16906 #[test]
16907 fn labels_survive_the_cap_eviction() {
16908 let mut p = Project::single(FILE, 400);
16909 let frames = HISTORY_CAP as u32 + 5;
16910 for frame in 1..=frames {
16911 let mark = p.step_mark();
16912 assert!(p.split(frame));
16913 let name = if frame <= 3 { "Old" } else { "Split" };
16914 p.name_step(mark, name);
16915 }
16916 assert_eq!(p.history_len(), HISTORY_CAP);
16917 let mut taken = 0;
16918 while let Some(label) = p.undo_label().map(str::to_string) {
16919 assert_eq!(label, "Split", "a kept step keeps its own name");
16920 assert!(p.undo());
16921 taken += 1;
16922 }
16923 assert_eq!(taken, HISTORY_CAP);
16924 assert!(p.redo());
16925 assert_eq!(p.undo_label(), Some("Split"));
16926 assert_eq!(p.redo_label(), Some("Split"));
16927 }
16928
16929 /// A batch is one step and so one name: whatever the batch did, Undo names it once.
16930 #[test]
16931 fn a_batch_carries_one_label() {
16932 let mut p = Project::single(FILE, 270);
16933 let mark = p.step_mark();
16934 p.begin_batch();
16935 assert!(p.split(100));
16936 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16937 p.end_batch();
16938 p.name_step(mark, "Split, volume");
16939 assert_eq!(p.history_len(), 1, "the batch is one step");
16940 assert_eq!(p.undo_label(), Some("Split, volume"));
16941 assert!(p.undo());
16942 assert_eq!(p.redo_label(), Some("Split, volume"));
16943 }
16944
16945 #[test]
16946 fn undo_restores_exactly() {
16947 let mut p = three();
16948 let after_splits = shape(&p);
16949 assert!(p.delete(1));
16950 assert!(p.undo());
16951 assert_eq!(shape(&p), after_splits);
16952
16953 // walk all the way back through both splits, then run dry
16954 assert!(p.undo());
16955 assert_eq!(p.clips().len(), 2);
16956 assert!(p.undo());
16957 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
16958 assert!(!p.undo(), "empty history");
16959 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
16960 }
16961
16962 #[test]
16963 fn redo_restores_exactly() {
16964 let mut p = three();
16965 assert!(p.delete(1));
16966 let after_delete = p.parts();
16967 assert!(p.undo());
16968 assert!(p.redo());
16969 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
16970 assert!(!p.redo(), "empty redo stack");
16971 }
16972
16973 #[test]
16974 fn edit_after_undo_empties_redo() {
16975 let mut p = three();
16976 assert!(p.delete(1));
16977 assert!(p.undo());
16978 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
16979 assert!(p.split(1), "a fresh edit");
16980 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
16981 assert!(!p.redo(), "so redo has nothing left");
16982 }
16983
16984 #[test]
16985 fn redo_on_empty_stack_is_false() {
16986 let mut p = three();
16987 assert!(!p.redo(), "nothing has been undone yet");
16988 }
16989
16990 #[test]
16991 fn take_and_restore_redo_round_trips() {
16992 let mut p = three();
16993 assert!(p.delete(1));
16994 let after_delete = p.parts();
16995 assert!(p.undo());
16996 let cp = p.take_redo();
16997 assert_eq!(p.redo_len(), 0, "taken out with no step");
16998 assert!(p.split(1), "a trial edit, which clears what is left");
16999 p.restore_redo(cp);
17000 assert_eq!(p.redo_len(), 1, "the stack the trial found is back");
17001 assert!(p.redo());
17002 assert_eq!(p.parts(), after_delete, "and it still redoes to the same state");
17003 }
17004
17005 #[test]
17006 fn held_history_evicts_nothing_until_released() {
17007 let mut p = Project::single(FILE, 400);
17008 for frame in 1..=HISTORY_CAP as u32 {
17009 assert!(p.split(frame));
17010 }
17011 p.hold_history(true);
17012 for frame in 101..=103 {
17013 assert!(p.split(frame));
17014 }
17015 assert_eq!(p.history.len(), HISTORY_CAP + 3, "a held trial evicts nothing");
17016 for _ in 0..3 {
17017 assert!(p.undo());
17018 }
17019 assert_eq!(p.history.len(), HISTORY_CAP, "the trial rolled back, the cap is still the same");
17020 p.hold_history(false);
17021 assert_eq!(p.history.len(), HISTORY_CAP);
17022 for frame in 101..=103 {
17023 assert!(p.split(frame));
17024 }
17025 p.hold_history(true);
17026 for frame in 110..=112 {
17027 assert!(p.split(frame));
17028 }
17029 assert_eq!(p.history.len(), HISTORY_CAP + 3);
17030 p.hold_history(false);
17031 assert_eq!(p.history.len(), HISTORY_CAP, "releasing trims back to the cap");
17032 }
17033
17034 /// Past the cap the *oldest* step goes, so a long session undoes exactly
17035 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
17036 #[test]
17037 fn history_stops_at_the_cap() {
17038 let mut p = Project::single(FILE, 400);
17039 for frame in 1..=150 {
17040 assert!(p.split(frame), "split {frame} is an edit");
17041 }
17042 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
17043 for step in 0..HISTORY_CAP {
17044 assert!(p.undo(), "undo {step} is inside the cap");
17045 }
17046 assert!(!p.undo(), "and the 101st has nothing left to take");
17047 // 100 undos off 150 splits is the timeline after the 50th: the older
17048 // steps were dropped, not the newer ones.
17049 assert_eq!(p.clips().len(), 51);
17050 }
17051
17052 /// The push count keeps rising past the cap, where `history_len` stops, so a
17053 /// caller can tell how many snapshots a batch pushed even at the cap.
17054 #[test]
17055 fn undo_pushes_counter_keeps_counting_past_the_cap() {
17056 let mut p = Project::single(FILE, 400);
17057 let start = p.history_pushes();
17058 for frame in 1..=HISTORY_CAP as u32 + 5 {
17059 assert!(p.split(frame));
17060 }
17061 assert_eq!(p.history.len(), HISTORY_CAP, "the length has saturated");
17062 assert_eq!(p.history_pushes() - start, HISTORY_CAP as u64 + 5);
17063 assert!(p.undo());
17064 assert_eq!(
17065 p.history_pushes() - start,
17066 HISTORY_CAP as u64 + 5,
17067 "an undo pushes nothing"
17068 );
17069 }
17070
17071 /// Undo/redo by hand across a split must never merge two takes into one
17072 /// group by reusing an id.
17073 #[test]
17074 fn group_ids_are_never_reused() {
17075 let mut p = Project::single(FILE, 9);
17076 assert!(p.split(3));
17077 let first = p.clips()[1].link;
17078 assert!(p.undo());
17079 assert!(p.split(5));
17080 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
17081 }
17082
17083 #[test]
17084 fn segments_from_reads_the_audio_lane() {
17085 let p = three();
17086 // mid-clip: partial first segment, whole clips after it
17087 assert_eq!(
17088 p.segments_from(4, FPS),
17089 vec![
17090 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
17091 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
17092 ]
17093 );
17094 // on a boundary: nothing partial
17095 assert_eq!(
17096 p.segments_from(3, FPS),
17097 vec![
17098 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
17099 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
17100 ]
17101 );
17102 // from the top: one entry per clip
17103 assert_eq!(p.segments_from(0, FPS).len(), 3);
17104 // last clip only
17105 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
17106 // past the end / unusable fps
17107 assert!(p.segments_from(9, FPS).is_empty());
17108 assert!(p.segments_from(0, 0.0).is_empty());
17109 assert!(p.segments_from(0, f64::NAN).is_empty());
17110 }
17111
17112 #[test]
17113 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
17114 let mut p = three();
17115 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
17116 assert_eq!(
17117 p.segments_from(0, FPS),
17118 vec![
17119 (Some(0), 0.0, 3.0 / 30.0),
17120 (None, 0.0, 2.0 / 30.0),
17121 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
17122 ]
17123 );
17124 // The list still covers exactly the timeline: that is what stops the
17125 // master clock stalling at the hole.
17126 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
17127 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
17128 // Starting inside the gap trims the silence, not the clip after it.
17129 assert_eq!(
17130 p.segments_from(4, FPS),
17131 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
17132 );
17133 // ...and a lane that is nothing but gap is a run of silence.
17134 assert!(p.lift(Lane::A1, 0));
17135 assert!(p.lift(Lane::A1, 0));
17136 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
17137 }
17138
17139 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
17140 /// of source 0 then [0,4) of source 1.
17141 fn two_sources() -> Project {
17142 let mut p = three();
17143 let s = p.import(FILE2, 0);
17144 assert_eq!(s, 1);
17145 assert!(p.append_clip(s, 4));
17146 p
17147 }
17148
17149 #[test]
17150 fn import_dedups_and_appends() {
17151 let mut p = Project::single(FILE, 9);
17152 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
17153 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
17154 assert_eq!(p.import(FILE2, 0), 1);
17155 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
17156 // ...but the same file on another audio stream is another source: it is
17157 // what a clip names, and a clip plays exactly one stream.
17158 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
17159 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
17160 assert_eq!(p.sources()[2].audio_stream, 1);
17161 assert!(p.append_clip(2, 4), "a stream entry is placeable");
17162 assert!(p.undo());
17163 assert_eq!(p.sources().len(), 3);
17164 assert!(!p.append_clip(3, 5), "unknown source index");
17165 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
17166
17167 // Two spellings of one real file are one source: this is the case the
17168 // raw-path comparison above would get wrong.
17169 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
17170 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
17171 let mut p = Project::single(here, 9);
17172 assert_eq!(p.import(detour, 0), 0);
17173 assert_eq!(p.sources().len(), 1);
17174 }
17175
17176 #[test]
17177 fn append_clip_is_one_undo_step() {
17178 let mut p = two_sources();
17179 assert_eq!(p.timeline_frames(), 13);
17180 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
17181 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
17182 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
17183 assert!(p.undo());
17184 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
17185 assert_eq!(
17186 p.sources().len(),
17187 2,
17188 "the orphan source entry stays -- indexes are forever"
17189 );
17190 // ...and it is still usable, so a redo-by-hand costs no reimport.
17191 assert!(p.append_clip(1, 0));
17192 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
17193 }
17194
17195 #[test]
17196 fn edits_carry_the_source_along() {
17197 let mut p = two_sources();
17198 // A split inside the second source splits into two source-1 clips.
17199 assert!(p.split(11));
17200 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
17201 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
17202
17203 // A source-1 clip pasted into source-0 territory keeps its file, and so
17204 // does the source-0 half that got split off around it.
17205 let copied = p.clips()[4].clone();
17206 assert!(p.paste(1, copied));
17207 assert_eq!(p.clips()[1].source, 1);
17208 assert_eq!(p.clips()[1].in_frame, 2);
17209 assert_eq!(p.clips()[2].source, 0);
17210 assert!(p.undo());
17211 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
17212 }
17213
17214 #[test]
17215 fn segments_from_names_the_source() {
17216 let p = two_sources();
17217 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
17218 assert_eq!(
17219 p.segments_from(4, FPS),
17220 vec![
17221 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
17222 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
17223 (Some(1), 0.0, 4.0 / 30.0),
17224 ]
17225 );
17226 // Mid-clip in source 1: only that source is left.
17227 assert_eq!(
17228 p.segments_from(10, FPS),
17229 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
17230 );
17231 assert!(p.segments_from(13, FPS).is_empty());
17232 // Segments still cover exactly the timeline across the join.
17233 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
17234 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
17235 }
17236
17237 #[test]
17238 fn segments_follow_deletes_and_fps() {
17239 let mut p = three();
17240 assert!(p.delete(0));
17241 // source seconds, not timeline: deleting the head does not shift them
17242 let segs = p.segments_from(0, 25.0);
17243 assert_eq!(
17244 segs,
17245 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
17246 );
17247 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
17248 assert!(
17249 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
17250 "segments must cover exactly the timeline: {played}"
17251 );
17252 }
17253
17254 #[test]
17255 fn every_source_is_saved_in_session_order_and_the_clips_keep_theirs() {
17256 // Import a second file, undo it: source 1 is now an orphan. It is kept
17257 // anyway -- an import is not an undo step, so the library entry stays
17258 // at the index a reload will look for it at.
17259 let mut p = two_sources();
17260 assert!(p.undo());
17261 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17262 assert_eq!(
17263 sources,
17264 vec![Source::new(FILE, 0), Source::new(FILE2, 0)],
17265 "the orphan is kept, in session order"
17266 );
17267 assert!(eq.is_empty(), "and a project with no equalizer writes none");
17268 assert!(color.is_empty(), "nor a colour it never graded with");
17269 assert_eq!(
17270 lanes,
17271 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
17272 "the clips are untouched"
17273 );
17274
17275 // Three sources where only the middle one is unused: all three are
17276 // saved, in order, and the clip keeps the index it was given -- 2 here,
17277 // not renumbered down to 1. (The clip from `single` is still source 0.)
17278 let mut p = Project::single(FILE, 9);
17279 assert_eq!(p.import(FILE2, 0), 1);
17280 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
17281 assert!(p.append_clip(2, 4));
17282 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17283 assert_eq!(
17284 sources,
17285 vec![
17286 Source::new(FILE, 0),
17287 Source::new(FILE2, 0),
17288 Source::new("/nonexistent/c.mp4", 0)
17289 ]
17290 );
17291 assert_eq!(
17292 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
17293 [0, 2]
17294 );
17295 // ...and what comes out is loadable, with the same timeline.
17296 let reloaded =
17297 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
17298 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
17299 assert_eq!(reloaded.sources().len(), 3);
17300 }
17301
17302 /// Taking a file out of the library: refused by name -- lanes and counts --
17303 /// while a clip still plays from it, and once nothing does, the entry goes
17304 /// and every clip that indexed past it is renumbered onto the short list.
17305 /// A project rebuilt from parts keeps each source's bin and star (the loader's own door).
17306 #[test]
17307 fn from_parts_keeps_a_sources_bin_and_star() {
17308 let mut one = Source::new(FILE, 0);
17309 one.fav = true;
17310 one.bin = 7;
17311 let lanes = vec![(LaneKind::Video, vec![clip(0, 0, 10, 0)]), (LaneKind::Audio, vec![clip(0, 0, 10, 0)])];
17312 let p = Project::from_parts(vec![one], lanes, vec![], vec![], Vec::new()).expect("valid parts");
17313 assert!(p.sources()[0].fav);
17314 assert_eq!(p.sources()[0].bin, 7);
17315 }
17316
17317 #[test]
17318 fn bins_and_favourites_follow_the_usual_edit_rules() {
17319 let mut p = two_sources();
17320 let a = p.create_bin(" Interviews ", 0).expect("makes a bin");
17321 assert_eq!(p.bins()[0].name, "Interviews");
17322 assert!(p.create_bin("interviews", 0).is_err(), "no twin at one place");
17323 let b = p.create_bin("Day 1", a).expect("one level of nesting");
17324 assert!(p.create_bin("deeper", b).is_err(), "no third level");
17325 assert!(p.create_bin(" ", 0).is_err() && p.create_bin("a\nb", 0).is_err() && p.create_bin("x", 99).is_err());
17326 assert_eq!(p.move_to_bin(&[0, 1, 1], b), Ok(2));
17327 assert_eq!(p.move_to_bin(&[0], b), Ok(0), "no change, no history");
17328 assert!(p.move_to_bin(&[7], b).is_err() && p.move_to_bin(&[0], 42).is_err());
17329 assert_eq!(p.set_favourite(&[1], true), Ok(1));
17330 assert_eq!(p.set_favourite(&[1], true), Ok(0));
17331 assert!(p.sources()[1].fav && p.sources()[1].bin == b);
17332 assert_eq!(p.rename_bin(b, "Day one"), Ok(true));
17333 assert_eq!(p.rename_bin(b, "Day one"), Ok(false));
17334 // Undo walks back one step at a time: rename, star, move, then the bins themselves.
17335 assert!(p.undo() && p.bins()[1].name == "Day 1");
17336 assert!(p.undo() && !p.sources()[1].fav);
17337 assert!(p.undo() && p.sources()[0].bin == 0);
17338 assert!(p.redo() && p.sources()[0].bin == b);
17339 // Removing the outer bin keeps what it held: sources go up, inner bins to the top.
17340 assert_eq!(p.remove_bin(a), Ok(0));
17341 assert_eq!(p.bins().len(), 1);
17342 assert_eq!(p.bins()[0].parent, 0);
17343 assert_eq!(p.remove_bin(b), Ok(2));
17344 assert!(p.sources().iter().all(|s| s.bin == 0));
17345 assert!(p.undo() && p.sources()[0].bin == b && p.bins().len() == 1);
17346 assert!(p.undo() && p.bins().len() == 2 && p.bins()[1].parent == a);
17347 // A source's identity is its file and stream, not its star.
17348 assert_eq!(p.sources()[0], Source::new(&p.sources()[0].path, 0));
17349 }
17350
17351 #[test]
17352 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
17353 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
17354 // plus a second stream of FILE as source 2 with a take of its own.
17355 let mut p = two_sources();
17356 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
17357 assert!(p.append_clip(2, 4));
17358
17359 let refusal = p
17360 .remove_source(1)
17361 .expect_err("a source with clips on it cannot go")
17362 .to_string();
17363 assert!(refusal.contains(FILE2), "names the file: {refusal}");
17364 assert!(
17365 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
17366 "names the lanes holding it: {refusal}"
17367 );
17368 assert!(refusal.contains("still plays"), "{refusal}");
17369 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
17370 assert_eq!(shape(&p)[0][3].source, 1);
17371
17372 // Delete FILE2's take -- the whole span, on every lane -- and the entry
17373 // is free to go. Source 2's clips become source 1's.
17374 assert!(p.delete_in(Lane::V1, 3));
17375 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
17376 p.remove_source(1).expect("nothing plays FILE2 any more");
17377 assert_eq!(
17378 p.sources(),
17379 [Source::new(FILE, 0), Source::new(FILE, 1)],
17380 "the middle entry is gone"
17381 );
17382 assert_eq!(
17383 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
17384 [0, 0, 0, 1],
17385 "the clips past it renumbered"
17386 );
17387 assert_eq!(
17388 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
17389 [0, 0, 0, 1],
17390 "on every lane"
17391 );
17392 // What is left is a project that still loads, which is the whole point
17393 // of renumbering rather than leaving a hole.
17394 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17395 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
17396 }
17397
17398 /// The two edges of a removal: it retires the undo stack (the corner-cut on
17399 /// [`Project::remove_source`]), and the last entry goes like any other
17400 /// once nothing plays it -- a project may name no file at all.
17401 #[test]
17402 fn relink_is_one_undo_step_and_undo_puts_the_old_path_back() {
17403 let mut p = two_sources();
17404 let old = p.sources()[1].path.clone();
17405 let new = Source::new(FILE, 0).path;
17406 let depth = p.history_len();
17407 p.relink_source(1, Path::new(FILE)).expect("relinks");
17408 assert_eq!(p.sources()[1].path, new);
17409 assert_eq!(p.history_len(), depth + 1, "one step");
17410 assert!(p.undo());
17411 assert_eq!(p.sources()[1].path, old, "undo points back at the old file");
17412 assert!(p.redo());
17413 assert_eq!(p.sources()[1].path, new, "redo re-points it");
17414 p.relink_source(1, Path::new(FILE)).expect("the path it has");
17415 assert_eq!(p.history_len(), depth + 1, "a relink to the same path is no step");
17416 assert!(p.relink_source(9, Path::new(FILE)).is_err(), "no source 9");
17417 }
17418
17419 #[test]
17420 fn undo_keeps_a_source_imported_after_the_step() {
17421 let mut p = three();
17422 assert_eq!(p.import(FILE2, 0), 1);
17423 assert!(p.undo(), "the last split");
17424 assert_eq!(p.sources().len(), 2, "the import outlives the undo, as an import does");
17425 assert_eq!(p.sources()[1].path, Source::new(FILE2, 0).path);
17426 assert!(p.redo());
17427 assert_eq!(p.sources().len(), 2);
17428 }
17429
17430 #[test]
17431 fn adopt_as_step_takes_the_other_timeline_and_undo_gives_this_one_back() {
17432 let geometry = |p: &Project| -> Vec<Vec<(u32, u32, u32, usize)>> {
17433 p.lanes()
17434 .into_iter()
17435 .map(|l| p.lane(l).iter().map(|c| (c.start, c.in_frame, c.out_frame, c.source)).collect())
17436 .collect()
17437 };
17438 let mut p = three();
17439 assert!(p.set_eq(Lane::A1, 0, Some(band_at(7))), "this project's own table entry");
17440 let mut other = two_sources();
17441 assert!(other.set_eq(Lane::A1, 0, Some(band_at(2))));
17442 let (want, want_eq) = (geometry(&other), other.eq_of(Lane::A1, 0).cloned());
17443 let saved = geometry(&p);
17444 let depth = p.history_len();
17445 assert!(p.adopt_as_step(&other));
17446 assert_eq!(p.history_len(), depth + 1, "one step");
17447 assert_eq!(geometry(&p), want, "the other timeline");
17448 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), want_eq, "its effects read from the appended table");
17449 assert!(p.undo());
17450 assert_eq!(geometry(&p), saved);
17451 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), Some(band_at(7)), "and this project's own table is still there");
17452 assert!(p.redo());
17453 assert_eq!(geometry(&p), want);
17454 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), want_eq);
17455 assert_eq!(p.sources()[1].path, other.sources()[1].path, "the other sources come with it");
17456 }
17457
17458 /// A recovery takes the autosave's markers with its timeline, and undo gives back the
17459 /// markers this project had: the marker list is part of what a step restores.
17460 #[test]
17461 fn adopt_as_step_carries_the_markers_of_the_other_timeline() {
17462 let marker = |frame: u32, name: &str| Marker {
17463 frame,
17464 length: 0,
17465 name: name.into(),
17466 note: String::new(),
17467 color: MarkerColor::Red,
17468 };
17469 let mut p = three();
17470 assert!(p.add_marker(marker(4, "mine")).is_ok());
17471 let mut other = two_sources();
17472 assert!(other.add_marker(marker(9, "theirs")).is_ok());
17473 assert!(p.adopt_as_step(&other));
17474 let names: Vec<&str> = p.markers().iter().map(|m| m.name.as_str()).collect();
17475 assert_eq!(names, ["theirs"], "the other timeline's markers");
17476 assert!(p.undo());
17477 let names: Vec<&str> = p.markers().iter().map(|m| m.name.as_str()).collect();
17478 assert_eq!(names, ["mine"], "undo gives this project's markers back");
17479 }
17480
17481 #[test]
17482 fn revision_walks_back_with_undo_and_never_repeats() {
17483 let mut p = three();
17484 let saved = p.revision();
17485 assert!(p.delete_in(Lane::V1, 2));
17486 let edited = p.revision();
17487 assert_ne!(edited, saved, "an edit moves the timeline off the saved state");
17488 assert!(p.undo());
17489 assert_eq!(p.revision(), saved, "undo back to the saved timeline gives its id back");
17490 assert!(p.redo());
17491 assert_eq!(p.revision(), edited, "redo walks forward to the same id");
17492 // A new edit after an undo is a state of its own: it must not read as the saved one.
17493 assert!(p.undo());
17494 assert!(p.delete_in(Lane::V1, 0));
17495 assert_ne!(p.revision(), saved, "a branch off the saved timeline is not the saved one");
17496 assert_ne!(p.revision(), edited);
17497 assert!(!p.redo(), "the branch cleared the redo stack");
17498 assert_eq!(p.revision(), p.revision(), "reading is not an edit");
17499 }
17500
17501 #[test]
17502 fn revision_moves_once_per_batch_step_and_undo_takes_the_whole_batch_back() {
17503 let mut p = three();
17504 let saved = p.revision();
17505 p.begin_batch();
17506 assert!(p.delete_in(Lane::V1, 2));
17507 let first = p.revision();
17508 assert!(p.delete_in(Lane::V1, 1));
17509 assert_ne!(p.revision(), first, "each edit in a batch is a new state");
17510 p.end_batch();
17511 assert!(p.undo());
17512 assert_eq!(p.revision(), saved, "one undo takes the whole batch back to the saved id");
17513 }
17514
17515 #[test]
17516 fn revision_of_a_recovery_step_is_undone_back_to_the_timeline_it_replaced() {
17517 let mut current = three();
17518 assert!(current.delete_in(Lane::V1, 2));
17519 let edited = current.revision();
17520 let other = two_sources();
17521 assert!(current.adopt_as_step(&other));
17522 assert_ne!(current.revision(), edited, "the other timeline is a new state");
17523 assert!(current.undo());
17524 assert_eq!(current.revision(), edited, "undo gives back the timeline it replaced, by its id");
17525 }
17526
17527 #[test]
17528 fn remove_source_retires_undo_and_empties_the_library() {
17529 let mut p = two_sources();
17530 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
17531 assert!(!p.history.is_empty(), "there is something to undo");
17532 p.remove_source(1).expect("nothing plays FILE2");
17533 assert!(
17534 p.history.is_empty(),
17535 "a snapshot naming the removed source must not survive it"
17536 );
17537 assert!(!p.undo(), "and so there is nothing left to undo");
17538
17539 // The last file standing is held to the one rule every row is -- what
17540 // plays cannot go -- and to no other.
17541 assert_eq!(p.sources().len(), 1);
17542 let refusal = p
17543 .remove_source(0)
17544 .expect_err("its clips are still on the lanes")
17545 .to_string();
17546 assert!(refusal.contains("still plays"), "{refusal}");
17547 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
17548 while p.delete_in(Lane::V1, 0) {}
17549 p.remove_source(0)
17550 .expect("the last row goes like any other");
17551 assert!(
17552 p.sources().is_empty(),
17553 "a project may name no file at all: an empty library over an empty timeline"
17554 );
17555 assert_eq!(p.timeline_frames(), 0);
17556 assert!(
17557 p.remove_source(0).is_err(),
17558 "and an index that is not there is refused, not panicked on"
17559 );
17560 }
17561
17562 /// A clip's equalizer is the clip's: it survives every edit that copies a
17563 /// placement, and it comes back with an undo.
17564 #[test]
17565 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
17566 let mut p = three();
17567 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
17568 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
17569 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17570 assert!(
17571 p.eq_of(Lane::V1, 0).is_none(),
17572 "one clip, not the lane above"
17573 );
17574
17575 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
17576 assert!(p.split(1));
17577 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17578 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
17579 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
17580
17581 // A clipboard copy carries it -- onto another lane, at that.
17582 let copied = p.lane(Lane::A1)[1].clone();
17583 assert!(p.place(Lane::V1, 20, copied));
17584 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
17585 assert!(p.undo());
17586 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
17587
17588 // ...and a change to one is one undo step, in both directions.
17589 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
17590 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
17591 assert!(p.undo());
17592 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17593 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
17594 assert!(p.eq_of(Lane::A1, 0).is_none());
17595 assert!(p.undo());
17596 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17597
17598 // Two refusals, neither of which costs an undo step.
17599 let mut nan = band_at(1);
17600 nan.bands[0].q = f32::INFINITY;
17601 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
17602 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
17603 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17604 assert!(p.undo());
17605 assert_eq!(
17606 p.lane(Lane::A1).len(),
17607 3,
17608 "one step back is before the split"
17609 );
17610 assert!(p.undo());
17611 assert!(
17612 p.eq_of(Lane::A1, 0).is_none(),
17613 "and the next is before the setting: the refusals pushed none"
17614 );
17615 }
17616
17617 /// The table is append-only within a session, exactly as the sources are, so
17618 /// an undone setting is still in it -- and a save is where it goes.
17619 #[test]
17620 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
17621 let mut p = three();
17622 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
17623 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
17624 assert!(p.undo(), "back to the first setting");
17625 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
17626
17627 let (_, lanes, eq, _, _) = p.without_orphan_sources();
17628 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
17629 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
17630 assert_eq!(lanes[0].1[1].eq, None);
17631
17632 // One curve on three clips is one entry: settings that are equal share.
17633 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
17634 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
17635 let (_, lanes, eq, _, _) = p.without_orphan_sources();
17636 assert_eq!(eq.len(), 1, "equal settings share their entry");
17637 assert_eq!(lanes[1].1[2].eq, Some(0));
17638 reloads(&p, "an equalizer that outlived an undo");
17639 }
17640
17641 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
17642 /// grade is the clip's, through every edit that copies a placement.
17643 #[test]
17644 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
17645 let mut p = three();
17646 assert!(
17647 p.color_of(Lane::V1, 0).is_none(),
17648 "a fresh clip is ungraded"
17649 );
17650 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
17651 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17652 assert!(
17653 p.color_of(Lane::A1, 0).is_none(),
17654 "one clip, not the lane below"
17655 );
17656 assert!(
17657 p.eq_of(Lane::V1, 0).is_none(),
17658 "and a grade is not an equalizer"
17659 );
17660
17661 // Cutting a graded clip must not grade half of it: both halves inherit.
17662 assert!(p.split(1));
17663 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17664 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
17665 assert!(
17666 p.color_of(Lane::V1, 2).is_none(),
17667 "the clip after it is ungraded"
17668 );
17669
17670 // A clipboard copy carries it -- onto another lane, at that.
17671 let copied = p.lane(Lane::V1)[1].clone();
17672 assert!(p.place(Lane::A1, 20, copied));
17673 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
17674 assert!(p.undo());
17675 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
17676
17677 // ...and a change to one is one undo step, in both directions.
17678 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
17679 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
17680 assert!(p.undo());
17681 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17682 assert!(
17683 p.set_color(Lane::V1, 0, None),
17684 "and taking it off is an edit"
17685 );
17686 assert!(p.color_of(Lane::V1, 0).is_none());
17687 assert!(p.undo());
17688 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17689
17690 // Two refusals, neither of which costs an undo step.
17691 let nan = ColorParams {
17692 contrast: f32::NAN,
17693 ..grade_at(1)
17694 };
17695 assert!(
17696 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
17697 "no clip there"
17698 );
17699 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
17700 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17701 assert!(p.undo());
17702 assert_eq!(
17703 p.lane(Lane::V1).len(),
17704 3,
17705 "one step back is before the split"
17706 );
17707 assert!(p.undo());
17708 assert!(
17709 p.color_of(Lane::V1, 0).is_none(),
17710 "and the next is before the grade: the refusals pushed none"
17711 );
17712 }
17713
17714 /// A slider drag is one gesture: the press snapshots, every sample after it
17715 /// only regrades, and the single undo lands on what the clip was *before*
17716 /// the hand touched it -- not one step back down the drag.
17717 #[test]
17718 fn a_whole_colour_drag_undoes_in_one_step() {
17719 let mut p = three();
17720 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
17721 for n in 2..=8 {
17722 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
17723 }
17724 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
17725 assert!(p.undo());
17726 assert!(
17727 p.color_of(Lane::V1, 0).is_none(),
17728 "one undo is the whole gesture, back to ungraded"
17729 );
17730
17731 // The live write refuses what the snapshotting one refuses, and a
17732 // refusal still costs no history either way.
17733 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
17734 assert!(!p.set_color_live(
17735 Lane::V1,
17736 0,
17737 Some(ColorParams {
17738 contrast: f32::NAN,
17739 ..grade_at(1)
17740 })
17741 ));
17742 assert!(p.undo());
17743 assert_eq!(
17744 p.lane(Lane::V1).len(),
17745 2,
17746 "the next step back is the split before the drag: no sample pushed one"
17747 );
17748 }
17749
17750 /// A drag across the colour wheel is one gesture -- the look's twin of
17751 /// [`a_whole_colour_drag_undoes_in_one_step`]: the press snapshots, every
17752 /// sample after it only repaints, and the single undo lands on the look
17753 /// the clip had *before* the hand touched it. The committing setter is
17754 /// still exactly one step, refusals included.
17755 /// A LUT is relinked like media: every clip naming the old path moves to the
17756 /// new one in one undo step, a missing file is a named problem rather than an
17757 /// error, and keys leave the look alone.
17758 #[test]
17759 fn a_lut_relinks_in_one_step_and_a_missing_one_is_named() {
17760 let dir = std::env::temp_dir().join(format!("edith-relink-lut-{}", std::process::id()));
17761 std::fs::create_dir_all(&dir).unwrap();
17762 let good = dir.join("good.cube");
17763 std::fs::write(&good, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap();
17764 let gone = dir.join("gone.cube");
17765 let mut p = three();
17766 let with = |path: &Path| ColorParams {
17767 look: crate::color::Look { lut: Some(crate::cube::LutRef::open(path)), ..Default::default() },
17768 ..Default::default()
17769 };
17770 assert!(p.set_color(Lane::V1, 0, Some(with(&gone))));
17771 assert!(p.set_color(Lane::V1, 1, Some(with(&gone))));
17772 let problems = p.lut_problems();
17773 assert_eq!(problems.len(), 1, "one file, named once");
17774 assert!(problems[0].0 == gone && problems[0].1.contains("cannot read"));
17775 assert_eq!(p.relink_lut(&dir.join("other.cube"), &good), 0, "nothing names it");
17776 assert_eq!(p.relink_lut(&gone, &good), 2);
17777 assert!(p.lut_problems().is_empty());
17778 assert_eq!(p.color_of(Lane::V1, 1).and_then(|c| c.look.lut).map(|r| r.path()), Some(good.clone()));
17779 assert!(p.undo());
17780 assert_eq!(p.lut_problems().len(), 1, "one undo puts both back");
17781 std::fs::remove_dir_all(&dir).ok();
17782 }
17783
17784 #[test]
17785 fn a_whole_look_drag_undoes_in_one_step() {
17786 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
17787 let mut p = three();
17788 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "the press");
17789 for hue in 2..=8u8 {
17790 assert!(p.set_viz_paint_live(Lane::V1, 0, look(hue)), "a sample");
17791 }
17792 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(8));
17793 assert!(p.undo());
17794 assert_eq!(
17795 p.lane(Lane::V1)[0].viz_paint,
17796 0,
17797 "one undo is the whole gesture, back to the default look"
17798 );
17799
17800 // The live write refuses an index that is not there -- and a refusal
17801 // costs no history -- while one committing write is one step back.
17802 assert!(!p.set_viz_paint_live(Lane::V1, 99, look(1)));
17803 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "a click, not a drag");
17804 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(1));
17805 assert!(p.undo());
17806 assert_eq!(
17807 p.lane(Lane::V1)[0].viz_paint,
17808 0,
17809 "the committing setter is one undo step, no more"
17810 );
17811 }
17812
17813 /// The colour table is append-only within a session, exactly as the eq one
17814 /// is -- and a save is where an undone grade goes.
17815 #[test]
17816 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
17817 let mut p = three();
17818 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
17819 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
17820 assert!(p.undo(), "back to the first grade");
17821 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
17822
17823 let (_, lanes, _, color, _) = p.without_orphan_sources();
17824 assert_eq!(
17825 color,
17826 vec![grade_at(1)],
17827 "what nothing plays is not written"
17828 );
17829 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
17830 assert_eq!(lanes[0].1[1].color, None);
17831
17832 // One grade on three clips is one entry: settings that are equal share.
17833 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
17834 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
17835 let (_, lanes, _, color, _) = p.without_orphan_sources();
17836 assert_eq!(color.len(), 1, "equal grades share their entry");
17837 assert_eq!(lanes[1].1[2].color, Some(0));
17838 reloads(&p, "a colour that outlived an undo");
17839
17840 // An equalizer and a grade on one clip are two independent tables.
17841 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
17842 let (_, lanes, eq, color, _) = p.without_orphan_sources();
17843 assert_eq!((eq.len(), color.len()), (1, 1));
17844 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
17845 }
17846
17847 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
17848 /// placement is the clip's, through every edit that copies one.
17849 #[test]
17850 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
17851 let mut p = three();
17852 assert!(
17853 p.transform_of(Lane::V1, 0).is_none(),
17854 "a fresh clip is untransformed"
17855 );
17856 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
17857 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17858 assert!(
17859 p.transform_of(Lane::A1, 0).is_none(),
17860 "one clip, not the lane below"
17861 );
17862 assert!(
17863 p.color_of(Lane::V1, 0).is_none(),
17864 "and a placement is not a grade"
17865 );
17866
17867 // Cutting a transformed clip must not transform half of it: both
17868 // halves inherit.
17869 assert!(p.split(1));
17870 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17871 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
17872 assert!(
17873 p.transform_of(Lane::V1, 2).is_none(),
17874 "the clip after it is untransformed"
17875 );
17876
17877 // A clipboard copy carries it -- onto another lane, at that.
17878 let copied = p.lane(Lane::V1)[1].clone();
17879 assert!(p.place(Lane::A1, 20, copied));
17880 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
17881 assert!(p.undo());
17882 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
17883
17884 // ...and a change to one is one undo step, in both directions.
17885 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
17886 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
17887 assert!(p.undo());
17888 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17889 assert!(
17890 p.set_transform(Lane::V1, 0, None),
17891 "and taking it off is an edit"
17892 );
17893 assert!(p.transform_of(Lane::V1, 0).is_none());
17894 assert!(p.undo());
17895 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17896
17897 // Two refusals, neither of which costs an undo step.
17898 let nan = TransformParams {
17899 scale: f32::NAN,
17900 ..transform_at(1)
17901 };
17902 assert!(
17903 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
17904 "no clip there"
17905 );
17906 assert!(
17907 !p.set_transform(Lane::V1, 0, Some(nan)),
17908 "not a finite value"
17909 );
17910 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17911 assert!(p.undo());
17912 assert_eq!(
17913 p.lane(Lane::V1).len(),
17914 3,
17915 "one step back is before the split"
17916 );
17917 assert!(p.undo());
17918 assert!(
17919 p.transform_of(Lane::V1, 0).is_none(),
17920 "and the next is before the placement: the refusals pushed none"
17921 );
17922 }
17923
17924 /// The transform table is append-only within a session, exactly as the eq
17925 /// and colour ones are -- and a save is where an undone placement goes.
17926 #[test]
17927 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
17928 let mut p = three();
17929 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
17930 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
17931 assert!(p.undo(), "back to the first placement");
17932 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
17933
17934 let (_, lanes, _, _, transform) = p.without_orphan_sources();
17935 assert_eq!(
17936 transform,
17937 vec![transform_at(1)],
17938 "what nothing plays is not written"
17939 );
17940 assert_eq!(
17941 lanes[0].1[0].transform,
17942 Some(0),
17943 "and the survivor renumbers"
17944 );
17945 assert_eq!(lanes[0].1[1].transform, None);
17946
17947 // One placement on three clips is one entry: settings that are equal
17948 // share.
17949 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
17950 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
17951 let (_, lanes, _, _, transform) = p.without_orphan_sources();
17952 assert_eq!(transform.len(), 1, "equal placements share their entry");
17953 assert_eq!(lanes[1].1[2].transform, Some(0));
17954 reloads(&p, "a transform that outlived an undo");
17955
17956 // A grade and a placement on one clip are two independent tables.
17957 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
17958 let (_, lanes, _, color, transform) = p.without_orphan_sources();
17959 assert_eq!((color.len(), transform.len()), (1, 1));
17960 assert_eq!(
17961 (lanes[0].1[0].color, lanes[0].1[0].transform),
17962 (Some(0), Some(0))
17963 );
17964 }
17965
17966 /// Not a claim about correctness but about cost: a clip is cloned on every
17967 /// paste, every undo snapshot and every lane clone, so its size is worth
17968 /// bounding. A clip is no longer `Copy` by design -- the keyframed gain
17969 /// envelope (`gain_keys`) owns a `Vec` -- so a clone is a heap allocation
17970 /// too, and the bound that matters is the inline size: 224 bytes today (the
17971 /// deinterlace choice, one byte, took it from 216 as there was no padding left)
17972 /// (the visualizer `u64` and six `Vec`s, the volume, placement, speed
17973 /// ramp, opacity and colour keys and the effects stack, are the wide fields; the placement keys raised it from 96 by one
17974 /// `Vec`, the speed ramp raised it from 120 by another, the opacity and
17975 /// colour keys took it from 144 to 192, and the effects stack to 216, the multicam angle to 224). The
17976 /// bound is `<=` rather than `==` so a field that shrinks the clip does not
17977 /// trip it; growing past it is the thing to notice.
17978 #[test]
17979 fn a_clip_stays_within_224_bytes() {
17980 assert!(
17981 std::mem::size_of::<Clip>() <= 224,
17982 "Clip grew to {} bytes -- every undo snapshot and clone pays for it",
17983 std::mem::size_of::<Clip>()
17984 );
17985 }
17986
17987 #[test]
17988 fn from_parts_has_no_history_and_checks_the_invariants() {
17989 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
17990 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
17991 let mut p = Project::from_parts(
17992 sources.clone(),
17993 lanes.clone(),
17994 eq.clone(),
17995 color.clone(),
17996 Vec::new(),
17997 )
17998 .expect("valid parts");
17999 assert_eq!(p.clips(), three().clips());
18000 assert!(!p.undo(), "a loaded project has nothing to undo");
18001 assert!(p.split(4), "...and is editable from there");
18002 assert!(p.undo());
18003
18004 // A lane may be empty, and so may every lane -- an emptied timeline is a
18005 // project. No lane at all is not one: there would be nothing to place on.
18006 assert!(
18007 Project::from_parts(
18008 sources.clone(),
18009 two(video.clone(), Vec::new()),
18010 Vec::new(),
18011 Vec::new(),
18012 Vec::new(),
18013 )
18014 .is_ok()
18015 );
18016 assert!(
18017 Project::from_parts(
18018 sources.clone(),
18019 two(Vec::new(), Vec::new()),
18020 Vec::new(),
18021 Vec::new(),
18022 Vec::new(),
18023 )
18024 .is_ok()
18025 );
18026 assert!(
18027 Project::from_parts(
18028 sources.clone(),
18029 Vec::new(),
18030 Vec::new(),
18031 Vec::new(),
18032 Vec::new()
18033 )
18034 .is_err()
18035 );
18036 let bad: [Vec<Clip>; 5] = [
18037 vec![clip(0, 0, 3, 1)], // source that is not there
18038 vec![clip(0, 3, 3, 0)], // empty clip
18039 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
18040 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
18041 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
18042 ];
18043 for clips in bad {
18044 assert!(
18045 Project::from_parts(
18046 sources.clone(),
18047 two(clips.clone(), Vec::new()),
18048 Vec::new(),
18049 Vec::new(),
18050 Vec::new(),
18051 )
18052 .is_err(),
18053 "{clips:?}"
18054 );
18055 assert!(
18056 Project::from_parts(
18057 sources.clone(),
18058 two(video.clone(), clips.clone()),
18059 Vec::new(),
18060 Vec::new(),
18061 Vec::new(),
18062 )
18063 .is_err()
18064 );
18065 // ...and on a third lane, which is checked by the same walk.
18066 assert!(
18067 Project::from_parts(
18068 sources.clone(),
18069 vec![
18070 (LaneKind::Video, video.clone()),
18071 (LaneKind::Audio, audio.clone()),
18072 (LaneKind::Video, clips),
18073 ],
18074 Vec::new(),
18075 Vec::new(),
18076 Vec::new(),
18077 )
18078 .is_err()
18079 );
18080 }
18081 // An equalizer index no table entry answers, and a table entry the file
18082 // format could not have written, are refused at this door too.
18083 let eqd = |i: u16| {
18084 vec![Clip {
18085 fade_in: 0,
18086 fade_out: 0,
18087 transition_out: 0,
18088 transition_kind: Default::default(),
18089 visualizer: 0,
18090 viz_paint: 0,
18091 gain_db: 0.0,
18092 eq: Some(i),
18093 ..video[0].clone()
18094 }]
18095 };
18096 assert!(
18097 Project::from_parts(
18098 sources.clone(),
18099 two(eqd(0), Vec::new()),
18100 Vec::new(),
18101 Vec::new(),
18102 Vec::new(),
18103 )
18104 .is_err()
18105 );
18106 let mut nan = band_at(1);
18107 nan.bands[0].freq_hz = f32::NAN;
18108 assert!(
18109 Project::from_parts(
18110 sources.clone(),
18111 two(eqd(0), Vec::new()),
18112 vec![nan],
18113 Vec::new(),
18114 Vec::new(),
18115 )
18116 .is_err()
18117 );
18118 let loaded = Project::from_parts(
18119 sources.clone(),
18120 two(eqd(0), Vec::new()),
18121 vec![band_at(1)],
18122 Vec::new(),
18123 Vec::new(),
18124 )
18125 .expect("an eq the table holds");
18126 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
18127
18128 // The same two refusals for a colour, at the same door.
18129 let graded = |i: u16| {
18130 vec![Clip {
18131 fade_in: 0,
18132 fade_out: 0,
18133 transition_out: 0,
18134 transition_kind: Default::default(),
18135 visualizer: 0,
18136 viz_paint: 0,
18137 gain_db: 0.0,
18138 color: Some(i),
18139 fit: FitPolicy::default(),
18140 speed: Speed::NORMAL,
18141 ..video[0].clone()
18142 }]
18143 };
18144 assert!(
18145 Project::from_parts(
18146 sources.clone(),
18147 two(graded(0), Vec::new()),
18148 Vec::new(),
18149 Vec::new(),
18150 Vec::new(),
18151 )
18152 .is_err(),
18153 "a colour index no entry answers"
18154 );
18155 assert!(
18156 Project::from_parts(
18157 sources.clone(),
18158 two(graded(0), Vec::new()),
18159 Vec::new(),
18160 vec![ColorParams {
18161 tint: f32::NAN,
18162 ..grade_at(1)
18163 }],
18164 Vec::new(),
18165 )
18166 .is_err(),
18167 "a value the file format could not have written"
18168 );
18169 let loaded = Project::from_parts(
18170 sources.clone(),
18171 two(graded(0), Vec::new()),
18172 Vec::new(),
18173 vec![grade_at(1)],
18174 Vec::new(),
18175 )
18176 .expect("a colour the table holds");
18177 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
18178
18179 // Group ids survive a load, and the next split gets a fresh one.
18180 let mut p =
18181 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
18182 assert!(p.split(4));
18183 assert!(p.clips().iter().all(|c| c.link.is_some()));
18184 }
18185
18186 /// The grouping rules, at the untrusted door and after every edit that can
18187 /// touch a link. A link id is at most one placement per lane -- a clip or a
18188 /// caption, whichever carries it -- and no sequence of edits may produce
18189 /// otherwise, because what an edit produces is what a save writes and a load
18190 /// reads.
18191 ///
18192 /// Amended for the offset-preserving group: the members keep their own
18193 /// spans, so two placements of one id covering different frames is *legal*
18194 /// -- it is what a hand-built group is -- and the only refusal left is the
18195 /// doubled id inside one lane.
18196 #[test]
18197 fn a_link_id_is_never_two_clips_of_one_lane() {
18198 let sources = vec![Source::new(FILE, 0)];
18199 let linked = |start, in_frame, out_frame, link| Clip {
18200 speed_keys: Vec::new(),
18201 reversed: false,
18202 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
18203 angle: Default::default(),
18204 fade_in: 0,
18205 fade_out: 0,
18206 transition_out: 0,
18207 transition_kind: Default::default(),
18208 visualizer: 0,
18209 viz_paint: 0,
18210 gain_db: 0.0,
18211 gain_keys: Vec::new(),
18212 pan: 0,
18213 pitch: 0,
18214 transform_keys: Vec::new(),
18215 opacity_keys: Vec::new(),
18216 color_keys: Vec::new(),
18217 effects: Vec::new(),
18218 start,
18219 in_frame,
18220 out_frame,
18221 source: 0,
18222 link: Some(link),
18223 eq: None,
18224 color: None,
18225 transform: None,
18226 fit: FitPolicy::default(),
18227 speed: Speed::NORMAL,
18228 };
18229
18230 // The door: a doubled id inside one lane, refused by name.
18231 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
18232 Project::from_parts(
18233 sources.clone(),
18234 two(video, audio),
18235 Vec::new(),
18236 Vec::new(),
18237 Vec::new(),
18238 )
18239 .expect_err("refused")
18240 .to_string()
18241 };
18242 assert!(
18243 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
18244 .contains("link 7 names two clips in the V1 lane"),
18245 "a duplicate id inside one lane is refused by name"
18246 );
18247 // ...and the same doubling on a subtitle lane, in its own words: a
18248 // caption is the other placement an id may name.
18249 let caption = |start: u32, frames: u32, link| SubClip {
18250 start,
18251 frames,
18252 track: 0,
18253 in_us: 0,
18254 out_us: i64::from(frames) * 1_000_000,
18255 link: Some(link),
18256 };
18257 let subs = LaneData {
18258 clips: Vec::new(),
18259 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
18260 ..LaneData::new(LaneKind::Subtitle, Vec::new())
18261 };
18262 assert_eq!(
18263 links_are_consistent(&[subs]).unwrap_err().to_string(),
18264 "link 7 names two captions in the S1 lane"
18265 );
18266 // A pair covering *different* frames is legal now: the members of a
18267 // hand-built group keep their own spans, and what binds them is the id.
18268 let apart = Project::from_parts(
18269 sources.clone(),
18270 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
18271 Vec::new(),
18272 Vec::new(),
18273 Vec::new(),
18274 );
18275 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
18276 // A one-sided link is *not* an error: it is what a lift leaves behind.
18277 let mut p = Project::single(FILE, 9);
18278 assert!(p.lift(Lane::A1, 0));
18279 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
18280 assert!(
18281 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
18282 "a lifted lane's project has to load again"
18283 );
18284
18285 // The edits: nothing below may break either rule.
18286 let consistent = |p: &Project, what: &str| {
18287 assert!(
18288 links_are_consistent(&p.lanes).is_ok(),
18289 "{what}: {:?}",
18290 p.lanes
18291 );
18292 };
18293 let mut p = three();
18294 let copied = p.clips()[0].clone();
18295 assert!(
18296 copied.link.is_some(),
18297 "the clipboard clip carries its group"
18298 );
18299 assert!(p.lift(Lane::V1, 0));
18300 assert!(p.place(Lane::V1, 0, copied.clone()));
18301 assert!(
18302 p.place(Lane::V1, 20, copied.clone()),
18303 "and again, further out"
18304 );
18305 assert_eq!(
18306 p.clips().iter().filter(|c| c.link == copied.link).count(),
18307 0,
18308 "a placement belongs to no group, so it cannot duplicate one"
18309 );
18310 consistent(&p, "lift + place twice");
18311 assert!(
18312 p.place(Lane::A1, 4, copied.clone()),
18313 "over a linked clip's middle"
18314 );
18315 consistent(&p, "place through a grouped clip");
18316 assert!(
18317 p.paste(6, copied.clone()),
18318 "a rippling paste through another"
18319 );
18320 consistent(&p, "paste");
18321 assert!(p.split(2));
18322 consistent(&p, "split");
18323 assert!(p.ripple_delete(1, 3));
18324 consistent(&p, "ripple_delete");
18325 assert!(p.undo());
18326 consistent(&p, "undo");
18327 }
18328
18329 /// What an edit produces is what a save writes, so *every* state the public
18330 /// API can reach has to load again. The two the verifier panel found where
18331 /// it did not: a split and a regroup handed one group id to two clips that
18332 /// were not the same span, because the lanes had been edited apart.
18333 #[test]
18334 fn every_reachable_state_reloads() {
18335 let mut p = Project::single(FILE, 150);
18336 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
18337 assert!(p.split(10), "the lanes are cut apart at 10");
18338 reloads(&p, "place on one lane, then split");
18339
18340 let mut p = Project::single(FILE, 150);
18341 assert!(p.split(30));
18342 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
18343 assert!(p.regroup(30), "only the audio lane can rejoin");
18344 assert!(p.split(60));
18345 reloads(&p, "lift, regroup one lane, split");
18346
18347 // Two audio streams of one file, both placed: two source entries with
18348 // one path between them, which is the state a stream picked out of the
18349 // library reaches -- and the state a save has to write and read back.
18350 let mut p = Project::single(FILE, 150);
18351 let second = p.import(FILE, 1);
18352 assert_eq!(second, 1, "the same file on another stream is a new source");
18353 assert!(p.append_clip(second, 150));
18354 assert!(p.split(200));
18355 reloads(
18356 &p,
18357 "a second audio stream of the same file, placed and split",
18358 );
18359 let (sources, ..) = p.without_orphan_sources();
18360 assert_eq!(
18361 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
18362 [0, 1],
18363 "both entries survive the orphan prune: both are played"
18364 );
18365 }
18366
18367 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
18368 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
18369 /// is the stamp playback puts on a decoded source frame -- and the *last*
18370 /// source frame the pump is still holding at a timeline frame has to be
18371 /// exactly the one the export encoded there, at every rate. Anything else is
18372 /// A/V drift that grows with the clip, and no test of either side alone
18373 /// would see it.
18374 ///
18375 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
18376 /// is a better answer than the floor/floor this had: floor/floor put the
18377 /// preview a whole held frame off the export at slow rates.)
18378 #[test]
18379 fn speed_maps_both_ways() {
18380 for permille in (250..=4000).step_by(1) {
18381 let speed = Speed::from_permille(permille);
18382 assert_eq!(speed.permille(), permille, "no clamping in range");
18383 for d in 0..200u32 {
18384 let want = speed.source_at(d);
18385 // What the pump shows at `d` is the last frame whose stamp has
18386 // come due -- and it is `want`, the frame the export encodes
18387 // there. Slowed, that is the frame it is still holding; sped up,
18388 // it is the newest of the several that arrived.
18389 let held = (0..=want + 8).rev().find(|&s| speed.timeline_at(s) <= d);
18390 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
18391 }
18392 for n in 1..300u32 {
18393 // A footprint is never zero: a clip occupying no timeline frame
18394 // is a placement the lane invariants cannot hold.
18395 let frames = speed.frames(n);
18396 assert!(frames >= 1, "{speed} of {n} frames");
18397 // ...and its last timeline frame never reads past the clip.
18398 assert!(
18399 speed.source_at(frames - 1) < n,
18400 "{speed}: the last timeline frame of {n} reads past the clip"
18401 );
18402 // The trim inverse never overshoots the room it was given, and
18403 // answers for every room a footprint can be.
18404 let fit = speed.fit(frames).expect("a clip fits its own footprint");
18405 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
18406 // A room narrower than one source frame's own footprint holds
18407 // nothing, and says so rather than rounding something into it.
18408 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
18409 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
18410 }
18411 }
18412 // Real time is the identity map, byte for byte.
18413 for d in 0..1000 {
18414 assert_eq!(Speed::NORMAL.source_at(d), d);
18415 assert_eq!(Speed::NORMAL.timeline_at(d), d);
18416 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
18417 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
18418 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
18419 }
18420 // The one door: no zero, no reverse, nothing past the ends.
18421 assert_eq!(Speed::from_permille(0), Speed::MIN);
18422 assert_eq!(Speed::from_permille(249), Speed::MIN);
18423 assert_eq!(Speed::from_permille(4001), Speed::MAX);
18424 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
18425 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
18426 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
18427 }
18428
18429 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
18430 /// export encodes at a timeline frame is the one playback is holding there,
18431 /// a file is as long in timeline frames as the seconds it lasts, and the two
18432 /// compose so a speeded clip at another rate is exactly both.
18433 #[test]
18434 fn rate_composes_with_speed() {
18435 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
18436 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
18437 // the identity map or a single-rate project would move.
18438 for (source_fps, timeline_fps) in [
18439 (24000. / 1001., 30.),
18440 (30., 24000. / 1001.),
18441 (60., 30.),
18442 (25., 30.),
18443 (30., 30.),
18444 ] {
18445 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
18446 for n in 0..2000u32 {
18447 let source = rate.source_at(n);
18448 // The stamp is the *first* timeline-rate frame that shows it, so
18449 // the picture on screen at `n` is the picture encoded at `n`.
18450 let held = (0..=source + 4).rev().find(|&s| rate.timeline_at(s) <= n);
18451 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
18452 }
18453 // A file of `count` frames is `timeline_at(count)` frames long here,
18454 // and its last one still reads a frame the file has.
18455 for count in 1..500u32 {
18456 let frames = rate.timeline_at(count);
18457 assert!(frames >= 1, "a file is never zero frames long");
18458 assert!(
18459 rate.source_at(frames - 1) < count,
18460 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
18461 );
18462 }
18463 // No drift: the mapping is one exact division of the *rate itself*,
18464 // not an accumulation and not a rounded rate, so an hour in is as
18465 // true as the first second. (Held to the real ratio of the two rates
18466 // the caller asked for -- `as_f64` would be true of a wrong rate.)
18467 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
18468 let want = f64::from(n) * source_fps / timeline_fps;
18469 assert!(
18470 (f64::from(rate.source_at(n)) - want).abs() < 1.,
18471 "{source_fps} on {timeline_fps}: frame {n} drifted"
18472 );
18473 }
18474 }
18475 // The timeline's own rate is the identity, whichever way it is written.
18476 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
18477 assert!(
18478 Rate::from_fps(30.0004, 30.)
18479 .expect("30.0004 over 30")
18480 .is_real_time(),
18481 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
18482 );
18483 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
18484 // one thing `matches_timeline` refuses a file for now that the rate gate
18485 // is gone.
18486 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
18487 assert!(Rate::from_fps(30., f64::NAN).is_err());
18488 for n in 0..1000 {
18489 assert_eq!(Rate::REAL_TIME.source_at(n), n);
18490 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
18491 }
18492 // ...and the composition, in the order the decoder's door applies it:
18493 // the speed picks the clip's (timeline-rate) frame, the rate picks the
18494 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
18495 // timeline frames per frame shown, each of them exactly 800/1001 of a
18496 // file frame.
18497 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
18498 let speed = Speed::from_permille(2000);
18499 for d in 0..100u32 {
18500 assert_eq!(
18501 rate.source_at(speed.source_at(d)),
18502 (u64::from(d) * 2 * 800 / 1001) as u32,
18503 "2x of a 23.976 fps file at timeline frame {d}"
18504 );
18505 }
18506 }
18507
18508 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
18509 /// source frames per timeline frame and still starts at its own in-point,
18510 /// and a half-speed one shows every source frame twice.
18511 #[test]
18512 fn a_rate_maps_timeline_frames_onto_source_frames() {
18513 let mut p = Project::single(FILE, 40);
18514 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
18515 .expect("room enough");
18516 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
18517 assert_eq!(
18518 p.map(Lane::V1, 0),
18519 Some((0, 0)),
18520 "and it starts where it did"
18521 );
18522 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
18523 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
18524 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
18525 // The span a decoder is handed: as many source frames as it will read,
18526 // which is the last shown frame's own and not one more -- timeline frame
18527 // 19 shows source frame 38, so 39 frames are read and the 40th is a
18528 // picture nothing would display.
18529 let span = p.span_at(Lane::V1, 0).expect("a span");
18530 assert_eq!((span.len, span.source_len()), (20, 39));
18531 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
18532 // ...and the same clip the other way round.
18533 let mut p = Project::single(FILE, 40);
18534 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
18535 .expect("room enough");
18536 assert_eq!(p.timeline_frames(), 80);
18537 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
18538 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
18539 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
18540 assert_eq!(
18541 p.map(Lane::V1, 79),
18542 Some((0, 39)),
18543 "and the last timeline frame is still inside the source range"
18544 );
18545 }
18546
18547 /// A trim of a speeded clip is still a trim of its *source*, and the edge
18548 /// still stops at the wall: the room a rate leaves is measured in timeline
18549 /// frames and the range it commits in source ones.
18550 #[test]
18551 fn trimming_a_speeded_clip_stays_inside_its_room() {
18552 let mut p = Project::single(FILE, 40);
18553 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
18554 .expect("room enough");
18555 // A second clip butted against the first, so the wall is a real one.
18556 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
18557 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
18558 assert_eq!(room, (1, 20), "out to the neighbour and no further");
18559 assert!(
18560 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
18561 "clamped to the wall, which is where the edge already is"
18562 );
18563 let c = p.clips()[0].clone();
18564 assert_eq!(c.end(), 20, "so nothing moved");
18565 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
18566 // ...and in: half the timeline frames is half the source range.
18567 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
18568 let c = p.clips()[0].clone();
18569 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
18570 assert_eq!(c.end(), 10, "and ten timeline frames of them");
18571 assert!(sorted_disjoint(p.clips()));
18572 }
18573
18574 /// The frames a rate cannot address: at half speed each source frame is on
18575 /// screen twice, and the cut between the two showings is not a cut in the
18576 /// file. Refused, so the two halves always add up to the clip that was cut.
18577 #[test]
18578 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
18579 let mut p = Project::single(FILE, 10);
18580 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
18581 .expect("room enough");
18582 assert_eq!(p.timeline_frames(), 20);
18583 assert!(
18584 !p.split(3),
18585 "an odd frame is between two showings of one frame"
18586 );
18587 assert_eq!(p.clips().len(), 1, "and nothing was cut");
18588 assert!(p.split(4), "an even one is a frame boundary");
18589 let halves = p.clips().to_vec();
18590 assert_eq!(
18591 (halves[0].end(), halves[1].start, halves[1].end()),
18592 (4, 4, 20),
18593 "the halves meet, and still end where the clip did"
18594 );
18595 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
18596 assert!(p.regroup(4), "and the inverse puts it back");
18597 assert_eq!(p.clips().len(), 1);
18598 }
18599
18600 /// The same claim, swept: random op sequences off the public surface, the
18601 /// project reloaded after every one of them. A failure prints its seed, and
18602 /// the seed replays the whole sequence.
18603 #[test]
18604 fn random_edit_sequences_reload() {
18605 // Two thousand, not two hundred: the overlap a hole punched into a slow
18606 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
18607 // sequences, and a 200-seed sweep walked straight past it (it took a
18608 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
18609 // has no business being the narrow one.
18610 for seed in 0..2000u64 {
18611 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
18612 let mut next = move |n: u32| {
18613 // xorshift64*: no dependency, and the seed replays it exactly.
18614 rng ^= rng << 13;
18615 rng ^= rng >> 7;
18616 rng ^= rng << 17;
18617 (rng >> 33) as u32 % n
18618 };
18619 let mut p = Project::single(FILE, 40);
18620 for step in 0..24 {
18621 let frame = next(44);
18622 // A clipboard copy carries the group id of the take it came from
18623 // -- the input that made a placement duplicate an id -- and, one
18624 // time in three, a rate of its own: a *speeded clip placed over
18625 // a speeded clip* is the shape whose remainders have to be run
18626 // through `Speed::fit`, and it is not a shape the lanes hand out
18627 // on their own often enough to be sure of.
18628 let mut copied = p
18629 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
18630 .get(next(4) as usize)
18631 .cloned()
18632 .unwrap_or_else(|| clip(0, 0, 5, 0));
18633 if next(3) == 0 {
18634 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
18635 }
18636 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
18637 let idx = next(4) as usize;
18638 let _ = match next(16) {
18639 // A clip dragged along its own lane to wherever the pointer
18640 // let it go: the op that moves a placement without changing
18641 // what it plays, so what it may not do is land on top of the
18642 // neighbour it was dragged at.
18643 15 => p.move_clip(lane, idx, lane, frame),
18644 // ...and a second `place`, so a punch lands inside a clip
18645 // far more often than one op in fourteen would put it there.
18646 14 => p.place(lane, frame, copied.clone()),
18647 0 => p.split(frame),
18648 1 => p.regroup(frame),
18649 2 => p.lift(lane, idx),
18650 3 => p.place(lane, frame, copied.clone()),
18651 4 => p.paste(frame, copied.clone()),
18652 5 => p.ripple_delete(frame, next(9)),
18653 6 => p.delete(idx),
18654 7 => p.undo(),
18655 // An equalizer put on and taken off in the mix: what a clip
18656 // carries has to reload with it, and the entries an undo
18657 // orphans must not come back out of the prune.
18658 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
18659 9 => p.set_eq(lane, idx, None),
18660 // ...and a colour grade in the same mix, for the same
18661 // reason: it rides on the clip and its orphans must go.
18662 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
18663 11 => p.set_color(lane, idx, None),
18664 // ...and a rate in with them, which is the one of the three
18665 // that moves *placements*: a clip that grew has to be
18666 // refused rather than overlap, and one that shrank leaves a
18667 // lane that still loads. Both are what `reloads` asks.
18668 12 => p
18669 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
18670 .is_ok(),
18671 _ => p.append_clip(0, 1 + next(9)),
18672 };
18673 reloads(&p, &format!("seed {seed}, step {step}"));
18674 }
18675 }
18676 }
18677
18678 /// The save/load round trip a project must survive: the parts a save writes,
18679 /// handed back to the constructor a load goes through -- every lane of them,
18680 /// and the reloaded timeline has to be the same lanes in the same order.
18681 fn reloads(p: &Project, what: &str) {
18682 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
18683 match Project::from_parts(sources, lanes, eq, color, transform) {
18684 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
18685 Ok(back) => {
18686 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
18687 // Placements, not whole clips: an orphan prune renumbers the
18688 // sources a clip names, which is the point of it.
18689 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
18690 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
18691 };
18692 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
18693 // The prune renumbers the eq table too, so what has to survive
18694 // is the settings themselves, clip by clip.
18695 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
18696 p.lanes()
18697 .into_iter()
18698 .map(|l| {
18699 (0..p.lane(l).len())
18700 .map(|i| p.eq_of(l, i).cloned())
18701 .collect()
18702 })
18703 .collect()
18704 };
18705 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
18706 // The colour table renumbers in the same prune, so the same
18707 // claim: the params a clip names, not the index it names them by.
18708 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
18709 p.lanes()
18710 .into_iter()
18711 .map(|l| {
18712 (0..p.lane(l).len())
18713 .map(|i| p.color_of(l, i).copied())
18714 .collect()
18715 })
18716 .collect()
18717 };
18718 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
18719 // ...and the transform table, by the same claim again.
18720 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
18721 p.lanes()
18722 .into_iter()
18723 .map(|l| {
18724 (0..p.lane(l).len())
18725 .map(|i| p.transform_of(l, i).copied())
18726 .collect()
18727 })
18728 .collect()
18729 };
18730 assert_eq!(
18731 transforms(&back),
18732 transforms(p),
18733 "{what}: the transforms changed"
18734 );
18735 }
18736 }
18737 }
18738
18739 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
18740 /// -- each one sorted and disjoint, and one span per group id -- asserted
18741 /// directly, where the point is the invariant rather than the round trip.
18742 fn invariants_hold(p: &Project, what: &str) {
18743 for lane in p.lanes() {
18744 assert!(
18745 sorted_disjoint(p.lane(lane)),
18746 "{what}: {} is out of order or overlaps itself: {:?}",
18747 lane.label(),
18748 p.lane(lane)
18749 );
18750 }
18751 if let Err(e) = links_are_consistent(&p.lanes) {
18752 panic!("{what}: {e}\n{:?}", p.lanes);
18753 }
18754 }
18755
18756 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
18757 /// edited without any other lane hearing about it. A handle naming a lane
18758 /// that is not there reads as empty and refuses to mutate.
18759 #[test]
18760 fn a_third_lane_is_a_peer() {
18761 let mut p = three();
18762 assert_eq!(p.lane_count(LaneKind::Video), 1);
18763 assert_eq!(p.lane_count(LaneKind::Audio), 1);
18764 let v2 = p.add_lane(LaneKind::Video);
18765 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
18766 assert_eq!(v2.label(), "V2");
18767 assert_eq!(p.lane_count(LaneKind::Video), 2);
18768 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
18769 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
18770
18771 // A handle for a lane that is not there: empty, and no mutation takes.
18772 let v3 = Lane::new(LaneKind::Video, 2);
18773 assert!(p.lane(v3).is_empty());
18774 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
18775 assert!(!p.lift(v3, 0));
18776 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
18777
18778 // Placing on V2 moves nothing else, and the lane can outrun the rest.
18779 let before = shape(&p);
18780 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
18781 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
18782 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
18783 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
18784 assert_eq!(
18785 p.timeline_frames(),
18786 16,
18787 "the last lane to end sets the length"
18788 );
18789 assert_eq!(p.map(v2, 5), Some((0, 21)));
18790 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
18791 assert_eq!(
18792 p.span_at(v2, 0),
18793 Some(Span {
18794 reverse: false,
18795 ramp: None,
18796 start: 0,
18797 len: 4,
18798 from: None,
18799 speed: Speed::NORMAL,
18800 pitch: 0,
18801 })
18802 );
18803 // Every lane still covers the whole timeline, gaps included.
18804 for l in p.lanes() {
18805 let spans = p.spans_from(l, 0);
18806 assert_eq!(
18807 spans.iter().map(|s| s.len).sum::<u32>(),
18808 16,
18809 "{}",
18810 l.label()
18811 );
18812 }
18813 // ...and playback still reads V1 and A1, whatever else is there.
18814 assert_eq!(p.clips(), p.lane(Lane::V1));
18815 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
18816 let segments = p.segments_from(0, FPS);
18817 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
18818 assert_eq!(
18819 segments[3],
18820 (None, 0.0, 7.0 / FPS),
18821 "A1 keeps the clock counting over the picture V2 added"
18822 );
18823 invariants_hold(&p, "place on V2");
18824
18825 // A lift is that lane's business too, and the lane list undoes.
18826 assert!(p.lift(v2, 0));
18827 assert!(p.lane(v2).is_empty());
18828 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
18829 assert!(p.undo());
18830 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
18831 assert!(p.undo());
18832 assert!(p.lane(v2).is_empty(), "the placement came off V2");
18833 assert!(p.undo(), "and one more step takes the lane itself back");
18834 assert_eq!(p.lane_count(LaneKind::Video), 1);
18835 assert_eq!(shape(&p), shape(&three()));
18836 }
18837
18838 /// The add taken back: an empty lane comes off, a lane holding clips never
18839 /// does (and says which clips), the last lane of a kind never does, the
18840 /// lanes below the one that went move up an `ord`, and one undo puts it
18841 /// back where it stood.
18842 #[test]
18843 fn an_empty_lane_comes_off_again() {
18844 let mut p = three();
18845 let v2 = p.add_lane(LaneKind::Video);
18846 let v3 = p.add_lane(LaneKind::Video);
18847 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
18848 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
18849 let history = p.history.len();
18850
18851 // The last lane of its kind stays: `V1`/`A1` are where an import and a
18852 // paste land, and a project missing one would swallow half of a file
18853 // dropped on it.
18854 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
18855 assert_eq!(
18856 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
18857 "there is no V10 to remove"
18858 );
18859
18860 // A lane with clips on it refuses and names them: a track removal never
18861 // deletes a take.
18862 let refusal = why(p.remove_lane(v3));
18863 assert!(refusal.contains("V3 still holds"), "{refusal}");
18864 assert!(refusal.contains(FILE), "{refusal}");
18865 assert!(refusal.contains("at frame 0"), "{refusal}");
18866 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
18867 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
18868
18869 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
18870 // all.
18871 p.remove_lane(v2).expect("V2 is empty");
18872 assert_eq!(p.lane_count(LaneKind::Video), 2);
18873 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
18874 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
18875 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
18876 invariants_hold(&p, "remove V2");
18877
18878 // ...and one stroke puts the empty lane back above it.
18879 assert!(p.undo());
18880 assert_eq!(p.lane_count(LaneKind::Video), 3);
18881 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
18882 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
18883 }
18884
18885 /// A duck is the audio lane's own setting: it names another audio lane as
18886 /// its key, refuses itself and video lanes as a key or a target, is one undo
18887 /// step, and reaches the mix only for a key that is in the mix.
18888 #[test]
18889 fn a_duck_keys_off_another_audio_lane_and_is_one_undo_step() {
18890 use crate::duck::Duck;
18891 let mut p = Project::single(FILE, 9);
18892 let a2 = p.add_lane(LaneKind::Audio);
18893 let duck = Duck::new(0, -12.0);
18894 let history = p.history.len();
18895 assert!(
18896 !p.set_lane_duck(Lane::A1, Some(duck)),
18897 "a lane is not its own key"
18898 );
18899 assert!(
18900 !p.set_lane_duck(Lane::V1, Some(duck)),
18901 "a video lane does not duck"
18902 );
18903 assert!(
18904 !p.set_lane_duck(a2, Some(Duck::new(5, -12.0))),
18905 "no such key"
18906 );
18907 assert!(!p.set_lane_duck(
18908 a2,
18909 Some(Duck {
18910 depth_db: f32::NAN,
18911 ..duck
18912 })
18913 ));
18914 assert_eq!(p.history.len(), history, "a refusal writes no history");
18915 assert!(p.set_lane_duck(a2, Some(duck)));
18916 assert_eq!(p.lane_duck(a2), Some(duck));
18917 assert_eq!(p.history.len(), history + 1, "one undo step");
18918 // A2 is empty, so it is not in the mix and cannot be a key in it.
18919 assert_eq!(p.audio_ducks(), vec![Vec::<Duck>::new()], "one mixed lane, unducked");
18920 assert_eq!(p.lane_ducks()[2], vec![duck], "saved by its own lane");
18921 assert!(p.undo());
18922 assert_eq!(p.lane_duck(a2), None, "undone");
18923 }
18924
18925 /// A lane is ducked under several keys at once, each set on its own: a duck
18926 /// under a key the lane already has replaces that one, a clear takes one key
18927 /// away, and the mix reads them all in the order they were set.
18928 #[test]
18929 fn a_lane_ducks_under_several_keys_and_each_can_be_cleared() {
18930 use crate::duck::Duck;
18931 let mut p = Project::single(FILE, 9);
18932 let a2 = p.add_lane(LaneKind::Audio);
18933 let a3 = p.add_lane(LaneKind::Audio);
18934 // A1 and A2 are the keys that A3 is ducked under.
18935 assert!(p.set_lane_duck(a3, Some(Duck::new(0, -12.0))), "A3 under A1");
18936 assert!(p.set_lane_duck(a3, Some(Duck::new(1, -6.0))), "A3 under A2 too");
18937 assert_eq!(p.lane_duck_list(a3).len(), 2, "both kept");
18938 assert_eq!(p.lane_duck(a3), Some(Duck::new(0, -12.0)), "the first set");
18939 // The same key again replaces its duck and keeps the other.
18940 assert!(p.set_lane_duck(a3, Some(Duck::new(1, -20.0))));
18941 let list = p.lane_duck_list(a3);
18942 assert_eq!(list.len(), 2);
18943 assert_eq!(list[1].depth_db, -20.0, "the A2 key's depth changed in place");
18944 assert_eq!(list[0].depth_db, -12.0, "the A1 key untouched");
18945 // A key that is the lane itself is still refused, whatever else it holds.
18946 assert!(!p.set_lane_duck(a3, Some(Duck::new(2, -6.0))));
18947 // Clearing one key leaves the other; clearing a key it lacks is a refusal.
18948 assert!(p.clear_lane_duck(a3, 0));
18949 assert_eq!(p.lane_duck_list(a3), vec![Duck { depth_db: -20.0, ..Duck::new(1, -20.0) }]);
18950 assert!(!p.clear_lane_duck(a3, 0), "no duck under A1 now");
18951 // None clears them all.
18952 assert!(p.set_lane_duck(a3, None));
18953 assert!(p.lane_duck_list(a3).is_empty());
18954 assert!(!p.set_lane_duck(a2, None), "nothing to clear is no change");
18955 }
18956
18957 /// Mute is the audio lane's switch and nothing else: it zeroes the lane's
18958 /// amplitude in the mix, leaves the lane's volume and clips where they were,
18959 /// is one undo step each way, and refuses the lanes it cannot mean anything
18960 /// for.
18961 #[test]
18962 fn a_muted_audio_lane_is_silent_in_the_mix_and_unmuting_restores_it() {
18963 let mut p = Project::single(FILE, 9);
18964 assert_eq!(p.audio_gains(), vec![1.0], "one lane at unity");
18965 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
18966 let loud = p.audio_gains()[0];
18967 let history = p.history.len();
18968
18969 assert!(p.set_lane_muted(Lane::A1, true));
18970 assert_eq!(p.audio_gains(), vec![0.0], "muted is silence in the sum");
18971 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "the volume is kept");
18972 assert_eq!(p.lane(Lane::A1).len(), 1, "and so are the clips");
18973 assert_eq!(p.history.len(), history + 1, "one undo step");
18974 assert!(
18975 !p.set_lane_muted(Lane::A1, true),
18976 "already muted is a no-op"
18977 );
18978 assert_eq!(p.history.len(), history + 1, "and no undo step for it");
18979
18980 assert!(p.set_lane_muted(Lane::A1, false));
18981 assert_eq!(p.audio_gains(), vec![loud], "unmuted is what it was");
18982
18983 // One undo per switch: the flag comes back through the lane list.
18984 assert!(p.undo());
18985 assert!(p.lane_muted(Lane::A1), "undo restores the muted flag");
18986 assert!(p.undo());
18987 assert!(!p.lane_muted(Lane::A1), "and the one before it");
18988
18989 assert!(
18990 !p.set_lane_muted(Lane::V1, true),
18991 "a video lane is never mixed"
18992 );
18993 assert!(
18994 !p.set_lane_hidden(Lane::A1, true),
18995 "an audio lane has no picture to hide"
18996 );
18997 assert!(
18998 !p.set_lane_hidden(Lane::new(LaneKind::Video, 7), true),
18999 "a lane that is not there"
19000 );
19001 }
19002
19003 /// Hiding a video lane takes it out of the composite: the picture is what
19004 /// the visible lanes cover, the lane under a hidden one shows through, and
19005 /// hiding the last covering lane leaves black. One undo step, and the flag
19006 /// is in the lane list, so a save and an undo both carry it.
19007 #[test]
19008 fn a_hidden_video_lane_leaves_the_composite() {
19009 let mut p = Project::single(FILE, 9);
19010 let v2 = p.add_lane(LaneKind::Video);
19011 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
19012 assert_eq!(p.composite_clip_at(3), Some((v2, 0)), "V2 is on top");
19013
19014 let history = p.history.len();
19015 assert!(p.set_lane_hidden(v2, true));
19016 assert_eq!(p.history.len(), history + 1, "one undo step");
19017 assert!(p.lane_hidden(v2));
19018 assert_eq!(
19019 p.composite_clip_at(3),
19020 Some((Lane::V1, 0)),
19021 "V1 shows through"
19022 );
19023 assert_eq!(
19024 p.composite_spans_from(0).len(),
19025 1,
19026 "one span, from V1 alone"
19027 );
19028
19029 assert!(p.set_lane_hidden(Lane::V1, true));
19030 assert_eq!(p.composite_clip_at(3), None, "nothing visible, so black");
19031 assert!(p.undo());
19032 assert!(!p.lane_hidden(Lane::V1), "undo restores the flag");
19033 assert!(p.lane_hidden(v2));
19034 assert!(p.undo());
19035 assert!(!p.lane_hidden(v2));
19036 assert_eq!(p.composite_clip_at(3), Some((v2, 0)));
19037
19038 // Lock is state only: it refuses nothing in the engine.
19039 assert!(p.set_lane_locked(v2, true));
19040 assert!(p.lane_locked(v2));
19041 assert!(
19042 p.place(v2, 0, clip(0, 0, 3, 0)),
19043 "a locked lane still takes edits"
19044 );
19045 assert!(p.undo());
19046 assert!(p.lane_locked(v2), "undoing the edit leaves the lock");
19047 assert!(p.undo());
19048 assert!(!p.lane_locked(v2), "and the lock is one step of its own");
19049 }
19050
19051 /// A hidden subtitle lane has no cues, so the screen draws none and the
19052 /// export writes no track for it; showing it again brings them back.
19053 #[test]
19054 fn a_hidden_subtitle_lane_yields_no_cues_until_shown_again() {
19055 let track = SubtitleTrack {
19056 path: FILE.into(),
19057 track: None,
19058 language: "eng".into(),
19059 name: String::new(),
19060 label: "eng".into(),
19061 cues: vec![crate::subtitle::Cue {
19062 start_us: 8_000_000,
19063 end_us: 9_000_000,
19064 text: "a line".into(),
19065 image: None,
19066 words: Vec::new(),
19067 karaoke: Vec::new(),
19068 }],
19069 bitmap: false,
19070 refused: None,
19071 };
19072 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
19073 let s1 = p.add_lane(LaneKind::Subtitle);
19074 p.place_sub(
19075 s1,
19076 0,
19077 SubClip {
19078 start: 0,
19079 frames: 300,
19080 track: 0,
19081 in_us: 0,
19082 out_us: 10_000_000,
19083 link: None,
19084 },
19085 )
19086 .expect("placed");
19087 assert_eq!(p.sub_lane_cues(s1, FPS).len(), 1, "shown, the cue is there");
19088
19089 assert!(p.set_lane_hidden(s1, true));
19090 assert!(
19091 p.sub_lane_cues(s1, FPS).is_empty(),
19092 "hidden, the lane gives no cues"
19093 );
19094
19095 assert!(p.set_lane_hidden(s1, false));
19096 assert_eq!(
19097 p.sub_lane_cues(s1, FPS).len(),
19098 1,
19099 "shown again, the cue comes back"
19100 );
19101 }
19102
19103 /// The switches live in the lane list, so a snapshot carries them with the
19104 /// rest; and [`Project::with_lane_flags`] puts them back on load with no undo
19105 /// step, as [`Project::with_mix`] does for the volumes.
19106 #[test]
19107 fn lane_switches_come_back_on_load_without_an_undo_step() {
19108 let mut p = Project::single(FILE, 9);
19109 assert!(p.set_lane_locked(Lane::V1, true));
19110 assert!(p.set_lane_hidden(Lane::V1, true));
19111 let flags = p.lane_flags();
19112 assert_eq!(
19113 flags[0],
19114 LaneFlags {
19115 hidden: true,
19116 muted: false,
19117 locked: true,
19118 pan: 0.0,
19119 }
19120 );
19121 let back = Project::from_parts(
19122 p.sources().to_vec(),
19123 p.lanes()
19124 .into_iter()
19125 .map(|l| (l.kind, p.lane(l).to_vec()))
19126 .collect(),
19127 Vec::new(),
19128 Vec::new(),
19129 Vec::new(),
19130 )
19131 .expect("the same lanes load")
19132 .with_lane_flags(&flags);
19133 assert!(back.lane_hidden(Lane::V1) && back.lane_locked(Lane::V1));
19134 assert!(!back.lane_muted(Lane::A1));
19135 let mut back = back;
19136 assert!(!back.undo(), "a loaded switch is not an undo step");
19137 }
19138
19139 /// A track dragged to another place in the stack: the whole lane travels --
19140 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
19141 /// a video one, a lane that crosses one of its own kind swaps names with it
19142 /// (and swaps the composite with it), one undo puts the order back, and a
19143 /// save carries it.
19144 #[test]
19145 fn a_track_is_dragged_to_another_place_in_the_stack() {
19146 let mut p = three();
19147 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
19148 let before = shape(&p);
19149 let history = p.history.len();
19150
19151 // A1 over V1: the screen is rearranged and nothing else is. Both keep
19152 // their names -- neither crossed a lane of its own kind -- so every
19153 // handle a front-end holds still names the track it named before.
19154 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
19155 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
19156 assert_eq!(
19157 shape(&p),
19158 vec![before[1].clone(), before[0].clone()],
19159 "each lane's clips travelled with it, and none was remapped"
19160 );
19161 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
19162 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
19163 invariants_hold(&p, "A1 over V1");
19164
19165 // Nothing moves for a lane that is not there, a slot that is not, or a
19166 // lane already standing in the one it was pointed at.
19167 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
19168 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
19169 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
19170 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
19171
19172 // ...and one stroke puts the order back.
19173 assert!(p.undo());
19174 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
19175 assert_eq!(shape(&p), before);
19176
19177 // A second video lane over the first: display order *is* the stack, so
19178 // the last video lane covering a frame is the picture that shows.
19179 let v2 = p.add_lane(LaneKind::Video);
19180 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
19181 let over = shape(&p)[2].clone();
19182 assert_eq!(
19183 p.composite_span_at(0).map(|s| s.len),
19184 Some(5),
19185 "V2's five frames are what frame 0 shows"
19186 );
19187
19188 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
19189 // a position among the lanes of its kind. The picture that wins changes
19190 // with it: the take that was covering is the covered one now.
19191 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
19192 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
19193 assert_eq!(
19194 shape(&p),
19195 vec![over.clone(), before[0].clone(), before[1].clone()],
19196 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
19197 );
19198 assert_eq!(
19199 p.composite_span_at(0).map(|s| s.len),
19200 Some(3),
19201 "the lower video lane wins, and it is the old V1 now"
19202 );
19203 invariants_hold(&p, "V2 over V1");
19204
19205 // A save writes that order and a load takes it back.
19206 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
19207 assert_eq!(
19208 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
19209 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
19210 );
19211 let back =
19212 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
19213 assert_eq!(back.lanes(), p.lanes());
19214 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
19215
19216 assert!(p.undo(), "and the stack goes back to how it stood");
19217 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
19218 }
19219
19220 /// The grouping rule across more than two lanes, under the offset model: a
19221 /// split *keeps* the group on the left halves and hands the right halves of
19222 /// that group one fresh id of their own -- a clip in no group comes out of
19223 /// the cut in none. So a take cut apart is two takes, one per side, and a
19224 /// lane that was never part of it stays out of both.
19225 #[test]
19226 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
19227 let mut p = Project::single(FILE, 9);
19228 let take = p.clips()[0].link.expect("a fresh project is one take");
19229 let v2 = p.add_lane(LaneKind::Video);
19230 assert!(
19231 p.place(v2, 0, clip(0, 0, 9, 0)),
19232 "a placement joins no group"
19233 );
19234 assert!(p.split(4));
19235 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
19236 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
19237 };
19238 let (left, right) = (side(&p, 0), side(&p, 1));
19239 // The lanes in order are V1, A1, V2: the take's two keep its id on the
19240 // left, and the placed clip never had one for the cut to keep.
19241 assert_eq!(
19242 left,
19243 vec![Some(take), Some(take), None],
19244 "the left halves keep the take"
19245 );
19246 // ...and the right halves of that take are one fresh group.
19247 assert_eq!(right[0], right[1]);
19248 assert_ne!(right[0], Some(take));
19249 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
19250 invariants_hold(&p, "split across three lanes");
19251
19252 // V2 ends early: the left halves still keep what each clip carried --
19253 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
19254 // shared by exactly the take's lanes.
19255 let mut p = Project::single(FILE, 9);
19256 let v2 = p.add_lane(LaneKind::Video);
19257 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
19258 assert!(p.split(3));
19259 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
19260 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
19261 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
19262 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
19263 invariants_hold(&p, "split where one lane ends early");
19264
19265 // The inverse rejoins each lane into the group its left half kept.
19266 assert!(p.regroup(3));
19267 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
19268 assert_eq!(
19269 p.lane(Lane::V1)[0].link,
19270 Some(take),
19271 "the take's id is back, not a fresh one"
19272 );
19273 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
19274 invariants_hold(&p, "regroup across three lanes");
19275 }
19276
19277 /// A group is one placement per lane, on however many lanes carry the id --
19278 /// not a video/audio pair and not a pairing by `ord` -- and the members may
19279 /// cover whatever frames they cover: the offset between them is what a
19280 /// hand-built group keeps. Lanes built by hand, because the rule is checked
19281 /// at the untrusted door and no edit can produce the one thing it refuses.
19282 #[test]
19283 fn a_group_may_span_any_lane() {
19284 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
19285 let one = |start: u32, end: u32, link| Clip {
19286 speed_keys: Vec::new(),
19287 reversed: false,
19288 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
19289 angle: Default::default(),
19290 fade_in: 0,
19291 fade_out: 0,
19292 transition_out: 0,
19293 transition_kind: Default::default(),
19294 visualizer: 0,
19295 viz_paint: 0,
19296 gain_db: 0.0,
19297 gain_keys: Vec::new(),
19298 pan: 0,
19299 pitch: 0,
19300 transform_keys: Vec::new(),
19301 opacity_keys: Vec::new(),
19302 color_keys: Vec::new(),
19303 effects: Vec::new(),
19304 start,
19305 in_frame: start,
19306 out_frame: end,
19307 source: 0,
19308 link: Some(link),
19309 eq: None,
19310 color: None,
19311 transform: None,
19312 fit: FitPolicy::default(),
19313 speed: Speed::NORMAL,
19314 };
19315 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
19316 let kinds = [
19317 LaneKind::Video,
19318 LaneKind::Audio,
19319 LaneKind::Video,
19320 LaneKind::Audio,
19321 ];
19322 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
19323 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
19324 };
19325 let take = || vec![one(0, 4, 7)];
19326 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
19327 // The same take on V1 + A2 only, the lanes between it empty: legal, the
19328 // way a lifted half is legal.
19329 let across = build([take(), Vec::new(), Vec::new(), take()]);
19330 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
19331 // ...and so is a group whose members disagree about their spans: the
19332 // offset between them is the hand's business, not the loader's.
19333 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
19334 assert!(
19335 links_are_consistent(&apart).is_ok(),
19336 "[0, 4) on V1 and [2, 6) on A2 are one group"
19337 );
19338 // One id twice in one lane is still that lane's error, by name.
19339 let twice = build([
19340 Vec::new(),
19341 Vec::new(),
19342 vec![one(0, 4, 7), one(4, 8, 7)],
19343 Vec::new(),
19344 ]);
19345 assert_eq!(
19346 links_are_consistent(&twice).unwrap_err().to_string(),
19347 "link 7 names two clips in the V2 lane"
19348 );
19349 }
19350
19351 /// Every lane a save writes comes out, in display order and with its kind --
19352 /// an empty one included, since it is state a front-end shows -- and a
19353 /// two-lane project still writes exactly the parts it always did.
19354 #[test]
19355 fn a_save_writes_every_lane_it_has() {
19356 let mut p = three();
19357 let before = p.without_orphan_sources();
19358 assert_eq!(before.1.len(), 2, "V1 and A1");
19359 let v2 = p.add_lane(LaneKind::Video);
19360 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
19361 let a2 = p.add_lane(LaneKind::Audio);
19362 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
19363 assert_eq!(
19364 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
19365 [
19366 LaneKind::Video,
19367 LaneKind::Audio,
19368 LaneKind::Video,
19369 LaneKind::Audio
19370 ],
19371 "display order, not video-then-audio"
19372 );
19373 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
19374 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
19375 // ...and all four load again as the same four.
19376 let back =
19377 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
19378 assert_eq!(back.lanes(), p.lanes());
19379 assert_eq!(back.lane(a2), p.lane(a2));
19380
19381 // Taking the lanes back leaves exactly what a two-lane save wrote.
19382 for _ in 0..3 {
19383 assert!(p.undo());
19384 }
19385 assert_eq!(
19386 p.without_orphan_sources(),
19387 before,
19388 "byte for byte the same parts a two-lane save always wrote"
19389 );
19390 }
19391
19392 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
19393 /// three lanes and grows more: every lane's own order and the one
19394 /// span-per-id rule after every op, *and* the reload the v4 format restored
19395 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
19396 /// project of any number of lanes.
19397 #[test]
19398 fn random_edit_sequences_keep_many_lanes_consistent() {
19399 for seed in 0..2000u64 {
19400 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
19401 let mut next = move |n: u32| {
19402 rng ^= rng << 13;
19403 rng ^= rng >> 7;
19404 rng ^= rng << 17;
19405 (rng >> 33) as u32 % n
19406 };
19407 let mut p = Project::single(FILE, 40);
19408 let v2 = p.add_lane(LaneKind::Video);
19409 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
19410 let lanes = [Lane::V1, Lane::A1, v2];
19411 for step in 0..24 {
19412 let frame = next(44);
19413 let copied = p
19414 .lane(lanes[next(3) as usize])
19415 .get(next(4) as usize)
19416 .cloned()
19417 .unwrap_or_else(|| clip(0, 0, 5, 0));
19418 let lane = lanes[next(3) as usize];
19419 let idx = next(4) as usize;
19420 let _ = match next(14) {
19421 // The drag, in the mix: a clip dragged along its own lane
19422 // and onto another one, at a frame the pointer picked --
19423 // which is where the group rule and the sorted+disjoint one
19424 // meet, since every half travels the same distance.
19425 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
19426 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
19427 11 => p.set_eq(lane, idx, None),
19428 // A rate, which on many lanes is the group rule as well:
19429 // every clip carrying the link moves together or none of
19430 // them does, and `invariants_hold` is what says so.
19431 12 => p
19432 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
19433 .is_ok(),
19434 0 => p.split(frame),
19435 1 => p.regroup(frame),
19436 2 => p.lift(lane, idx),
19437 3 => p.place(lane, frame, copied.clone()),
19438 4 => p.paste(frame, copied.clone()),
19439 5 => p.ripple_delete(frame, next(9)),
19440 6 => p.delete(idx),
19441 7 => p.undo(),
19442 8 => {
19443 p.add_lane(if next(2) == 0 {
19444 LaneKind::Video
19445 } else {
19446 LaneKind::Audio
19447 });
19448 true
19449 }
19450 _ => p.append_clip(0, 1 + next(9)),
19451 };
19452 invariants_hold(&p, &format!("seed {seed}, step {step}"));
19453 reloads(&p, &format!("seed {seed}, step {step}"));
19454 }
19455 }
19456 }
19457
19458 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
19459 /// there, `V1` shows again on either side of it, and a frame no video lane
19460 /// covers is a gap however many lanes there are.
19461 #[test]
19462 fn the_composite_is_the_topmost_lane_with_a_clip() {
19463 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19464 let lanes = vec![
19465 // V1: the whole 30 frames of source 0.
19466 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19467 // V2: source 1 over the middle third.
19468 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
19469 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19470 ];
19471 let p =
19472 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
19473 assert_eq!(
19474 p.composite_spans_from(0),
19475 vec![
19476 Span {
19477 reverse: false,
19478 ramp: None,
19479 start: 0,
19480 len: 10,
19481 from: Some((0, 0)),
19482 speed: Speed::NORMAL,
19483 pitch: 0,
19484 },
19485 Span {
19486 reverse: false,
19487 ramp: None,
19488 start: 10,
19489 len: 10,
19490 from: Some((1, 5)),
19491 speed: Speed::NORMAL,
19492 pitch: 0,
19493 },
19494 Span {
19495 reverse: false,
19496 ramp: None,
19497 start: 20,
19498 len: 10,
19499 from: Some((0, 20)),
19500 speed: Speed::NORMAL,
19501 pitch: 0,
19502 },
19503 ],
19504 "V2 takes over for its own span and hands V1 back"
19505 );
19506 // A mid-span ask resolves the same way, which is what a seek does.
19507 assert_eq!(
19508 p.composite_span_at(15),
19509 Some(Span {
19510 reverse: false,
19511 ramp: None,
19512 start: 15,
19513 len: 5,
19514 from: Some((1, 10)),
19515 speed: Speed::NORMAL,
19516 pitch: 0,
19517 })
19518 );
19519 assert_eq!(p.composite_span_at(30), None, "past the end");
19520
19521 // A hole in V1 under V2's clip: black between the two, and black after
19522 // both run out (the audio lane is still holding the timeline open).
19523 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19524 let holed = vec![
19525 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
19526 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
19527 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19528 ];
19529 let p =
19530 Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
19531 assert_eq!(
19532 p.composite_spans_from(0),
19533 vec![
19534 Span {
19535 reverse: false,
19536 ramp: None,
19537 start: 0,
19538 len: 5,
19539 from: Some((0, 0)),
19540 speed: Speed::NORMAL,
19541 pitch: 0,
19542 },
19543 Span {
19544 reverse: false,
19545 ramp: None,
19546 start: 5,
19547 len: 5,
19548 from: None,
19549 speed: Speed::NORMAL,
19550 pitch: 0,
19551 },
19552 Span {
19553 reverse: false,
19554 ramp: None,
19555 start: 10,
19556 len: 10,
19557 from: Some((1, 0)),
19558 speed: Speed::NORMAL,
19559 pitch: 0,
19560 },
19561 Span {
19562 reverse: false,
19563 ramp: None,
19564 start: 20,
19565 len: 10,
19566 from: None,
19567 speed: Speed::NORMAL,
19568 pitch: 0,
19569 },
19570 ]
19571 );
19572
19573 // One video lane: the composite *is* that lane, span for span -- the
19574 // promise every existing two-lane project rests on.
19575 let p = Project::single(FILE, 30);
19576 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
19577 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
19578 }
19579
19580 /// Every audio lane holding something gets a play list, and only those.
19581 #[test]
19582 fn audio_segments_cover_every_lane_that_holds_something() {
19583 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19584 let lanes = vec![
19585 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19586 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19587 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
19588 (LaneKind::Audio, Vec::new()),
19589 ];
19590 let p =
19591 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
19592 let lists = p.audio_segments_from(0, FPS);
19593 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
19594 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
19595 // A2 is a gap up to frame 15, then the whole of source 1.
19596 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
19597
19598 // No audio lane holds anything: one all-gap list, so such a timeline
19599 // still plays silence against a master clock.
19600 let p = Project::from_parts(
19601 vec![Source::new(FILE, 0)],
19602 vec![
19603 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19604 (LaneKind::Audio, Vec::new()),
19605 ],
19606 vec![],
19607 vec![],
19608 Vec::new(),
19609 )
19610 .expect("valid parts");
19611 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
19612 }
19613
19614 /// D4: removing a subtitle column used to clear the whole undo history,
19615 /// because a placement names its track by index into the palette and the
19616 /// reindex left every later entry naming the wrong one. The entry holds the
19617 /// palette beside the lanes now, so the reindex undoes with it.
19618 #[test]
19619 fn removing_a_subtitle_column_undoes_with_its_reindex() {
19620 let track = |label: &str| SubtitleTrack {
19621 path: FILE.into(),
19622 track: None,
19623 language: "eng".into(),
19624 name: String::new(),
19625 label: label.into(),
19626 cues: Vec::new(),
19627 bitmap: false,
19628 refused: None,
19629 };
19630 let mut p = Project::single(FILE, 300).with_subtitles(vec![
19631 track("one"),
19632 track("two"),
19633 track("three"),
19634 ]);
19635 assert_eq!(p.subtitles().len(), 3);
19636 let before = p.parts();
19637 let palette = p.subtitles().to_vec();
19638 // Column 0 goes, which renumbers the two behind it.
19639 p.remove_subtitles(0).expect("a column with nothing on it");
19640 assert_eq!(p.subtitles().len(), 2);
19641 assert_eq!(p.subtitles()[0].label, "two");
19642 assert!(p.undo(), "the removal is a step like any other cut");
19643 // The palette itself, and not only what `parts` happens to compare: this
19644 // is the assertion that cannot go vacuous if the restore below it ever
19645 // leaves a field of it behind.
19646 assert_eq!(
19647 p.subtitles(),
19648 palette.as_slice(),
19649 "the palette itself, back"
19650 );
19651 assert_eq!(p.parts(), before, "the palette and the lanes, both back");
19652 assert!(p.redo(), "and forward again");
19653 assert_eq!(p.subtitles().len(), 2, "the column goes again");
19654 assert_eq!(p.subtitles()[0].label, "two");
19655 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");
19656 }
19657
19658 /// Finds every line that **writes** a caption's clock, in three forms: an
19659 /// assignment through any operator (`.out_us = `, `.out_us += `,
19660 /// `.out_us <<= `), a struct-literal field (`out_us: ...`) and the
19661 /// shorthand form (`out_us,`). A `let` binding is skipped for the literal
19662 /// forms only, so `let x: &mut SubClip = ..; (*x).in_us = 5;` is still
19663 /// caught while `let out_us = s.out_us;` is not.
19664 ///
19665 /// The operator list is `=` plus one assignment operator each, and
19666 /// deliberately excludes `<=`: the first version of this matcher counted
19667 /// `s.out_us <= s.in_us` as a write, which would have flagged every
19668 /// never-empty check in the file.
19669 fn window_writes(text: &str) -> Vec<(usize, String)> {
19670 const FIELDS: [&str; 2] = ["in_us", "out_us"];
19671 const OPS: [&str; 11] = [
19672 "=", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "<<=", ">>=",
19673 ];
19674 let mut found = Vec::new();
19675 for (n, raw) in text.lines().enumerate() {
19676 let line = raw.trim();
19677 if line.starts_with("//") {
19678 continue;
19679 }
19680 let is_binding = line.starts_with("let ");
19681 // `let (a, b) = ..` is a tuple pattern, not a struct literal: the
19682 // commas there bind names. `let half = SubClip { frames: n, in_us,
19683 // out_us, ..s };` is the opposite -- the same commas are shorthand
19684 // fields -- and what separates them is the paren, not the `let`.
19685 let tuple_pattern = line.starts_with("let (");
19686 for field in FIELDS {
19687 let access = format!(".{field}");
19688 if let Some(at) = line.find(&access) {
19689 let after = &line[at + access.len()..];
19690 let after = after.trim_start();
19691 if OPS
19692 .iter()
19693 .any(|op| after.starts_with(op) && !after[op.len()..].starts_with('='))
19694 {
19695 found.push((n + 1, line.to_owned()));
19696 continue;
19697 }
19698 }
19699 // A bare name: a literal field, a shorthand, or a local
19700 // binding. Skipped when a `.` or an identifier character
19701 // precedes it -- that is a read, not a field being set.
19702 //
19703 // The `let` exclusion is per-occurrence and keyed on what
19704 // FOLLOWS, not on the line. `let out_us = s.out_us;` names a
19705 // local, so the `=` form is skipped; but `let tail = SubClip {
19706 // in_us: cut, out_us: s.out_us, ..s };` is a struct literal
19707 // behind a `let`, and an earlier version of this matcher
19708 // skipped the whole line for being a `let` -- so that shape,
19709 // which is exactly what a plausible composer looks like, went
19710 // through green. Keyed on the follower, a `let` hides nothing.
19711 for (at, _) in line.match_indices(field) {
19712 let preceded_by_name = line[..at]
19713 .chars()
19714 .next_back()
19715 .is_some_and(|c| c == '.' || c.is_alphanumeric() || c == '_');
19716 if preceded_by_name {
19717 continue;
19718 }
19719 let after = line[at + field.len()..].trim_start();
19720 let sets_a_field =
19721 after.starts_with(':') || (after.starts_with(',') && !tuple_pattern);
19722 let names_a_local = after.starts_with('=') && !after[1..].starts_with('=');
19723 if sets_a_field || (names_a_local && !is_binding) {
19724 found.push((n + 1, line.to_owned()));
19725 break;
19726 }
19727 }
19728 }
19729 }
19730 found
19731 }
19732
19733 /// A **heuristic guard**, not a proof. The honest reading of a green here
19734 /// is the residual risk in this comment, not the green itself.
19735 ///
19736 /// Three rounds of review each found one more composer a per-arm check had
19737 /// missed -- a tail trim, a head trim, a rejoin that SUMS two legal
19738 /// widths -- and each produced the same failure: the editor wrote a
19739 /// `.edith` its own loader then refused, with no in-app way back. The
19740 /// invariant is now structural in the code (every composer calls
19741 /// [`set_window`]); this is what keeps that structure from quietly losing
19742 /// a caller.
19743 ///
19744 /// **Why this is a scan and not the compiler**, which is the better answer
19745 /// and was priced rather than skipped: making `in_us`/`out_us` private to
19746 /// this module turns every outside write into a compile error, which no
19747 /// one-token edit can defeat. It costs 74 `SubClip` construction sites
19748 /// (31 of them in this crate's own integration tests) plus a public
19749 /// constructor, and it reaches `crates/app`'s `timeline_edit.rs` and
19750 /// `timeline_math.rs`, which other lanes own. That is a refactor of a
19751 /// door's public shape rather than a bound, and the wrong size for this
19752 /// lane -- so the guard stands here with its limits written down instead.
19753 ///
19754 /// **Residual risk, by class, most likely first.** These are not all
19755 /// equally hypothetical; the first is the one a real composer would reach
19756 /// for, and it is the one this matcher cannot see at all:
19757 ///
19758 /// 1. **Field-less writes.** `*a = *b;`, `*a = other;`,
19759 /// `std::mem::swap(a, b)`, `a.clone_from(b)`, and any macro that
19760 /// expands to a field write (`bump!(s.out_us, by)`). None of these ever
19761 /// spell `in_us` or `out_us` on the line, so `window_writes` returns
19762 /// nothing for all of them. A *helper* that writes the field directly IS
19763 /// caught; it is specifically the whole-struct and macro forms that go
19764 /// through. This is the class most likely to be used, and it is
19765 /// unmatched by construction rather than by oversight.
19766 /// 2. **A rename.** The matcher keys on the literal strings `in_us` and
19767 /// `out_us`. Renaming the fields silences it entirely while it stays
19768 /// green -- the sharpest failure here, because the guard is supposed to
19769 /// be the thing that notices a rule drifting.
19770 /// 3. **A writer inside a test.** `/tests/` paths and `mod tests` blocks
19771 /// are cut. A test cannot produce a file a user loses, so the line is
19772 /// drawn there deliberately, not by omission.
19773 /// 4. **A file the walk does not reach**: a path outside `crates/`, or one
19774 /// under a directory named `target`, `.git`, `vendor`, or any
19775 /// dot-directory (`.delta/` holds scratch clones of other checkouts).
19776 ///
19777 /// What the matcher DOES now cover, after four rounds of it not doing so:
19778 /// every assignment operator; struct-literal fields and the shorthand form,
19779 /// including behind a `let`; writes through an indirect `&mut`; and every
19780 /// `.rs` under `crates/` with no filter on what the file contains, so a
19781 /// glob import or a type alias can no longer hide a module.
19782 #[test]
19783 fn every_window_write_outside_set_window_is_named() {
19784 // `CARGO_MANIFEST_DIR`, not `file!()`: a test runs with the WORKSPACE
19785 // root as its working directory, so `file!()`'s crate-relative path
19786 // does not resolve from where the binary actually starts.
19787 let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19788 .parent()
19789 .and_then(std::path::Path::parent)
19790 .expect("crates/engine sits two levels under the workspace root")
19791 .to_path_buf();
19792 // Every line in the workspace that names a clock and is not a
19793 // composer, each with its reason. A new entry is a claim someone has
19794 // to defend in review, which is the point of writing the list out.
19795 let allowed = [
19796 ("pub in_us: i64,", "the field declaration"),
19797 ("pub out_us: i64,", "the field declaration"),
19798 (
19799 "fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {",
19800 "set_window's own signature",
19801 ),
19802 ("s.in_us = in_us;", "set_window"),
19803 ("s.out_us = out_us;", "set_window"),
19804 (
19805 "set_window(&mut data.subs[idx], in_us, out_us);",
19806 "regroup naming the two values it is about to set",
19807 ),
19808 ("in_us: micros(f[3], n)?,", "edith.rs: the parse door"),
19809 ("out_us: micros(f[4], n)?,", "edith.rs: the parse door"),
19810 // Non-test helpers that build a value to hand `place_sub`, which is
19811 // a door. Not composers: nobody was mid-gesture, which is exactly
19812 // why a door refuses where a composer clamps.
19813 (
19814 "in_us: 0,",
19815 "sweep.rs caption helper, and timeline_edit.rs's palette row, -> place_sub",
19816 ),
19817 (
19818 "out_us: i64::from(frames) * 1_000_000,",
19819 "sweep.rs caption helper -> place_sub",
19820 ),
19821 // `SubClip::whole_track`: the one constructor a palette drop uses; its
19822 // window is the frames' own length, and the value goes to place_sub.
19823 (
19824 "SubClip { start: 0, frames, track, in_us: 0, out_us, link: None }",
19825 "SubClip::whole_track: whole-track value -> place_sub",
19826 ),
19827 ];
19828
19829 let mut found: Vec<String> = Vec::new();
19830 let (mut files, mut lines) = (0usize, 0usize);
19831 let mut seen_app = false;
19832 for (file, text) in read_workspace_rust(&workspace) {
19833 // Test code, by path or by module: a test builds `SubClip`s by hand
19834 // and its value is not one the loader ever reads, so the 31 sites in
19835 // `crates/engine/tests/` and three in `crates/app/src/tests/` are
19836 // not composers. A real limit rather than a technicality -- the
19837 // guard does not cover a writer hidden inside a test -- but a test
19838 // cannot produce a file a user loses, so it is where the line goes.
19839 let path = file.to_string_lossy().replace('\\', "/");
19840 if path.contains("/tests/") {
19841 continue;
19842 }
19843 let code = match text.find("\n#[cfg(test)]\nmod tests {") {
19844 Some(at) => &text[..at],
19845 None => text.as_str(),
19846 };
19847 lines += code.lines().count();
19848 files += 1;
19849 seen_app |= path.contains("crates/app/");
19850 for (n, line) in window_writes(code) {
19851 if !allowed.iter().any(|(text, _)| *text == line) {
19852 let at = file.strip_prefix(&workspace).unwrap_or(&file);
19853 found.push(format!("{}:{n}: {line}", at.display()));
19854 }
19855 }
19856 }
19857 // A floor, not a census: the walk now opens EVERY `.rs` under
19858 // `crates/` that is not test code -- 86 files and ~77,600 lines today,
19859 // which is 141 files and ~116,000 before `/tests/` and `mod tests` are
19860 // cut. The point is only to catch a walk rooted in the wrong place,
19861 // which reads a file or two.
19862 // The `seen_app` half is the one that matters: the two-file version of
19863 // this guard read `project.rs` and `edith.rs` and was silently
19864 // certifying a claim about the app it had never opened, and the
19865 // `contains("SubClip")` filter that came next
19866 // was the same mistake wearing a derived hat -- a file that reached
19867 // the type by glob import or alias was never opened either.
19868 assert!(
19869 lines > 70_000 && files >= 80 && seen_app,
19870 "the walk read {lines} lines in {files} files (app reached: \
19871 {seen_app}) -- it is not covering the workspace, and a guard that \
19872 reads nothing is worse than no guard because it reads as one"
19873 );
19874 // The assertion this whole test exists for. It was DELETED by a clumsy
19875 // edit while the coverage floor above was being retuned, and for a
19876 // moment the test reported green while `found` held a real offender --
19877 // the fourth version of this guard failing in the one way that looks
19878 // exactly like success. If you retune anything here, check this line
19879 // still exists.
19880 assert!(
19881 found.is_empty(),
19882 "a caption window is written outside set_window:\n {}",
19883 found.join("\n ")
19884 );
19885 }
19886
19887 /// The blind spot, pinned as cases. Every one of these is a write, and the
19888 /// guard exists because each of its earlier versions caught none of them --
19889 /// `s.out_us += by(...)` being a one-token edit that made it green while a
19890 /// grouped caption really did grow past the ceiling. A matcher that has
19891 /// quietly stopped matching is the failure mode that looks most like a
19892 /// pass, so it gets its own test rather than a comment.
19893 ///
19894 /// The last group is the opposite: the field-less forms that are a write
19895 /// and that this matcher CANNOT see. They are asserted to be missed, on
19896 /// purpose, so that the day someone can match them the test says so --
19897 /// and so nobody reads this file as claiming more than it does.
19898 #[test]
19899 fn the_window_write_matcher_catches_the_ways_a_composer_hides() {
19900 for (what, code) in [
19901 (
19902 "the one-token compound assignment",
19903 " s.out_us += by(s.end(), to);",
19904 ),
19905 ("a plain compound assignment", " s.in_us -= 1;"),
19906 ("a shift-assign", " s.out_us <<= 1;"),
19907 (
19908 "a write through a &mut the matcher cannot see past",
19909 " let x: &mut SubClip = q; (*x).in_us = 5;",
19910 ),
19911 (
19912 "a struct literal",
19913 " out.push(SubClip { in_us: 0, out_us: 1, ..s });",
19914 ),
19915 (
19916 "the shorthand form",
19917 " SubClip { in_us, out_us, ..s }",
19918 ),
19919 (
19920 "a struct literal behind a `let`, which the old line-wide `let` \
19921 exclusion skipped whole",
19922 " let tail = SubClip { in_us: cut, out_us: s.out_us, ..s };",
19923 ),
19924 (
19925 "a struct literal behind a `let` using the shorthand too",
19926 " let half = SubClip { frames: n, in_us, out_us, ..s };",
19927 ),
19928 ] {
19929 assert!(
19930 !window_writes(code).is_empty(),
19931 "the matcher misses {what}: {code:?}"
19932 );
19933 }
19934 // ...and the other side, so the allowlist is not padded with reads.
19935 for quiet in [
19936 " if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {",
19937 " debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);",
19938 " let out_us = s.out_us;",
19939 " (next.start == frame && next.in_us == subs[idx].out_us)",
19940 " let total = s.out_us - s.in_us;",
19941 ] {
19942 assert!(
19943 window_writes(quiet).is_empty(),
19944 "the matcher flags a read as a write: {quiet:?}"
19945 );
19946 }
19947 // The class this matcher CANNOT see, asserted as missed. Each of these
19948 // really does write a caption's window and none of them spell the field
19949 // name, so a field matcher returns nothing -- that is a property of the
19950 // approach, not a bug to be fixed here, and the test exists so the
19951 // doc comment's residual-risk list cannot quietly grow a claim this
19952 // matcher has not earned. If one of these ever starts matching, this
19953 // test fails and asks which side of the line moved.
19954 for unmatchable in [
19955 " *a = *b;",
19956 " *a = other;",
19957 " std::mem::swap(a, b);",
19958 " a.clone_from(b);",
19959 " bump!(s.out_us, by);",
19960 ] {
19961 assert!(
19962 window_writes(unmatchable).is_empty(),
19963 "the matcher now matches a field-less form it documented as \
19964 unmatched -- update the residual-risk list too: {unmatchable:?}"
19965 );
19966 }
19967 }
19968
19969 /// Every `.rs` under the workspace, paired with its text. Recursive
19970 /// because the set of files that can name `SubClip` is a fact about the
19971 /// tree, and a hardcoded pair of names goes stale the moment a lane adds a
19972 /// module -- which is how the two-file version of this guard came to
19973 /// certify a claim about `crates/app` it had never read.
19974 fn read_workspace_rust(root: &std::path::Path) -> Vec<(std::path::PathBuf, String)> {
19975 let mut out = Vec::new();
19976 let mut stack = vec![root.to_path_buf()];
19977 while let Some(dir) = stack.pop() {
19978 let Ok(entries) = std::fs::read_dir(&dir) else {
19979 continue;
19980 };
19981 for entry in entries.flatten() {
19982 let path = entry.path();
19983 if path.is_dir() {
19984 // `target` is not source and `vendor` is not ours to rule on.
19985 //
19986 // Every DOT-directory, for the same reason and one more: a
19987 // dot-dir is by convention not part of the tree we are
19988 // making claims about. This workspace root holds `.delta/`,
19989 // a scratch area of clones and worktrees left by delta/A-B
19990 // tooling, and the walk used to descend into it and report
19991 // the ten window writes inside a checkout that is not this
19992 // one -- so the guard was RED here for a file nobody edits,
19993 // and, worse, VACUOUS about its own tree: the same stale
19994 // clone that produced the noise could have hidden a real
19995 // offender behind it, and the floor below was being met in
19996 // part by lines this guard has no business reading. Skipping
19997 // the whole class rather than naming `.delta` is the point:
19998 // the next scratch dir a tool drops here is skipped too.
19999 let name = path.file_name().unwrap_or_default().to_string_lossy();
20000 let skip = name == "target"
20001 || name == ".git"
20002 || name == "vendor"
20003 || name.starts_with('.');
20004 if !skip {
20005 stack.push(path);
20006 }
20007 // EVERY `.rs`, with no filter on what it contains. The filter
20008 // that was here (`text.contains("SubClip")`) was a name-based
20009 // guess about which files can reach the type, and a glob import
20010 // or a type alias defeats it exactly as it defeats a
20011 // hardcoded file list: a new module holding the struct behind
20012 // `use engine::project::*;` was never opened, and stayed green.
20013 // The scan is text-only and the tree is small, so the honest
20014 // thing costs nothing here.
20015 } else if path.extension().is_some_and(|e| e == "rs")
20016 && let Ok(text) = std::fs::read_to_string(&path)
20017 {
20018 out.push((path, text));
20019 }
20020 }
20021 }
20022 out
20023 }
20024}
20025
20026#[cfg(test)]
20027mod title_tests {
20028 use super::*;
20029 use crate::text::{Outline, Place};
20030
20031 const FILE: &str = "/nonexistent/film.mkv";
20032
20033 fn title(start: u32, frames: u32, text: &str) -> Title {
20034 Title {
20035 start,
20036 frames,
20037 text: text.to_string(),
20038 style: TextStyle::default(),
20039 fade_in: 0,
20040 fade_out: 0,
20041 in_anim: Default::default(),
20042 out_anim: Default::default(),
20043 anim_frames: 0,
20044 keys: Vec::new(),
20045 }
20046 }
20047
20048 /// Going from 30 to 25 fps keeps the seconds: a title that shows for two
20049 /// seconds still shows for two (50 frames, not the 60 it was stored as),
20050 /// and every frame-counted envelope -- title fades, clip fades, the dissolve
20051 /// into the next clip, a volume point -- lands on the same moment of the
20052 /// new grid as the picture it belongs to.
20053 #[test]
20054 fn a_rate_change_rescales_titles_and_frame_envelopes() {
20055 let k = Rate::from_fps(30.0, 25.0).expect("a rate both grids name");
20056 let mut p = Project::single(FILE, 300);
20057 assert!(p.split(150));
20058 assert!(p.set_fade_in(Lane::A1, 0, 30));
20059 assert!(p.set_fade_out(Lane::A1, 0, 30));
20060 assert!(p.set_transition_out(Lane::V1, 0, 30));
20061 assert!(p.set_gain_keys(
20062 Lane::A1,
20063 0,
20064 vec![
20065 GainKey::new(60, -6.0),
20066 GainKey::new(120, -3.0),
20067 ],
20068 ));
20069 assert!(p.add_title(Title { fade_in: 0, fade_out: 12, ..title(0, 60, "Intro") }).is_ok());
20070 assert!(p.add_title(Title { fade_in: 12, fade_out: 0, ..title(90, 60, "Credit") }).is_ok());
20071
20072 p.retime(k, &[250]);
20073
20074 let t = p.titles();
20075 assert_eq!((t[0].start, t[0].frames, t[0].fade_out), (0, 50, 10));
20076 assert_eq!((t[1].start, t[1].frames, t[1].fade_in), (75, 50, 10));
20077 assert_eq!(t[0].frames * 6, 60 * 5, "the two seconds stay two seconds");
20078
20079 let a = p.lane(Lane::A1);
20080 assert_eq!((a[0].fade_in, a[0].fade_out), (25, 25));
20081 assert_eq!(p.lane(Lane::V1)[0].transition_out, 25);
20082 let keys: Vec<u32> = a[0].gain_keys.iter().map(|g| g.at).collect();
20083 assert_eq!(keys, [50, 100], "volume points follow their footage");
20084 }
20085
20086 #[test]
20087 fn title_add_set_remove_and_undo_redo() {
20088 let mut p = Project::single(FILE, 150);
20089 assert_eq!(p.add_title(title(160, 40, "Episode 17")).unwrap(), 0);
20090 assert_eq!(
20091 p.add_title(title(10, 20, "Intro")).unwrap(),
20092 0,
20093 "kept sorted by start"
20094 );
20095 assert_eq!(p.titles()[0].text, "Intro");
20096 assert_eq!(
20097 p.timeline_frames(),
20098 200,
20099 "a title past the clip extends the timeline"
20100 );
20101 assert_eq!(p.media_frames(), 200, "and the picture runs on over black");
20102
20103 assert!(p.undo());
20104 assert_eq!(p.titles().len(), 1);
20105 assert_eq!(p.timeline_frames(), 200);
20106 assert!(p.undo());
20107 assert!(p.titles().is_empty());
20108 assert_eq!(p.timeline_frames(), 150, "the timeline shrinks back");
20109 assert!(p.redo());
20110 assert!(p.redo());
20111 assert_eq!(p.titles().len(), 2);
20112
20113 assert!(p.remove_title(0));
20114 assert_eq!(p.titles().len(), 1);
20115 assert!(p.undo());
20116 assert_eq!(p.titles().len(), 2);
20117 assert!(!p.remove_title(9), "an index that is not there is refused");
20118
20119 let mut edited = p.titles()[1].clone();
20120 edited.text = "Episode 18".into();
20121 assert!(p.set_title(1, edited.clone()));
20122 assert!(!p.set_title(1, edited), "the same title is no edit");
20123 assert_eq!(p.titles()[1].text, "Episode 18");
20124 assert!(p.undo());
20125 assert_eq!(p.titles()[1].text, "Episode 17");
20126 }
20127
20128 #[test]
20129 fn chapter_add_set_move_remove_and_undo() {
20130 let chapter = |frame, title: &str| Chapter { frame, title: title.into() };
20131 let mut p = Project::single(FILE, 300);
20132 assert_eq!(p.add_chapter(chapter(150, "Setup")).unwrap(), 0);
20133 assert_eq!(p.add_chapter(chapter(0, "Intro")).unwrap(), 0, "kept sorted by frame");
20134 assert!(p.add_chapter(chapter(150, "Again")).is_err(), "one chapter per frame");
20135 assert!(p.add_chapter(chapter(20, " ")).is_err(), "a chapter needs a name");
20136 assert_eq!(p.chapters().len(), 2, "a refusal changes nothing");
20137
20138 assert!(p.undo());
20139 assert_eq!(p.chapters(), &[chapter(150, "Setup")], "undo takes back the last add");
20140 assert!(p.undo());
20141 assert!(p.chapters().is_empty());
20142 assert!(p.redo());
20143 assert!(p.redo());
20144
20145 assert_eq!(p.move_chapter(0, 200).unwrap(), 1, "its index follows its frame");
20146 assert_eq!(p.chapters()[1], chapter(200, "Intro"));
20147 assert!(p.move_chapter(0, 200).is_err(), "a frame another chapter holds is refused");
20148 assert!(p.move_chapter(9, 10).is_err(), "an index that is not there is refused");
20149
20150 assert!(p.set_chapter_title(0, "Begin"));
20151 assert!(!p.set_chapter_title(0, "Begin"), "the same name is no edit");
20152 assert!(!p.set_chapter_title(0, ""), "an empty name is refused");
20153 assert!(p.remove_chapter(1));
20154 assert_eq!(p.chapters(), &[chapter(150, "Begin")]);
20155 assert!(!p.remove_chapter(4), "an index that is not there is refused");
20156 assert!(p.undo());
20157 assert_eq!(p.chapters().len(), 2);
20158 assert_eq!(p.chapters()[0], chapter(150, "Begin"), "the rename is still there");
20159 assert_eq!(p.chapters()[1], chapter(200, "Intro"));
20160 }
20161
20162 #[test]
20163 fn the_caption_style_is_an_undoable_project_setting() {
20164 use crate::captionanim::{CaptionAnim, CaptionStyle};
20165 let mut p = Project::single(FILE, 9);
20166 assert_eq!(p.caption_style(), CaptionStyle::default());
20167 assert!(!p.set_caption_style(CaptionStyle::default()), "the style in force is no step");
20168 let karaoke = CaptionStyle { anim: CaptionAnim::Karaoke, words_per_line: 40, ..CaptionStyle::default() };
20169 assert!(p.set_caption_style(karaoke));
20170 assert_eq!(p.caption_style().words_per_line, crate::captionanim::MAX_WORDS_PER_LINE, "clamped");
20171 assert!(p.undo());
20172 assert_eq!(p.caption_style(), CaptionStyle::default());
20173 assert!(p.redo());
20174 assert_eq!(p.caption_style().anim, CaptionAnim::Karaoke);
20175 }
20176
20177 #[test]
20178 fn markers_add_set_remove_remap_and_undo() {
20179 let m = |frame, length, name: &str| Marker { frame, length, name: name.into(), note: String::new(), color: MarkerColor::Red };
20180 let mut p = Project::single(FILE, 9);
20181 assert_eq!(p.add_marker(m(100, 0, "B")).unwrap(), 0);
20182 assert_eq!(p.add_marker(m(10, 40, "A")).unwrap(), 0, "kept sorted by frame");
20183 assert_eq!(p.add_marker(m(100, 0, "B2")).unwrap(), 2, "a second on a frame goes after the first");
20184 assert!(p.add_marker(m(5, 0, " ")).is_err(), "a marker needs a name");
20185 assert_eq!(p.markers().len(), 3);
20186 assert!(p.undo());
20187 assert_eq!(p.markers().len(), 2, "undo takes back the last add");
20188 // A set that moves the frame re-sorts; an identical set is refused.
20189 assert_eq!(p.set_marker(0, m(200, 0, "A")).unwrap(), 1);
20190 assert!(p.set_marker(1, m(200, 0, "A")).is_err());
20191 assert!(p.set_marker(9, m(1, 0, "x")).is_err());
20192 // A remap moves a range's start and end; a ripple inside a range grows it.
20193 assert!(p.remap_markers(|f| if f >= 150 { f + 30 } else { f }));
20194 assert_eq!(p.markers()[0].frame, 100);
20195 assert_eq!(p.markers()[1].frame, 230);
20196 assert!(!p.remap_markers(|f| f), "no frame moves: no step");
20197 assert!(p.undo());
20198 assert_eq!(p.markers()[1].frame, 200, "one undo takes the whole remap back");
20199 let mut q = Project::single(FILE, 9);
20200 q.add_marker(m(10, 40, "R")).unwrap();
20201 assert!(q.remap_markers(|f| if f >= 30 { f + 100 } else { f }));
20202 assert_eq!((q.markers()[0].frame, q.markers()[0].length), (10, 140), "an insert inside a range grows it");
20203 assert!(q.remap_markers(|f| if f >= 20 { 20 } else { f }));
20204 assert_eq!(q.markers()[0].length, 10, "a cut through a range shortens it");
20205 assert!(q.remove_marker(0));
20206 assert!(!q.remove_marker(0));
20207 }
20208
20209 #[test]
20210 fn remap_chapters_is_one_undo_step_and_keeps_the_first_of_a_pair() {
20211 let mut p = Project::single(FILE, 300);
20212 p.add_chapter(Chapter { frame: 0, title: "A".into() }).unwrap();
20213 p.add_chapter(Chapter { frame: 50, title: "B".into() }).unwrap();
20214 p.add_chapter(Chapter { frame: 60, title: "C".into() }).unwrap();
20215 // C moves onto B's frame, so it is the one dropped.
20216 let dropped = p.remap_chapters(|f| if f == 60 { 50 } else { f });
20217 assert_eq!(dropped, 1);
20218 let titles: Vec<&str> = p.chapters().iter().map(|c| c.title.as_str()).collect();
20219 assert_eq!(titles, ["A", "B"]);
20220 assert!(p.undo());
20221 assert_eq!(p.chapters().len(), 3, "one undo brings back every chapter");
20222 assert_eq!(p.remap_chapters(|f| f), 0, "no frame moves: no step");
20223 assert!(p.undo());
20224 assert_eq!(p.chapters().len(), 2, "the step before was the add of C");
20225 }
20226
20227 #[test]
20228 fn title_refusals_change_nothing() {
20229 let mut p = Project::single(FILE, 150);
20230 let before = p.clone();
20231 assert!(p.add_title(title(0, 0, "none")).is_err(), "no frames");
20232 assert!(p.add_title(title(0, 10, " ")).is_err(), "no text");
20233 assert!(
20234 p.add_title(title(0, 10, &"x".repeat(MAX_TITLE_CHARS + 1)))
20235 .is_err()
20236 );
20237 assert!(
20238 p.add_title(title(MAX_TITLE_END, 10, "past")).is_err(),
20239 "past the maximum"
20240 );
20241 let mut big = title(0, 10, "size");
20242 big.style.size = 9;
20243 assert!(p.add_title(big).is_err(), "a size under the range");
20244 let mut fade = title(0, 10, "fade");
20245 fade.fade_in = 11;
20246 assert!(p.add_title(fade).is_err(), "a fade longer than the title");
20247 assert!(p.titles().is_empty());
20248 assert_eq!(p.parts(), before.parts());
20249 assert!(
20250 !p.undo() || p.titles().is_empty(),
20251 "a refusal takes no undo step"
20252 );
20253 }
20254
20255 #[test]
20256 fn title_alpha_ramps_in_and_out() {
20257 let mut t = title(10, 10, "fades");
20258 t.fade_in = 4;
20259 t.fade_out = 4;
20260 assert_eq!(t.alpha_at(9), 0, "before the title");
20261 assert_eq!(t.alpha_at(10), 51, "the first frame is one part in five");
20262 assert_eq!(t.alpha_at(13), 204);
20263 assert_eq!(t.alpha_at(14), 255, "full between the fades");
20264 assert_eq!(t.alpha_at(16), 204, "the fade-out counts off the end");
20265 assert_eq!(t.alpha_at(19), 51);
20266 assert_eq!(t.alpha_at(20), 0, "after the title");
20267 let plain = title(0, 3, "plain");
20268 assert_eq!(
20269 (0..3).map(|f| plain.alpha_at(f)).collect::<Vec<_>>(),
20270 [255, 255, 255]
20271 );
20272 }
20273
20274 #[test]
20275 fn title_style_outline_is_kept_by_the_title() {
20276 let mut t = title(0, 5, "edged");
20277 t.style.outline = Outline::Thick;
20278 t.style.place = Place::Top;
20279 let mut p = Project::single(FILE, 150);
20280 p.add_title(t.clone()).unwrap();
20281 assert_eq!(p.titles()[0], t);
20282 }
20283}
20284
20285#[cfg(test)]
20286mod speed_ramp_tests {
20287 use super::*;
20288
20289 const FILE: &str = "/nonexistent/a.mp4";
20290
20291 fn key(at: u32, permille: u16) -> SpeedKey {
20292 SpeedKey {
20293 at,
20294 speed: Speed::from_permille(permille),
20295 }
20296 }
20297
20298 /// The 1x-to-2x ramp over 60 frames of the brief.
20299 fn ramp() -> Vec<SpeedKey> {
20300 vec![key(0, 1000), key(60, 2000)]
20301 }
20302
20303 #[test]
20304 fn the_integral_of_a_one_to_two_ramp_over_sixty_frames_covers_ninety() {
20305 let keys = ramp();
20306 assert!((ramp_source_at(&keys, 60.) - 90.).abs() < 1e-9);
20307 // The midpoint: 30 frames at ~1.25x average to 37.5 of source.
20308 assert!((ramp_source_at(&keys, 30.) - 37.5).abs() < 1e-9);
20309 // Held at 2x past the last key: 90 + 2 * 10.
20310 assert!((ramp_source_at(&keys, 70.) - 110.).abs() < 1e-9);
20311 // Held at 1x before the first key.
20312 assert!((ramp_source_at(&[key(10, 1000), key(20, 2000)], 5.) - 5.).abs() < 1e-9);
20313 }
20314
20315 #[test]
20316 fn a_ramp_of_ninety_source_frames_is_sixty_timeline_frames() {
20317 assert_eq!(ramp_frames(&ramp(), 90), 60);
20318 // Constant keys are the constant speed, to the frame.
20319 for permille in [250u16, 500, 1000, 1500, 4000] {
20320 let flat = [key(0, permille)];
20321 for len in [1u32, 7, 90, 301] {
20322 assert_eq!(ramp_frames(&flat, len), Speed::from_permille(permille).frames(len), "{permille} over {len}");
20323 }
20324 }
20325 // Never zero, even for a source frame at the fastest speed.
20326 assert_eq!(ramp_frames(&[key(0, 4000), key(1, 4000)], 1), 1);
20327 }
20328
20329 #[test]
20330 fn source_pos_is_the_integral_and_constant_speed_is_bit_identical() {
20331 let mut p = Project::single(FILE, 90);
20332 let lane = Lane::V1;
20333 let clip = p.lane(lane)[0].clone();
20334 // An unramped clip maps exactly as the constant speed always did.
20335 for t in 0..=clip.frames() {
20336 let want = clip.in_frame + clip.speed.source_at(t);
20337 assert_eq!(source_pos(&clip, t).floor() as u32, want, "frame {t}");
20338 assert_eq!(source_pos(&clip, t).fract(), 0.0);
20339 }
20340 p.set_speed_ramp(lane, 0, &ramp()).expect("the ramp sets");
20341 let clip = p.lane(lane)[0].clone();
20342 assert_eq!(clip.frames(), 60, "the ramp's footprint");
20343 assert!((source_pos(&clip, 30) - 37.5).abs() < 1e-9);
20344 assert_eq!(source_frame(&clip, 30), 37, "the midpoint shows source frame 37");
20345 assert_eq!(source_frame(&clip, 59), 88, "the last frame shows the ramp's end");
20346 }
20347
20348 #[test]
20349 fn a_ramp_span_maps_both_ways_and_reads_real_time_for_its_field() {
20350 let mut p = Project::single(FILE, 90);
20351 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20352 let span = p.span_at(Lane::V1, 0).expect("a span");
20353 assert_eq!(span.len, 60);
20354 assert_eq!(span.speed, Speed::NORMAL, "a ramped span has no constant rate");
20355 assert_eq!(span.source_offset(30), 37, "offset 30 is source frame 37");
20356 // The last timeline frame shows source 88, as a constant 2x would stop short
20357 // of the file's last frame: 89 frames are read, the same rule as a constant speed.
20358 assert_eq!(span.source_len(), 89, "the span reads up to its last frame's source");
20359 for s in 0..90 {
20360 let t = span.timeline_at(s);
20361 assert!(span.source_offset(t) >= s, "source {s} is shown by timeline {t}");
20362 assert!(t == 0 || span.source_offset(t - 1) < s, "and not before it: {s}");
20363 }
20364 // A span from the middle of the clip is based there.
20365 let mid = p.span_at(Lane::V1, 30).expect("a span");
20366 assert_eq!(mid.from, Some((0, 37)));
20367 // S(40) - S(30) in floors: 53 - 37.
20368 assert_eq!(mid.source_offset(10), 16, "ten frames on from the midpoint");
20369 }
20370
20371 #[test]
20372 fn a_ramp_is_saved_undone_and_cleared_as_one_step_each() {
20373 let mut p = Project::single(FILE, 90);
20374 let before = p.lane(Lane::V1)[0].clone();
20375 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20376 assert_eq!(p.lane(Lane::V1)[0].speed_keys, ramp());
20377 assert!(p.undo(), "one undo step");
20378 assert_eq!(p.lane(Lane::V1)[0], before, "undo restores the constant clip");
20379 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets again");
20380 p.set_speed_ramp(Lane::V1, 0, &[]).expect("clears");
20381 assert_eq!(p.lane(Lane::V1)[0].frames(), 90, "a cleared ramp is real time");
20382 }
20383
20384 #[test]
20385 fn a_ramp_refuses_a_bad_key_list_and_a_constant_speed_on_top() {
20386 let mut p = Project::single(FILE, 90);
20387 assert!(p.set_speed_ramp(Lane::V1, 0, &[key(5, 1000), key(5, 2000)]).is_err());
20388 assert!(p.set_speed_ramp(Lane::V1, 0, &[key(9, 1000), key(3, 2000)]).is_err());
20389 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20390 assert!(p.set_speed(Lane::V1, 0, Speed::from_permille(2000)).is_err(), "clear the ramp first");
20391 assert!(p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 5).is_none());
20392 // A ramp cuts where it lands on a whole source frame: at 30 the halves are 38 and 52.
20393 assert!(p.split(30), "a ramp cuts at a whole frame");
20394 let clips = p.lane(Lane::V1);
20395 assert_eq!((clips.len(), clips[0].frames(), clips[1].start, clips[1].end()), (2, 30, 30, 60));
20396 assert!(clips.iter().all(|c| !c.speed_keys.is_empty()), "both halves keep the ramp");
20397 }
20398
20399 #[test]
20400 fn a_tail_trim_of_a_ramp_refits_its_keys_and_a_head_trim_is_refused() {
20401 let mut p = Project::single(FILE, 90);
20402 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20403 let clip = p.lane(Lane::V1)[0].clone();
20404 // The largest source length whose ramp footprint is at most 30 frames.
20405 let fit = clip.fit_source(30).expect("some of it fits");
20406 assert!(ramp_frames(&ramp(), fit) <= 30 && ramp_frames(&ramp(), fit + 1) > 30, "fit {fit}");
20407 assert_eq!(clip.fit_source(0), None);
20408 assert!(!p.trim(Lane::V1, 0, Edge::Start, 10, &[90]), "a head trim of a ramp is refused");
20409 assert_eq!(p.lane(Lane::V1)[0], clip, "and changes nothing");
20410 }
20411
20412 #[test]
20413 fn ramp_keys_from_rebases_a_tail_at_the_cut() {
20414 let keys = ramp();
20415 // Cut at 30: the speed there is 1.5x, then the key at 60 is 30 frames on.
20416 let tail = ramp_keys_from(&keys, 30);
20417 assert_eq!(tail, vec![key(0, 1500), key(30, 2000)]);
20418 assert!(valid_speed_keys(&tail));
20419 }
20420
20421 /// A ramp cuts where its own integral lands on a whole source frame, and both halves
20422 /// come back to their own lengths: 1x-to-2x over 60 frames is 90 source frames, and
20423 /// the cut at frame 30 is source 37.5, which rounds to 38.
20424 #[test]
20425 fn a_ramp_splits_into_two_halves_that_add_up() {
20426 let keys = ramp();
20427 let (src, head, tail) = ramp_split(&keys, 90, 30).expect("a whole frame at 30");
20428 assert_eq!(src, 38);
20429 assert!(valid_speed_keys(&head) && valid_speed_keys(&tail));
20430 assert_eq!(ramp_frames(&head, src), 30);
20431 assert_eq!(ramp_frames(&tail, 90 - src), 30);
20432 // Nothing at the ends, and nothing past the clip.
20433 assert!(ramp_split(&keys, 90, 0).is_none());
20434 assert!(ramp_split(&keys, 90, 60).is_none());
20435 }
20436
20437 /// A freeze on a ramp takes the nearest frame every lane can cut at: the frame itself
20438 /// when it is one, else one a few frames off, and the cut there really lands.
20439 #[test]
20440 fn a_freeze_on_a_ramp_finds_a_frame_the_ramp_can_cut_at() {
20441 let mut p = Project::single(FILE, 90);
20442 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20443 assert_eq!(p.cut_frame_near(30, 12), Some(30));
20444 let near = p.cut_frame_near(31, 12).expect("a cut within reach");
20445 assert!(near.abs_diff(31) <= 12, "{near}");
20446 assert!(p.split(near), "the frame it names is one the ramp cuts at");
20447 }
20448
20449 /// The clip-level mappings every source/timeline conversion outside the engine
20450 /// goes through: a ramp's integral and its inverses, and a constant speed's own.
20451 #[test]
20452 fn clip_mappings_follow_the_ramp_and_keep_the_constant_ones() {
20453 let mut c = Clip::source_range(0, 10, 400);
20454 c.speed_keys = vec![key(0, 1000), key(60, 2000)];
20455 // 1x to 2x over 60: source frame t + t^2/120.
20456 assert_eq!(c.source_offset(60), 90);
20457 assert_eq!(c.source_offset(30), 37);
20458 assert!((c.source_offset_f(60.0) - 90.0).abs() < 1e-9);
20459 // The ceil inverse: first timeline frame at or past a source offset.
20460 assert_eq!(c.timeline_offset(30), 25);
20461 assert_eq!(c.timeline_offset_floor(60), 43);
20462 assert!((c.timeline_offset_f(90.0) - 60.0).abs() < 1e-6);
20463 for src in [1, 17, 90, 130, 300] {
20464 let t = c.timeline_offset(src);
20465 assert!(c.source_offset(t) >= src && (t == 0 || c.source_offset(t - 1) < src), "{src}");
20466 }
20467 // A constant speed keeps its own arithmetic, bit for bit.
20468 c.speed_keys.clear();
20469 c.speed = Speed::from_permille(2000);
20470 assert_eq!(c.source_offset(30), 60);
20471 assert_eq!(c.timeline_offset(60), 30);
20472 assert_eq!(c.timeline_offset_floor(61), 30);
20473 assert!((c.timeline_offset_f(60.0) - 30.0).abs() < 1e-12);
20474 }
20475}
20476
20477#[cfg(test)]
20478mod three_point_tests {
20479 use super::*;
20480
20481 const V: &str = "/nonexistent/a.mp4";
20482
20483 /// A clip of source `source`, `in_frame..out_frame`, with the fields the tests do not look at left plain.
20484 fn take(source: usize, in_frame: u32, out_frame: u32) -> Clip {
20485 Project::single(V, 1).lane(Lane::V1)[0].clone().tap(|c| {
20486 c.source = source;
20487 c.in_frame = in_frame;
20488 c.out_frame = out_frame;
20489 c.start = 0;
20490 c.link = None;
20491 })
20492 }
20493
20494 trait Tap: Sized {
20495 fn tap(self, f: impl FnOnce(&mut Self)) -> Self;
20496 }
20497 impl Tap for Clip {
20498 fn tap(mut self, f: impl FnOnce(&mut Self)) -> Self {
20499 f(&mut self);
20500 self
20501 }
20502 }
20503
20504 /// `(start, end, in_frame, source)` of every clip on `lane`.
20505 fn spans(p: &Project, lane: Lane) -> Vec<(u32, u32, u32, usize)> {
20506 p.lane(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.source)).collect()
20507 }
20508
20509 /// A 90-frame take of source 0 on V1+A1, plus a second source (`b.mp4`) to edit in.
20510 fn bed() -> Project {
20511 let mut p = Project::single(V, 90);
20512 p.sources.push(Source::new("/nonexistent/b.mp4", 0));
20513 p
20514 }
20515
20516 fn both(source: usize, a: u32, b: u32) -> Vec<(Lane, Clip)> {
20517 vec![(Lane::V1, take(source, a, b)), (Lane::A1, take(source, a, b))]
20518 }
20519
20520 #[test]
20521 fn insert_into_the_middle_of_a_clip_splits_and_ripples() {
20522 let mut p = bed();
20523 p.edit_from_source(SourceEdit::Insert, 30, &both(1, 10, 25)).unwrap();
20524 let want = vec![(0, 30, 0, 0), (30, 45, 10, 1), (45, 105, 30, 0)];
20525 assert_eq!(spans(&p, Lane::V1), want);
20526 assert_eq!(spans(&p, Lane::A1), want);
20527 assert_eq!(p.timeline_frames(), 105);
20528 // The new take is one link; the halves of the split clip are one link each, and all differ.
20529 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
20530 for i in 0..3 {
20531 assert!(v[i].link.is_some() && v[i].link == a[i].link, "clip {i} stays a take");
20532 }
20533 assert!(v[0].link != v[1].link && v[1].link != v[2].link && v[0].link != v[2].link);
20534 assert!(links_are_consistent(&p.lanes).is_ok());
20535 }
20536
20537 #[test]
20538 fn insert_at_a_cut_and_at_zero_does_not_split() {
20539 let mut p = bed();
20540 p.edit_from_source(SourceEdit::Insert, 0, &both(1, 0, 10)).unwrap();
20541 assert_eq!(spans(&p, Lane::V1), vec![(0, 10, 0, 1), (10, 100, 0, 0)]);
20542 }
20543
20544 #[test]
20545 fn overwrite_across_two_clips_trims_and_splits_nothing_moves() {
20546 let mut p = bed();
20547 assert!(p.split(30));
20548 assert!(p.split(60));
20549 p.edit_from_source(SourceEdit::Overwrite, 20, &both(1, 0, 50)).unwrap();
20550 // 0..20 kept, 20..70 the new take, 70..90 the tail of the last clip; the clip at 30..60 is gone.
20551 let want = vec![(0, 20, 0, 0), (20, 70, 0, 1), (70, 90, 70, 0)];
20552 assert_eq!(spans(&p, Lane::V1), want);
20553 assert_eq!(spans(&p, Lane::A1), want);
20554 assert_eq!(p.timeline_frames(), 90, "nothing moved");
20555 }
20556
20557 #[test]
20558 fn overwrite_inside_one_clip_splits_it_in_three() {
20559 let mut p = bed();
20560 p.edit_from_source(SourceEdit::Overwrite, 40, &both(1, 5, 15)).unwrap();
20561 assert_eq!(spans(&p, Lane::V1), vec![(0, 40, 0, 0), (40, 50, 5, 1), (50, 90, 50, 0)]);
20562 }
20563
20564 #[test]
20565 fn overwrite_past_the_end_keeps_the_gap_and_extends_the_timeline() {
20566 let mut p = bed();
20567 p.edit_from_source(SourceEdit::Overwrite, 100, &both(1, 0, 20)).unwrap();
20568 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0), (100, 120, 0, 1)]);
20569 assert_eq!(p.timeline_frames(), 120);
20570 // An overwrite that starts inside the last clip and runs past its end.
20571 let mut p = bed();
20572 p.edit_from_source(SourceEdit::Overwrite, 80, &both(1, 0, 30)).unwrap();
20573 assert_eq!(spans(&p, Lane::V1), vec![(0, 80, 0, 0), (80, 110, 0, 1)]);
20574 }
20575
20576 #[test]
20577 fn an_insert_past_the_end_just_places() {
20578 let mut p = bed();
20579 p.edit_from_source(SourceEdit::Insert, 95, &both(1, 0, 5)).unwrap();
20580 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0), (95, 100, 0, 1)]);
20581 }
20582
20583 #[test]
20584 fn linked_takes_move_whole_and_an_untargeted_half_refuses() {
20585 let mut p = bed();
20586 // Insert on V1 alone: the take's sound on A1 would be pulled apart.
20587 let before = p.lane(Lane::V1).to_vec();
20588 let history = p.history_len();
20589 let err = p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::V1, take(1, 0, 10))]).unwrap_err();
20590 assert!(err.to_string().contains("one take with the A1 clip"), "{err}");
20591 assert_eq!(p.lane(Lane::V1), &before[..], "nothing changed");
20592 assert_eq!(p.history_len(), history, "and no undo step");
20593 // Detached, the same insert is fine and leaves A1 alone.
20594 assert!(p.ungroup(Lane::V1, 0));
20595 p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::V1, take(1, 0, 10))]).unwrap();
20596 assert_eq!(spans(&p, Lane::V1), vec![(0, 30, 0, 0), (30, 40, 0, 1), (40, 100, 30, 0)]);
20597 assert_eq!(spans(&p, Lane::A1), vec![(0, 90, 0, 0)]);
20598 }
20599
20600 #[test]
20601 fn a_lane_that_is_not_targeted_is_neither_cut_nor_moved() {
20602 let mut p = bed();
20603 let v2 = Lane::new(LaneKind::Video, 1);
20604 p.lanes.push(LaneData::new(LaneKind::Video, Vec::new()));
20605 let a2 = Lane::new(LaneKind::Audio, 1);
20606 p.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
20607 p.edit_from_source(SourceEdit::Overwrite, 20, &[(v2, take(1, 0, 60)), (a2, take(1, 0, 60))]).unwrap();
20608 p.edit_from_source(SourceEdit::Insert, 30, &both(1, 0, 10)).unwrap();
20609 assert_eq!(spans(&p, v2), vec![(20, 80, 0, 1)], "the V2 clip across the insert is untouched");
20610 assert_eq!(spans(&p, a2), vec![(20, 80, 0, 1)]);
20611 assert_eq!(spans(&p, Lane::V1)[1], (30, 40, 0, 1));
20612 }
20613
20614 #[test]
20615 fn a_locked_lane_refuses() {
20616 let mut p = bed();
20617 assert!(p.set_lane_locked(Lane::A1, true));
20618 let before = spans(&p, Lane::V1);
20619 for kind in [SourceEdit::Insert, SourceEdit::Overwrite] {
20620 let err = p.edit_from_source(kind, 10, &both(1, 0, 10)).unwrap_err();
20621 assert!(err.to_string().contains("A1 is locked"), "{err}");
20622 }
20623 assert_eq!(spans(&p, Lane::V1), before);
20624 }
20625
20626 #[test]
20627 fn an_audio_only_source_goes_on_an_audio_lane_only() {
20628 let mut p = bed();
20629 p.sources.push(Source::new("/nonexistent/song.mp3", 0));
20630 let err = p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::V1, take(2, 0, 10))]).unwrap_err();
20631 assert!(err.to_string().contains("no picture"), "{err}");
20632 assert!(p.ungroup(Lane::V1, 0));
20633 p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::A1, take(2, 0, 10))]).unwrap();
20634 assert_eq!(spans(&p, Lane::A1), vec![(0, 30, 0, 0), (30, 40, 0, 2), (40, 100, 30, 0)]);
20635 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0)]);
20636 assert_eq!(p.lane(Lane::A1)[1].link, None, "a lone half belongs to no group");
20637 }
20638
20639 #[test]
20640 fn a_still_goes_on_a_video_lane_only() {
20641 let mut p = bed();
20642 p.sources.push(Source::new("/nonexistent/pic.png", 0));
20643 let err = p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::A1, take(2, 0, 10))]).unwrap_err();
20644 assert!(err.to_string().contains("still"), "{err}");
20645 assert!(p.ungroup(Lane::V1, 0));
20646 p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::V1, take(2, 0, 125))]).unwrap();
20647 assert_eq!(spans(&p, Lane::V1), vec![(0, 10, 0, 0), (10, 135, 0, 2)]);
20648 assert_eq!(spans(&p, Lane::A1), vec![(0, 90, 0, 0)]);
20649 }
20650
20651 #[test]
20652 fn each_edit_is_one_undo_step() {
20653 for kind in [SourceEdit::Insert, SourceEdit::Overwrite] {
20654 let mut p = bed();
20655 let before = (p.lane(Lane::V1).to_vec(), p.lane(Lane::A1).to_vec());
20656 let history = p.history_len();
20657 p.edit_from_source(kind, 30, &both(1, 0, 10)).unwrap();
20658 assert_eq!(p.history_len(), history + 1);
20659 assert!(p.undo());
20660 assert_eq!((p.lane(Lane::V1).to_vec(), p.lane(Lane::A1).to_vec()), before, "{kind:?}");
20661 assert!(p.redo());
20662 assert_eq!(spans(&p, Lane::V1)[1], (30, 40, 0, 1));
20663 }
20664 }
20665
20666 #[test]
20667 fn bad_edits_refuse_and_cost_no_undo_step() {
20668 let mut p = bed();
20669 let history = p.history_len();
20670 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[]).is_err());
20671 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(1, 5, 5))]).is_err());
20672 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(9, 0, 5))]).is_err());
20673 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::new(LaneKind::Video, 4), take(1, 0, 5))]).is_err());
20674 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(1, 0, 5)), (Lane::V1, take(1, 0, 5))]).is_err());
20675 assert!(p.edit_from_source(SourceEdit::Overwrite, u32::MAX, &both(1, 0, 5)).is_err());
20676 assert_eq!(p.history_len(), history);
20677 }
20678}
20679
20680/// Roll, slip and slide: the trims that move two things at once.
20681#[cfg(test)]
20682mod pro_trim_tests {
20683 use super::*;
20684
20685 const FILE: &str = "/nonexistent/a.mp4";
20686
20687 fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip {
20688 Clip {
20689 speed_keys: Vec::new(),
20690 opacity_keys: Vec::new(),
20691 color_keys: Vec::new(),
20692 effects: Vec::new(),
20693 transition_kind: Default::default(),
20694 reversed: false,
20695 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
20696 angle: Default::default(),
20697 fade_in: 0,
20698 fade_out: 0,
20699 transition_out: 0,
20700 visualizer: 0,
20701 viz_paint: 0,
20702 gain_db: 0.0,
20703 gain_keys: Vec::new(),
20704 pan: 0,
20705 pitch: 0,
20706 transform_keys: Vec::new(),
20707 start,
20708 in_frame,
20709 out_frame,
20710 source: 0,
20711 link: None,
20712 eq: None,
20713 color: None,
20714 transform: None,
20715 fit: FitPolicy::default(),
20716 speed: Speed::NORMAL,
20717 }
20718 }
20719
20720 fn fast(start: u32, in_frame: u32, out_frame: u32, permille: u16) -> Clip {
20721 Clip { speed: Speed::from_permille(permille), ..clip(start, in_frame, out_frame) }
20722 }
20723
20724 /// 30 frames of V1+A1 (a linked take) cut into 0..10, 10..20, 20..30.
20725 fn three() -> Project {
20726 let mut p = Project::single(FILE, 30);
20727 assert!(p.split(10));
20728 assert!(p.split(20));
20729 p
20730 }
20731
20732 fn w(t: &[u32]) -> SourceWalls<'_> {
20733 SourceWalls::same(t)
20734 }
20735
20736 /// `(start, end, in, out)` of every clip on the lane.
20737 fn spans(p: &Project, lane: Lane) -> Vec<(u32, u32, u32, u32)> {
20738 p.lane(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.out_frame)).collect()
20739 }
20740
20741 /// A lane with `v2` holding the given clips; no linked partners.
20742 fn lone(clips: &[Clip]) -> (Project, Lane) {
20743 let mut p = Project::single(FILE, 1);
20744 let v = p.add_lane(LaneKind::Video);
20745 for c in clips {
20746 assert!(p.place(v, c.start, c.clone()));
20747 }
20748 (p, v)
20749 }
20750
20751 #[test]
20752 fn roll_moves_the_cut_of_a_take_and_keeps_the_length() {
20753 let mut p = three();
20754 let steps = p.history.len();
20755 assert_eq!(p.roll(Lane::V1, 0, 14, w(&[30])), Some(14));
20756 for lane in [Lane::V1, Lane::A1] {
20757 assert_eq!(
20758 spans(&p, lane),
20759 [(0, 14, 0, 14), (14, 20, 14, 20), (20, 30, 20, 30)],
20760 "{lane:?}: both halves of the take rolled, the far cut stayed"
20761 );
20762 }
20763 assert_eq!(p.history.len(), steps + 1, "one undo step");
20764 assert!(p.undo());
20765 assert_eq!(spans(&p, Lane::V1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20766 assert_eq!(spans(&p, Lane::A1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20767 // Rolled back toward the start, from the other side of the take.
20768 assert_eq!(p.roll(Lane::A1, 1, 25, w(&[30])), Some(25));
20769 assert_eq!(spans(&p, Lane::V1)[1..], [(10, 25, 10, 25), (25, 30, 25, 30)]);
20770 }
20771
20772 #[test]
20773 fn roll_is_clamped_to_a_frame_each_side_and_changes_nothing_in_place() {
20774 let mut p = three();
20775 assert_eq!(p.roll_room(Lane::V1, 0, w(&[30])), Some((1, 19)));
20776 assert_eq!(p.roll(Lane::V1, 0, 500, w(&[30])), Some(19));
20777 assert_eq!(spans(&p, Lane::V1)[..2], [(0, 19, 0, 19), (19, 20, 19, 20)]);
20778 assert_eq!(p.roll(Lane::V1, 0, 0, w(&[30])), Some(1));
20779 let steps = p.history.len();
20780 assert_eq!(p.roll(Lane::V1, 0, 1, w(&[30])), Some(1), "already there");
20781 assert_eq!(p.history.len(), steps, "and a roll that moves nothing costs no step");
20782 }
20783
20784 #[test]
20785 fn roll_stops_at_the_source_media() {
20786 // A plays 5..15 of a source that is 18 frames long; B plays 25..30.
20787 let (mut p, v) = lone(&[clip(0, 5, 15), clip(10, 25, 30)]);
20788 assert_eq!(p.roll_room(v, 0, w(&[18])), Some((1, 13)));
20789 assert_eq!(p.roll(v, 0, 100, w(&[18])), Some(13));
20790 assert_eq!(p.lane(v)[0].out_frame, 18, "the out-point is the source's last frame");
20791 assert_eq!(spans(&p, v)[1], (13, 15, 28, 30), "the next in-point moved by the same frames");
20792 // The other way: B can back up only to its own first frame.
20793 let (mut p, v) = lone(&[clip(0, 5, 15), clip(10, 3, 8)]);
20794 assert_eq!(p.roll(v, 0, 0, w(&[30])), Some(7), "3 frames of head: the cut stops 3 frames back");
20795 assert_eq!(p.lane(v)[1].in_frame, 0);
20796 }
20797
20798 #[test]
20799 fn roll_needs_a_cut() {
20800 let mut p = three();
20801 assert_eq!(p.roll(Lane::V1, 2, 25, w(&[30])), None, "the last clip has no neighbour");
20802 assert_eq!(p.roll(Lane::V1, 9, 25, w(&[30])), None, "no such clip");
20803 let (mut p, v) = lone(&[clip(0, 0, 10), clip(12, 0, 10)]);
20804 let steps = p.history.len();
20805 assert_eq!(p.roll(v, 0, 5, w(&[30])), None, "a gap is not a cut");
20806 assert_eq!(p.history.len(), steps);
20807 }
20808
20809 #[test]
20810 fn roll_at_speed_moves_source_by_the_rate() {
20811 // Two clips at 2x: 10 timeline frames each, twenty source frames each.
20812 let (mut p, v) = lone(&[fast(0, 0, 20, 2000), fast(10, 30, 50, 2000)]);
20813 assert_eq!(p.roll(v, 0, 14, w(&[100])), Some(14));
20814 assert_eq!(spans(&p, v), [(0, 14, 0, 28), (14, 20, 38, 50)], "4 timeline frames are 8 source frames");
20815 assert!(p.undo());
20816 assert_eq!(spans(&p, v), [(0, 10, 0, 20), (10, 20, 30, 50)]);
20817 }
20818
20819 #[test]
20820 fn roll_at_a_slow_rate_never_opens_a_gap_or_changes_the_length() {
20821 // 0.4x: a source range of n frames is round(2.5 n) timeline frames, so most
20822 // timeline lengths are unreachable.
20823 for to in 1..20 {
20824 let (mut p, v) = lone(&[fast(0, 0, 4, 400), fast(10, 10, 14, 400)]);
20825 let end = p.lane(v)[1].end();
20826 let landed = p.roll(v, 0, to, w(&[100])).expect("a cut");
20827 let [a, b] = [&p.lane(v)[0], &p.lane(v)[1]];
20828 assert_eq!((a.end(), b.start, b.end()), (landed, landed, end), "roll to {to}");
20829 assert!(sorted_disjoint(p.lane(v)));
20830 }
20831 }
20832
20833 #[test]
20834 fn roll_pins_at_a_ramped_clip_behind_the_cut() {
20835 let (mut p, v) = lone(&[clip(0, 0, 10), clip(10, 0, 10)]);
20836 p.set_speed_ramp(v, 1, &[SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 8, speed: Speed::from_permille(2000) }])
20837 .expect("ramp");
20838 assert_eq!(p.roll(v, 0, 5, w(&[100])), Some(10), "a ramped in-point cannot move");
20839 // The ramp may be the one before the cut: its tail is the only edge that moves.
20840 let (mut p, v) = lone(&[clip(0, 0, 20)]);
20841 p.set_speed_ramp(v, 0, &[SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 15, speed: Speed::from_permille(2000) }])
20842 .expect("ramp");
20843 let at = p.lane(v)[0].end();
20844 assert!(p.place(v, at, clip(at, 5, 15)));
20845 let end = p.lane(v)[1].end();
20846 let cut = p.lane(v)[0].end();
20847 let landed = p.roll(v, 0, cut - 3, w(&[100])).expect("a cut");
20848 assert!(landed < cut);
20849 assert_eq!((p.lane(v)[0].end(), p.lane(v)[1].start, p.lane(v)[1].end()), (landed, landed, end));
20850 }
20851
20852 #[test]
20853 fn slip_shifts_the_window_and_nothing_else() {
20854 let mut p = three();
20855 let steps = p.history.len();
20856 assert_eq!(p.slip(Lane::V1, 1, 5, w(&[30])), Some(5));
20857 for lane in [Lane::V1, Lane::A1] {
20858 assert_eq!(
20859 spans(&p, lane)[1],
20860 (10, 20, 15, 25),
20861 "{lane:?}: same slot, later footage"
20862 );
20863 assert_eq!(spans(&p, lane)[0], (0, 10, 0, 10), "the neighbours are untouched");
20864 }
20865 assert_eq!(p.history.len(), steps + 1);
20866 assert!(p.undo());
20867 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 10, 20));
20868 assert_eq!(spans(&p, Lane::A1)[1], (10, 20, 10, 20));
20869 }
20870
20871 #[test]
20872 fn slip_is_clamped_to_the_source_and_each_member_to_its_own() {
20873 let mut p = three();
20874 assert_eq!(p.slip_room(Lane::V1, 1, w(&[30])), Some((-10, 10)));
20875 assert_eq!(p.slip(Lane::V1, 1, -99, w(&[30])), Some(-10));
20876 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 0, 10));
20877 assert_eq!(p.slip(Lane::V1, 1, 99, w(&[30])), Some(20));
20878 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 20, 30));
20879 // The sound is 5 frames shorter than the picture: it stops where it stops.
20880 let mut p = three();
20881 let walls = SourceWalls { picture: &[30], sound: &[25] };
20882 assert_eq!(p.slip(Lane::V1, 1, 8, walls), Some(8));
20883 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 18, 28));
20884 assert_eq!(spans(&p, Lane::A1)[1], (10, 20, 15, 25), "the sound ran out of file first");
20885 // Pinned: no change, no step.
20886 let steps = p.history.len();
20887 assert_eq!(p.slip(Lane::V1, 1, 1, w(&[28])), Some(0));
20888 assert_eq!(p.history.len(), steps);
20889 }
20890
20891 #[test]
20892 fn slip_at_speed_keeps_the_slot_and_converts_timeline_frames() {
20893 let (mut p, v) = lone(&[fast(0, 10, 20, 2000)]);
20894 assert_eq!(p.lane(v)[0].end(), 5);
20895 assert_eq!(p.slip_source_delta(v, 0, 3), Some(6), "3 timeline frames at 2x");
20896 assert_eq!(p.slip_source_delta(v, 0, -3), Some(-6));
20897 assert_eq!(p.slip(v, 0, 6, w(&[60])), Some(6));
20898 assert_eq!(spans(&p, v), [(0, 5, 16, 26)]);
20899 assert_eq!(p.slip(v, 0, 1000, w(&[60])), Some(34), "clamped to the 60 frames the source has");
20900 assert_eq!(spans(&p, v), [(0, 5, 50, 60)]);
20901 // Half speed: a timeline frame is half a source frame.
20902 let (p, v) = lone(&[fast(0, 10, 20, 500)]);
20903 assert_eq!(p.slip_source_delta(v, 0, 8), Some(4));
20904 }
20905
20906 #[test]
20907 fn slip_keeps_a_ramped_clip_in_its_slot() {
20908 let (mut p, v) = lone(&[clip(0, 10, 30)]);
20909 let keys = [SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 10, speed: Speed::from_permille(2000) }];
20910 p.set_speed_ramp(v, 0, &keys).expect("ramp");
20911 let before = (p.lane(v)[0].start, p.lane(v)[0].end());
20912 assert_eq!(p.slip(v, 0, 7, w(&[100])), Some(7));
20913 let c = &p.lane(v)[0];
20914 assert_eq!((c.start, c.end(), c.in_frame, c.out_frame), (before.0, before.1, 17, 37));
20915 assert_eq!(c.speed_keys.len(), 2, "the ramp stays on the clip");
20916 }
20917
20918 #[test]
20919 fn slip_has_nothing_to_do_to_a_still_or_a_missing_clip() {
20920 let mut p = Project::single("/nonexistent/pic.png", 100);
20921 let steps = p.history.len();
20922 assert_eq!(p.slip(Lane::V1, 0, 5, w(&[100])), None);
20923 assert_eq!(p.slip(Lane::V1, 3, 5, w(&[100])), None);
20924 assert_eq!(p.history.len(), steps);
20925 }
20926
20927 #[test]
20928 fn slide_moves_the_clip_and_its_neighbours_absorb_it() {
20929 let mut p = three();
20930 let steps = p.history.len();
20931 assert_eq!(p.slide(Lane::V1, 1, 13, w(&[30])), Some(13));
20932 for lane in [Lane::V1, Lane::A1] {
20933 assert_eq!(
20934 spans(&p, lane),
20935 [(0, 13, 0, 13), (13, 23, 10, 20), (23, 30, 23, 30)],
20936 "{lane:?}: same content, same length, neighbours absorb"
20937 );
20938 }
20939 assert_eq!(p.history.len(), steps + 1, "one undo step");
20940 assert!(p.undo());
20941 assert_eq!(spans(&p, Lane::V1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20942 assert_eq!(spans(&p, Lane::A1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20943 assert_eq!(p.slide(Lane::A1, 1, 6, w(&[30])), Some(6), "either half drags the take");
20944 assert_eq!(spans(&p, Lane::V1), [(0, 6, 0, 6), (6, 16, 10, 20), (16, 30, 16, 30)]);
20945 }
20946
20947 #[test]
20948 fn slide_is_clamped_to_a_frame_of_each_neighbour_and_their_media() {
20949 let mut p = three();
20950 assert_eq!(p.slide_room(Lane::V1, 1, w(&[30])), Some((1, 19)));
20951 assert_eq!(p.slide(Lane::V1, 1, 100, w(&[30])), Some(19));
20952 assert_eq!(spans(&p, Lane::V1), [(0, 19, 0, 19), (19, 29, 10, 20), (29, 30, 29, 30)]);
20953 assert_eq!(p.slide(Lane::V1, 1, 0, w(&[30])), Some(1));
20954 // The clip before it only has source up to frame 12; it cannot give more.
20955 let (mut p, v) = lone(&[clip(0, 0, 10), clip(10, 40, 50), clip(20, 60, 70)]);
20956 assert_eq!(p.slide(v, 1, 99, w(&[12])), Some(12));
20957 assert_eq!(p.lane(v)[0].out_frame, 12, "it gave every frame it had");
20958 }
20959
20960 #[test]
20961 fn slide_needs_a_neighbour_on_each_side() {
20962 let mut p = three();
20963 let steps = p.history.len();
20964 assert_eq!(p.slide(Lane::V1, 0, 3, w(&[30])), None, "first clip");
20965 assert_eq!(p.slide(Lane::V1, 2, 3, w(&[30])), None, "last clip");
20966 assert_eq!(p.slide(Lane::V1, 8, 3, w(&[30])), None, "no clip");
20967 assert_eq!(p.history.len(), steps);
20968 let (mut p, v) = lone(&[clip(0, 0, 10)]);
20969 assert_eq!(p.slide(v, 0, 3, w(&[30])), None, "alone on its lane");
20970 }
20971
20972 #[test]
20973 fn slide_beside_a_gap_edits_only_the_cut_side() {
20974 // 0..10 | gap 10..15 | 15..25 | 25..35
20975 let (mut p, v) = lone(&[clip(0, 0, 10), clip(15, 20, 30), clip(25, 40, 50)]);
20976 assert_eq!(p.slide_room(v, 1, w(&[100])), Some((10, 24)));
20977 assert_eq!(p.slide(v, 1, 0, w(&[100])), Some(10), "into the gap, but not over the clip before it");
20978 assert_eq!(spans(&p, v), [(0, 10, 0, 10), (10, 20, 20, 30), (20, 35, 35, 50)]);
20979 }
20980
20981 #[test]
20982 fn slide_at_speed_moves_neighbour_source_by_their_rate() {
20983 // The clip before it plays at 2x: a frame of timeline is two of source.
20984 let (mut p, v) = lone(&[fast(0, 0, 20, 2000), clip(10, 40, 50), clip(20, 60, 70)]);
20985 assert_eq!(p.slide(v, 1, 13, w(&[100])), Some(13));
20986 assert_eq!(spans(&p, v), [(0, 13, 0, 26), (13, 23, 40, 50), (23, 30, 63, 70)]);
20987 assert!(p.undo());
20988 assert_eq!(spans(&p, v), [(0, 10, 0, 20), (10, 20, 40, 50), (20, 30, 60, 70)]);
20989 }
20990
20991 #[test]
20992 fn slide_keeps_the_length_whatever_the_rate() {
20993 for to in 1..40 {
20994 let (mut p, v) = lone(&[fast(0, 0, 4, 400), clip(10, 40, 50), fast(20, 10, 14, 400)]);
20995 let end = p.lane(v)[2].end();
20996 let landed = p.slide(v, 1, to, w(&[100])).expect("neighbours");
20997 let l = p.lane(v);
20998 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}");
20999 }
21000 }
21001}