forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc327308Tahinli25 days ago1014 commits

project.rs20800 lines, 910.2 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::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 sample,
107};
108
109/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
110/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
111/// for every purpose but the honest one, which is that it is still a level and
112/// not a mute.
113pub const MIN_GAIN_DB: f32 = -60.0;
114/// ...and how far up. +12 dB is four times the amplitude, which is as much as
115/// a mix bus can take before the limiter is doing all the work.
116pub const MAX_GAIN_DB: f32 = 12.0;
117
118/// The longest `[in_us, out_us)` window a [`SubClip`] may show, in
119/// microseconds: **30 days** of track.
120///
121/// A window is a stretch of *source media*, not of the timeline, so its width
122/// is the length of the recording a caption was cut from -- and that is not
123/// bounded by anything a day. A two-day conference stream, a lecture archive, a
124/// long interview session: all produce a palette row whose `out_us` is tens of
125/// hours, and a ceiling that refuses those refuses the user's own media back at
126/// them. The value is therefore "past any recording", and nothing more
127/// sophisticated: 30 days is a round number four orders of magnitude above the
128/// longest thing anybody captions and three orders below the point where a
129/// typed number becomes plausible as a duration at all.
130///
131/// What it has to clear, concretely, and the honest arithmetic for each:
132///
133/// - **The i64 multiply in [`SubClip::window_at`].** `window_us() * into`,
134/// where `into` is a `u32` frame offset, so at most 4.29e9. It is a
135/// `saturating_mul`, so this is not about safety -- saturation is total --
136/// but about the result still *meaning* something: 30 days x 4.29e9 is
137/// 1.1e22, which does NOT fit an i64. So the multiply saturates for any
138/// window above `i64::MAX / u32::MAX` = 2.1e9 us (~35 minutes), and 30 days
139/// is 1200x past that. The value is then finite but the proportion is not
140/// exact, and `set_window`'s clamp on the answer keeps the result inside the
141/// window rather than trusting it. That is the real precision cost, and it
142/// is why this is not "unlimited": past 35 minutes the cut degrades, past
143/// this it has degraded to "the far end of the window".
144/// - **`sub_lane_cues`'s f64 mapping.** `(t - in_us) as f64 * per`, where `per`
145/// is `frames / fps * 1e6 / window_us`. Here f64 exactness genuinely does
146/// apply: an i64 is exact in f64 to 2^53 = 9.0e15, and 30 days is 2.6e12 --
147/// about 3.5 orders of magnitude inside it, so the cue mapping is exact and
148/// not merely close.
149/// - **Nothing else.** There is no allocation, no index and no length derived
150/// from a window, so a wider value costs no memory. The ceiling is a claim
151/// about meaning, not about resource.
152///
153/// Past it, the value is not a caption any project holds -- a `.edith` a hand
154/// edited (or a hostile actor wrote) reaches this with a line the never-empty
155/// check at the parser cannot see past, because `out_us > in_us` says the
156/// window is *open* and never how wide it is. Every door -- the parse,
157/// [`Project::with_subs`], [`Project::place_sub`] -- refuses such a line by
158/// name, next to every other range check a `.edith` line has to pass. Every
159/// *composer* instead clamps to it through [`set_window`], which is the only
160/// function that writes a window; a trim that ran out of window stops at the
161/// window's end rather than failing, exactly like the frame walls it already
162/// has.
163pub const MAX_WINDOW_US: i64 = 30 * 24 * 60 * 60 * 1_000_000;
164
165/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
166/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
167/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
168/// comparable nor exactly writable, and `.edith` has to read back the very
169/// number that was set. A thousandth is finer than any card can drag and coarser
170/// than any rounding anyone can hear.
171///
172/// The rate alone: the audio path time-stretches a speeded clip
173/// (`crate::stretch`), so its pitch stays where it was recorded while its
174/// seconds compress or stretch -- the tape effect this used to be is gone.
175/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
176/// [`Speed::MAX`] four times.
177#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
178pub struct Speed(u16);
179
180/// What [`Project::parts`] hands back: the comparable shape of everything an
181/// edit can change, for the sweep's undo round-trip. Test-only, like every
182/// accessor it exists for: the sweep lives behind `cfg(test)`.
183#[cfg(test)]
184#[derive(Clone, Debug, PartialEq)]
185pub(crate) struct SweepParts(
186 pub(crate) usize,
187 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
188 pub(crate) Vec<Vec<SubClip>>,
189 /// The palette, which the history holds beside the lanes and an undo
190 /// therefore restores ([`Project::undo`]). Left out of this shape, a
191 /// round-trip check passed with the palette restore deleted outright.
192 pub(crate) Vec<SubtitleTrack>,
193 pub(crate) ProjectSettings,
194);
195
196impl Speed {
197 /// Real time -- what every clip is until something says otherwise, and the
198 /// value every path in this engine short-circuits on.
199 pub const NORMAL: Speed = Speed(1000);
200 pub const MIN: Speed = Speed(250);
201 pub const MAX: Speed = Speed(4000);
202
203 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
204 /// unrepresentable rather than merely refused: nothing downstream divides
205 /// by a speed that could be nothing.
206 pub fn from_permille(permille: u16) -> Self {
207 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
208 }
209
210 pub fn permille(self) -> u16 {
211 self.0
212 }
213
214 pub fn is_normal(self) -> bool {
215 self == Self::NORMAL
216 }
217
218 /// As a multiplier, for the sound worker and for a label.
219 pub fn as_f64(self) -> f64 {
220 f64::from(self.0) / 1000.
221 }
222
223 /// How many *timeline* frames `source` source frames occupy at this rate --
224 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
225 /// clip that occupied no frames would be an empty placement, which the lane
226 /// invariant forbids and which nothing could ever click on again.
227 pub fn frames(self, source: u32) -> u32 {
228 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
229 n.clamp(1, u64::from(u32::MAX)) as u32
230 }
231
232 /// The mapping itself: which source frame of a clip the `offset`th timeline
233 /// frame of it plays. Floored, so the first timeline frame is the clip's own
234 /// in-point at every rate.
235 pub fn source_at(self, offset: u32) -> u32 {
236 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
237 }
238
239 /// Its inverse, for a decoder's frames on their way back out: which timeline
240 /// frame of the clip the `offset`th *source* frame of it lands on.
241 ///
242 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
243 /// decoded frame with this and shows the newest whose stamp has come due, so
244 /// what is on screen at timeline offset `d` is the last source frame with
245 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
246 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
247 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
248 /// the two the same way would put the preview a frame off the export at some
249 /// speeds and a whole held frame off at slow ones -- drift that no test of
250 /// either side alone would catch.
251 pub fn timeline_at(self, offset: u32) -> u32 {
252 (u64::from(offset) * 1000)
253 .div_ceil(u64::from(self.0))
254 .min(u64::from(u32::MAX)) as u32
255 }
256
257 /// The longest source range that still *fits* in `frames` timeline frames at
258 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
259 /// any room narrower than the four timeline frames one source frame occupies.
260 ///
261 /// What a trim commits and what a hole-punch leaves behind: rounding could
262 /// otherwise hand back a range wider than the room, and a clip that outgrew
263 /// its room would overlap its neighbour -- the one thing a lane may never do.
264 /// `None` is not an error, it is "no remainder": the caller drops that piece
265 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
266 /// is `frames` itself, so nothing about an unspeeded edit changes.
267 pub fn fit(self, frames: u32) -> Option<u32> {
268 if frames == 0 || self.frames(1) > frames {
269 return None;
270 }
271 // The floored estimate is a step or two off in either direction: `frames`
272 // rounds, so at a slow rate the estimate can sit one short of the longest
273 // range that fits (0.333x: 48 source frames take 144 timeline frames, and
274 // `source_at(144)` is 47), and at a fast one one over. Both walked, so the
275 // answer is the longest range that fits, exactly -- which is what a wall
276 // ([`Project::trim_room`]) promises an edge can reach.
277 let mut src = self.source_at(frames).max(1);
278 while self.frames(src + 1) <= frames {
279 src += 1;
280 }
281 while src > 1 && self.frames(src) > frames {
282 src -= 1;
283 }
284 Some(src)
285 }
286
287 /// How many timeline frames `source` source frames of head (or tail) are
288 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
289 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
290 /// empty, but the room in front of one may well be.
291 pub fn room(self, source: u32) -> u32 {
292 match source {
293 0 => 0,
294 n => self.frames(n),
295 }
296 }
297
298 /// How many timeline frames from `offset` on show the **same** source frame:
299 /// one at real time and faster, more when the clip is slowed. What an export
300 /// encodes without decoding the same picture twice, and the count that makes
301 /// its frame walk exactly as long as the span.
302 pub fn repeats(self, offset: u32, len: u32) -> u32 {
303 let want = self.source_at(offset);
304 (offset..len)
305 .take_while(|&t| self.source_at(t) == want)
306 .count() as u32
307 }
308
309 /// Where in the source a cut `offset` timeline frames into a clip of `len`
310 /// source frames falls -- and `None` when this rate cannot address that
311 /// frame at all.
312 ///
313 /// At half speed a clip of ten source frames is twenty timeline frames long
314 /// and every source frame is on screen twice, so a cut between the two
315 /// showings of one frame is not a cut in the *file*: taking it would leave
316 /// two halves whose lengths no longer add up to the clip that was cut --
317 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
318 /// the model stays exact and the front-end can say why. At real time every
319 /// interior frame answers, which is the path a project without speeds is on.
320 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
321 let src = self.source_at(offset);
322 (src > 0
323 && src < len
324 && self.frames(src) == offset
325 && self.frames(len - src) == self.frames(len) - offset)
326 .then_some(src)
327 }
328}
329
330/// Most keys a speed ramp may hold ([`Clip::speed_keys`]). A fixed cap, so that a
331/// [`Span`] carrying a ramp stays `Copy`.
332pub const MAX_SPEED_KEYS: usize = 8;
333
334/// How long a still image is placed for when the project does not say (the 5 s every project had
335/// before v52), and the shortest and longest length a project may set for one.
336pub const STILL_DEFAULT_SECS: f64 = 5.0;
337pub const STILL_MIN_SECS: f64 = 0.5;
338pub const STILL_MAX_SECS: f64 = 600.0;
339
340/// One point of a clip's speed ramp ([`Clip::speed_keys`]): the speed `speed` at
341/// the clip-relative timeline frame `at`. Between points the speed is linear and
342/// it holds before the first and after the last. Speeds are [`Speed`]s, in
343/// thousandths like the constant one, so a ramp reads back exactly as it was set.
344#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
345pub struct SpeedKey {
346 pub at: u32,
347 pub speed: Speed,
348}
349
350/// The 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, 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/// The cut key takes the easing of the segment it sits in. Empty in, empty out.
1232pub fn split_transform_keys<K: Keyed>(keys: &[K], cut: u32) -> (Vec<K>, Vec<K>) {
1233 let Some(at) = sample(keys, f64::from(cut)) else {
1234 return (Vec::new(), Vec::new());
1235 };
1236 let ease = keys
1237 .iter()
1238 .rev()
1239 .find(|k| k.at() <= cut)
1240 .map_or(KeyEase::Linear, |k| k.ease());
1241 let boundary = at.placed(cut, ease);
1242 let mut left: Vec<K> = keys.iter().copied().filter(|k| k.at() < cut).collect();
1243 left.push(boundary);
1244 let mut right = vec![boundary];
1245 right.extend(keys.iter().copied().filter(|k| k.at() > cut));
1246 (left, right)
1247}
1248
1249/// The gain envelope's dB at source frame `src` over `keys`
1250/// ([`Clip::gain_keys`]): linear between points, held outside them, `0.0`
1251/// when there are none. Exact at a point, and the midpoint of two points is
1252/// the midpoint of their dB.
1253pub fn gain_keys_db_at(keys: &[GainKey], src: f64) -> f32 {
1254 lerp_db(keys, |k| (f64::from(k.at), k.db, k.ease), src)
1255}
1256
1257impl Clip {
1258 /// A plain clip of `source` reading `in_frame..out_frame`, at start 0, normal
1259 /// speed and no look: the shape a front-end hands
1260 /// [`Project::edit_from_source`] for one half of a take.
1261 pub fn source_range(source: usize, in_frame: u32, out_frame: u32) -> Clip {
1262 Clip {
1263 speed_keys: Vec::new(),
1264 reversed: false,
1265 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1266 angle: Default::default(),
1267 start: 0,
1268 in_frame,
1269 out_frame,
1270 source,
1271 link: None,
1272 eq: None,
1273 color: None,
1274 transform: None,
1275 transform_keys: Vec::new(),
1276 opacity_keys: Vec::new(),
1277 color_keys: Vec::new(),
1278 effects: Vec::new(),
1279 fit: FitPolicy::default(),
1280 speed: Speed::NORMAL,
1281 fade_in: 0,
1282 fade_out: 0,
1283 transition_out: 0,
1284 transition_kind: Default::default(),
1285 visualizer: 0,
1286 viz_paint: 0,
1287 gain_db: 0.0,
1288 gain_keys: Vec::new(),
1289 pan: 0,
1290 pitch: 0,
1291 }
1292 }
1293
1294 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
1295 /// reads out of its file -- not how long it is on the timeline, which is
1296 /// [`Clip::frames`] and differs the moment it is speeded.
1297 pub fn len(&self) -> u32 {
1298 self.out_frame - self.in_frame
1299 }
1300
1301 /// Always false: a clip reads at least one source frame.
1302 pub fn is_empty(&self) -> bool {
1303 self.len() == 0
1304 }
1305
1306 /// Timeline frames it occupies: its source range at its own speed, never
1307 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
1308 /// what it overlaps, how wide its box is -- is asked of this and not of
1309 /// [`Clip::len`].
1310 pub fn frames(&self) -> u32 {
1311 if self.speed_keys.is_empty() {
1312 self.speed.frames(self.len())
1313 } else {
1314 ramp_frames(&self.speed_keys, self.len())
1315 }
1316 }
1317
1318 /// One past the last timeline frame it covers.
1319 pub fn end(&self) -> u32 {
1320 self.start + self.frames()
1321 }
1322
1323 /// Whether a cut at `frame` lands cleanly on this clip: outside it, or inside at a frame
1324 /// its rate (or ramp) can address. What the razor asks before it offers to cut.
1325 pub fn splits_at(&self, frame: u32) -> bool {
1326 (self.start < frame && frame < self.end()) && split_source(self, frame).is_some()
1327 }
1328
1329 /// Source frames from the clip's in point to the one its `clip_frame`th timeline
1330 /// frame plays: [`Speed::source_at`], or for a ramped clip the ramp's integral
1331 /// floored ([`source_pos`]). What every "which source frame is on screen" asks,
1332 /// at a constant speed or not.
1333 pub fn source_offset(&self, clip_frame: u32) -> u32 {
1334 if self.speed_keys.is_empty() {
1335 self.speed.source_at(clip_frame)
1336 } else {
1337 ramp_source_at(&self.speed_keys, f64::from(clip_frame)).floor() as u32
1338 }
1339 }
1340
1341 /// The inverse of [`source_offset`](Clip::source_offset), ceiled: the first
1342 /// clip-relative timeline frame whose source frame is `source_offset` or past it
1343 /// -- [`Speed::timeline_at`], or the ramp's. Where a source instant that starts
1344 /// something (a word, a speech region) lands.
1345 pub fn timeline_offset(&self, source_offset: u32) -> u32 {
1346 if self.speed_keys.is_empty() {
1347 self.speed.timeline_at(source_offset)
1348 } else {
1349 SpeedRamp::new(&self.speed_keys, 0).timeline_at(source_offset)
1350 }
1351 }
1352
1353 /// [`timeline_offset`](Clip::timeline_offset) floored instead: the rounding an
1354 /// *end* needs, so a region never eats the frame the next thing starts on.
1355 pub fn timeline_offset_floor(&self, source_offset: u32) -> u32 {
1356 if self.speed_keys.is_empty() {
1357 (u64::from(source_offset) * 1000 / u64::from(self.speed.permille())).min(u64::from(u32::MAX))
1358 as u32
1359 } else {
1360 ramp_timeline_at(&self.speed_keys, f64::from(source_offset)).floor() as u32
1361 }
1362 }
1363
1364 /// [`source_offset`](Clip::source_offset) without the floor, for a fractional
1365 /// clip-relative timeline frame: source frames from the in point, continuous.
1366 pub fn source_offset_f(&self, clip_frame: f64) -> f64 {
1367 if self.speed_keys.is_empty() {
1368 clip_frame.max(0.0) * self.speed.as_f64()
1369 } else {
1370 ramp_source_at(&self.speed_keys, clip_frame)
1371 }
1372 }
1373
1374 /// The inverse of [`source_offset_f`](Clip::source_offset_f): the clip-relative
1375 /// timeline frame (fractional) at which the clip has played `source_frames` source
1376 /// frames of itself.
1377 pub fn timeline_offset_f(&self, source_frames: f64) -> f64 {
1378 if self.speed_keys.is_empty() {
1379 source_frames / self.speed.as_f64()
1380 } else {
1381 ramp_timeline_at(&self.speed_keys, source_frames)
1382 }
1383 }
1384
1385 /// The longest source range that fits in `frames` timeline frames at this clip's
1386 /// speed -- [`Speed::fit`], or for a ramped clip the largest length whose ramp
1387 /// footprint ([`ramp_frames`]) fits. `None` when nothing does.
1388 pub fn fit_source(&self, frames: u32) -> Option<u32> {
1389 if self.speed_keys.is_empty() {
1390 return self.speed.fit(frames);
1391 }
1392 if frames == 0 || ramp_frames(&self.speed_keys, 1) > frames {
1393 return None;
1394 }
1395 // The footprint is monotone in the source length, so bisect for the largest
1396 // that still fits. Doubling first bounds the search.
1397 let (mut lo, mut hi) = (1u32, 2u32);
1398 while ramp_frames(&self.speed_keys, hi) <= frames && hi < u32::MAX / 2 {
1399 lo = hi;
1400 hi *= 2;
1401 }
1402 while lo < hi {
1403 let mid = lo + (hi - lo).div_ceil(2);
1404 if ramp_frames(&self.speed_keys, mid) <= frames {
1405 lo = mid;
1406 } else {
1407 hi = mid - 1;
1408 }
1409 }
1410 Some(lo)
1411 }
1412}
1413
1414/// The speed a ramp runs at clip-relative frame `t`, linear between keys and held at
1415/// the ends, rounded to a [`Speed`] (thousandths).
1416pub fn ramp_speed_at(keys: &[SpeedKey], t: u32) -> Speed {
1417 let Some(first) = keys.first() else {
1418 return Speed::NORMAL;
1419 };
1420 if t <= first.at {
1421 return first.speed;
1422 }
1423 for w in keys.windows(2) {
1424 let (a, b) = (w[0], w[1]);
1425 if t <= b.at {
1426 let f = f64::from(t - a.at) / f64::from(b.at - a.at);
1427 let (ra, rb) = (a.speed.as_f64(), b.speed.as_f64());
1428 return Speed::from_permille(((ra + (rb - ra) * f) * 1000.).round() as u16);
1429 }
1430 }
1431 keys[keys.len() - 1].speed
1432}
1433
1434/// The keys of the part of a ramped clip from clip-relative frame `cut` on, rebased so
1435/// that `cut` is frame 0: the speed there first, then the keys after it, shifted.
1436/// What a clip's tail keeps when its head is cut away.
1437pub fn ramp_keys_from(keys: &[SpeedKey], cut: u32) -> Vec<SpeedKey> {
1438 let mut out = vec![SpeedKey {
1439 at: 0,
1440 speed: ramp_speed_at(keys, cut),
1441 }];
1442 out.extend(
1443 keys.iter()
1444 .filter(|k| k.at > cut)
1445 .map(|k| SpeedKey { at: k.at - cut, speed: k.speed }),
1446 );
1447 out
1448}
1449
1450/// A file the timeline plays from, and *which* of its audio streams it plays:
1451/// a file carrying one track per language is several sources, one per stream,
1452/// sharing a path. Two entries differing only in the stream are two sources --
1453/// they are what a clip names, and a clip plays exactly one stream.
1454///
1455/// The path is always canonical ([`Source::new`]), so the same file reached by
1456/// two paths is one source.
1457#[derive(Clone, Debug, Default)]
1458pub struct Source {
1459 pub path: PathBuf,
1460 /// Position among the file's audio tracks in file order, the numbering
1461 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
1462 /// single track, and for a silent one.
1463 pub audio_stream: usize,
1464 /// Starred in the library (v51). Not part of the source's identity.
1465 pub fav: bool,
1466 /// The [`Bin`] this source is filed in (v51); `0` for none, the library's top level.
1467 pub bin: u32,
1468}
1469
1470/// A source is the file and the stream: starring it or filing it in a bin does not make it
1471/// another source.
1472impl PartialEq for Source {
1473 fn eq(&self, other: &Self) -> bool {
1474 self.path == other.path && self.audio_stream == other.audio_stream
1475 }
1476}
1477impl Eq for Source {}
1478
1479/// A named folder in the media library (v51). Ids start at 1 and are never reused in a session.
1480/// `parent` is `0` for a top-level bin, or the id of a top-level bin: one level of nesting.
1481#[derive(Clone, Debug, PartialEq, Eq)]
1482pub struct Bin {
1483 pub id: u32,
1484 pub parent: u32,
1485 pub name: String,
1486}
1487
1488/// The longest bin name.
1489pub const MAX_BIN_NAME_CHARS: usize = 60;
1490/// The most bins a project holds.
1491pub const MAX_BINS: usize = 1_000;
1492
1493/// A bin name as the library keeps it: trimmed, non-empty, short, no control characters.
1494pub fn clean_bin_name(name: &str) -> Result<String, String> {
1495 let name = name.trim();
1496 if name.is_empty() {
1497 return Err("a bin needs a name".into());
1498 }
1499 if name.chars().count() > MAX_BIN_NAME_CHARS {
1500 return Err(format!("a bin name is at most {MAX_BIN_NAME_CHARS} characters"));
1501 }
1502 if name.chars().any(char::is_control) {
1503 return Err("a bin name holds no control characters".into());
1504 }
1505 Ok(name.to_string())
1506}
1507
1508impl Project {
1509 /// The library's bins, in creation order (v51).
1510 pub fn bins(&self) -> &[Bin] {
1511 &self.bins
1512 }
1513
1514 /// The bins a load puts back, with no undo step. Ids are kept; new ones start past the largest.
1515 pub fn with_bins(mut self, bins: Vec<Bin>) -> Self {
1516 self.bin_next = bins.iter().map(|b| b.id).max().unwrap_or(0) + 1;
1517 self.bins = bins;
1518 self
1519 }
1520
1521 fn bin_name_taken(&self, parent: u32, name: &str, except: u32) -> bool {
1522 self.bins.iter().any(|b| b.parent == parent && b.id != except && b.name.eq_ignore_ascii_case(name))
1523 }
1524
1525 /// Makes a bin named `name` inside bin `parent` (`0`: at the top level). Only a top-level bin
1526 /// holds bins, and two bins in one place cannot share a name. One undo step; returns the id.
1527 pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> {
1528 let name = clean_bin_name(name)?;
1529 if parent != 0 {
1530 match self.bins.iter().find(|b| b.id == parent) {
1531 None => return Err(format!("there is no bin {parent}")),
1532 Some(b) if b.parent != 0 => return Err("bins nest one level deep: that bin is already inside another".into()),
1533 Some(_) => {}
1534 }
1535 }
1536 if self.bin_name_taken(parent, &name, 0) {
1537 return Err(format!("there is already a bin named {name} there"));
1538 }
1539 if self.bins.len() >= MAX_BINS {
1540 return Err(format!("a project holds at most {MAX_BINS} bins"));
1541 }
1542 self.snapshot();
1543 let id = self.bin_next;
1544 self.bin_next += 1;
1545 self.bins.push(Bin { id, parent, name });
1546 Ok(id)
1547 }
1548
1549 /// Renames bin `id`. `Ok(false)`, and no undo step, when the name is already that.
1550 pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> {
1551 let name = clean_bin_name(name)?;
1552 let Some(at) = self.bins.iter().position(|b| b.id == id) else {
1553 return Err(format!("there is no bin {id}"));
1554 };
1555 if self.bins[at].name == name {
1556 return Ok(false);
1557 }
1558 if self.bin_name_taken(self.bins[at].parent, &name, id) {
1559 return Err(format!("there is already a bin named {name} there"));
1560 }
1561 self.snapshot();
1562 self.bins[at].name = name;
1563 Ok(true)
1564 }
1565
1566 /// Removes bin `id`. What it held is not lost: its sources go to the bin it was in (the top
1567 /// level for a top-level one) and the bins inside it come out to the top level. Returns how
1568 /// many sources moved. One undo step.
1569 pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> {
1570 let Some(bin) = self.bins.iter().find(|b| b.id == id).cloned() else {
1571 return Err(format!("there is no bin {id}"));
1572 };
1573 self.snapshot();
1574 let mut moved = 0;
1575 for s in self.sources.iter_mut().filter(|s| s.bin == id) {
1576 s.bin = bin.parent;
1577 moved += 1;
1578 }
1579 self.bins.retain(|b| b.id != id);
1580 let children: Vec<u32> = self.bins.iter().filter(|b| b.parent == id).map(|b| b.id).collect();
1581 for c in children {
1582 let at = self.bins.iter().position(|b| b.id == c).expect("listed above");
1583 let mut name = self.bins[at].name.clone();
1584 let mut n = 1;
1585 while self.bin_name_taken(0, &name, c) {
1586 n += 1;
1587 name = format!("{} {n}", self.bins[at].name);
1588 }
1589 self.bins[at].name = name;
1590 self.bins[at].parent = 0;
1591 }
1592 Ok(moved)
1593 }
1594
1595 /// Files sources `srcs` in bin `bin` (`0`: out of every bin, to the top level). Returns how
1596 /// many changed; one undo step, none when nothing changes.
1597 pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> {
1598 if bin != 0 && !self.bins.iter().any(|b| b.id == bin) {
1599 return Err(format!("there is no bin {bin}"));
1600 }
1601 if let Some(bad) = srcs.iter().find(|&&i| i >= self.sources.len()) {
1602 return Err(format!("there is no source {bad}"));
1603 }
1604 let mut todo: Vec<usize> = srcs.iter().copied().filter(|&i| self.sources[i].bin != bin).collect();
1605 todo.sort_unstable();
1606 todo.dedup();
1607 if todo.is_empty() {
1608 return Ok(0);
1609 }
1610 self.snapshot();
1611 for &i in &todo {
1612 self.sources[i].bin = bin;
1613 }
1614 Ok(todo.len())
1615 }
1616
1617 /// Stars or unstars sources `srcs`. Returns how many changed; one undo step, none when
1618 /// nothing changes.
1619 pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> {
1620 if let Some(bad) = srcs.iter().find(|&&i| i >= self.sources.len()) {
1621 return Err(format!("there is no source {bad}"));
1622 }
1623 let mut todo: Vec<usize> = srcs.iter().copied().filter(|&i| self.sources[i].fav != on).collect();
1624 todo.sort_unstable();
1625 todo.dedup();
1626 if todo.is_empty() {
1627 return Ok(0);
1628 }
1629 self.snapshot();
1630 for &i in &todo {
1631 self.sources[i].fav = on;
1632 }
1633 Ok(todo.len())
1634 }
1635}
1636
1637impl Source {
1638 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
1639 Self {
1640 path: canonical(path.as_ref()),
1641 audio_stream,
1642 fav: false,
1643 bin: 0,
1644 }
1645 }
1646}
1647
1648/// Which three-point edit [`Project::edit_from_source`] makes.
1649#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1650pub enum SourceEdit {
1651 /// Opens room: what is at and after the frame moves later.
1652 Insert,
1653 /// Replaces what is there for the take's length; nothing moves.
1654 Overwrite,
1655}
1656
1657/// What a lane carries, which is what a *gap* in it means: black frames on a
1658/// video lane, silence on an audio one, nothing over the picture on a subtitle
1659/// one.
1660#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1661pub enum LaneKind {
1662 Video,
1663 Audio,
1664 /// Words over the picture, placed and trimmed like everything else
1665 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
1666 /// so a caption is dragged, cut, rippled and undone by the machinery every
1667 /// other clip already goes through.
1668 ///
1669 /// It carries no [`Clip`] at all, and that is what keeps the media paths
1670 /// free of it: [`Project::lane`] hands back an empty slice, so every
1671 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
1672 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
1673 /// check it already had, [`Project::composite_span_at`] and
1674 /// [`Project::audio_lanes`] never look at it, and the three doors that
1675 /// could still put a picture on one -- [`Project::from_parts`],
1676 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
1677 Subtitle,
1678}
1679
1680/// Which lane an operation acts on: a kind plus a 0-based position among the
1681/// lanes of that kind, so [`Lane::V1`] is the first video lane and
1682/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
1683///
1684/// A handle, not the lane itself. It stays meaningful while lanes are added,
1685/// and one naming a lane that is not there reads as an empty lane and refuses
1686/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
1687/// bounds check of its own.
1688#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1689pub struct Lane {
1690 pub kind: LaneKind,
1691 pub ord: usize,
1692}
1693
1694impl Lane {
1695 /// The first video lane: what a decoder plays and what an export renders.
1696 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
1697 /// The first audio lane: what the audio worker plays.
1698 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
1699 /// The first subtitle lane -- the one a project has only once something
1700 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
1701 /// alone.
1702 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
1703
1704 pub const fn new(kind: LaneKind, ord: usize) -> Self {
1705 Self { kind, ord }
1706 }
1707
1708 /// `V1`, `A2`: how a lane is written in a header column and named in an
1709 /// error about it.
1710 pub fn label(self) -> String {
1711 let kind = match self.kind {
1712 LaneKind::Video => 'V',
1713 LaneKind::Audio => 'A',
1714 LaneKind::Subtitle => 'S',
1715 };
1716 format!("{kind}{}", self.ord + 1)
1717 }
1718}
1719
1720/// The shortest a cue may be trimmed to, in microseconds.
1721pub const MIN_CUE_US: i64 = 100_000;
1722
1723/// One cue of a caption lane as the timeline shows it: where it lands, which cue of which track it
1724/// is, and the part `window` of the cue's own clock that is shown.
1725#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1726pub struct CueSpan {
1727 pub start_us: i64,
1728 pub end_us: i64,
1729 pub track: usize,
1730 pub cue: usize,
1731 pub window: (i64, i64),
1732}
1733
1734/// One cue's saved word times: `(track, cue, [(start_us, end_us, word)])`.
1735pub type CueWordRow = (usize, usize, Vec<(i64, i64, String)>);
1736
1737/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
1738/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
1739/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
1740/// frames. Never empty at either end.
1741///
1742/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
1743/// actually has, and placed by the same one number: the window is in the
1744/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
1745/// placement is in timeline frames like everything else on a lane. So the lane
1746/// invariant is the lane's ([`subs_sorted_disjoint`] is
1747/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
1748/// else, and only the two calls that change a *duration* -- a trim, and the
1749/// mapping out -- ever need the timeline's rate.
1750///
1751/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
1752/// paste and an undo snapshot are a plain assignment and can never dangle.
1753#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1754pub struct SubClip {
1755 /// Timeline frame its first frame is shown at.
1756 pub start: u32,
1757 /// How many timeline frames it covers; `>= 1`. Held rather than derived
1758 /// from the window because a [`Project`] has no frame rate -- the rate
1759 /// enters at the door of the two calls that need it -- and every placement
1760 /// question (where it ends, what it overlaps) is asked in frames.
1761 pub frames: u32,
1762 /// Index into [`Project::subtitles`]: *which* track's words these are.
1763 pub track: usize,
1764 /// The half-open window of that track it shows, in microseconds from the
1765 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
1766 /// timed in, so no conversion stands between a cue and the window that
1767 /// keeps it.
1768 pub in_us: i64,
1769 pub out_us: i64,
1770 /// Group id: `Some` exactly when a hand put this caption in a group with
1771 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
1772 /// no group, and what a cut cuts apart loses the one it had
1773 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
1774 /// clip is what makes the caption move, trim and delete with it.
1775 pub link: Option<u32>,
1776}
1777
1778impl SubClip {
1779 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
1780 /// what every overlap question is asked of.
1781 pub fn end(&self) -> u32 {
1782 self.start + self.frames
1783 }
1784
1785 /// The whole of caption track `track`, whose last cue ends at `end_us`, as
1786 /// one placement at `fps` -- what a palette row dropped on a subtitle lane
1787 /// carries. The window is the frames' own length, not the track's: a track
1788 /// that ends between two frames (4.750 s on 143 frames) would otherwise be
1789 /// stretched over the frames it occupies, and every cue would show late by
1790 /// that fraction. The frames are the fewest that hold the last cue.
1791 pub fn whole_track(track: usize, end_us: i64, fps: f64) -> SubClip {
1792 let us_of = |f: u32| (f64::from(f) / fps * 1e6).round() as i64;
1793 let mut frames = ((end_us as f64) * fps / 1e6).ceil().clamp(1., f64::from(u32::MAX)) as u32;
1794 // The ceiling is at most one frame short, once the microsecond rounding is counted.
1795 if us_of(frames) < end_us {
1796 frames += 1;
1797 }
1798 let out_us = us_of(frames);
1799 SubClip { start: 0, frames, track, in_us: 0, out_us, link: None }
1800 }
1801
1802 /// How much of its track it shows, in microseconds; `>= 1` by the
1803 /// never-empty invariant, and never more than [`MAX_WINDOW_US`] for one
1804 /// that came through a door.
1805 pub fn window_us(&self) -> i64 {
1806 self.out_us.saturating_sub(self.in_us)
1807 }
1808
1809 /// Where in its window the timeline frame `frame` falls, in microseconds --
1810 /// the cut a split, a ripple and a trim all land on.
1811 ///
1812 /// By proportion and not by the timeline's rate: the window and the frame
1813 /// count measure the same stretch of time, so the fraction of the frames
1814 /// before `frame` is the fraction of the microseconds before it. That is
1815 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
1816 /// without either of them learning an fps.
1817 ///
1818 /// Total arithmetic, and clamped to the window it is cutting: the
1819 /// `saturating_mul` is what a `SubClip` built by a caller rather than a
1820 /// door gets (a hand-built one, a unit test, a future door that forgot the
1821 /// bound) -- a wrapped window would put a caption's clock *before* its own
1822 /// start, and the split that produced it would then hand back two halves
1823 /// whose windows do not meet. The clamp is the never-empty invariant
1824 /// restated: the answer is a point inside `[in_us, out_us]` or nothing.
1825 fn window_at(&self, frame: u32) -> i64 {
1826 let into = i64::from(frame.saturating_sub(self.start));
1827 let window = self.window_us().max(0);
1828 let at = window.saturating_mul(into) / i64::from(self.frames.max(1));
1829 self.in_us.saturating_add(at.min(window))
1830 }
1831}
1832
1833/// One lane: what it is and what it holds. A struct rather than a bare
1834/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
1835/// compositing mode, a name -- and it belongs next to the clips it applies to.
1836#[derive(Clone, Debug, PartialEq)]
1837struct LaneData {
1838 kind: LaneKind,
1839 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
1840 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
1841 /// ever seeing a subtitle: they all read this list.
1842 clips: Vec<Clip>,
1843 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
1844 /// empty on a video or audio one. Beside the clips rather than an enum over
1845 /// them so that everything a lane *is* -- its place in the stack, its
1846 /// label, its undo snapshot, its removal -- stays one code path for all
1847 /// three kinds.
1848 subs: Vec<SubClip>,
1849 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
1850 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
1851 /// makes it a different thing from a clip's equalizer: it moves everything
1852 /// on the track by the same amount, cuts included. Meaningless on a video
1853 /// lane, where it is kept at 0 and asked by nothing.
1854 gain_db: f32,
1855 /// Where this audio lane sits between the speakers, `-1.0..=1.0`, `0.0` the
1856 /// middle ([`Project::lane_pan`]); applied on top of each clip's own pan.
1857 pan: f32,
1858 /// The auto-ducks on this audio lane ([`Project::lane_duck_list`]): each
1859 /// drops the lane while the key lane it names is loud, so a lane can be
1860 /// ducked under several keys at once and the drops multiply. At most one per
1861 /// key, in the order they were set. Empty for every other lane.
1862 ducks: Vec<Duck>,
1863 /// The voice processors of this audio lane ([`Project::lane_voice`]): gate,
1864 /// noise reduction, compressor and de-esser, all off for a lane nobody has
1865 /// cleaned. Default on every other lane.
1866 voice: VoiceFx,
1867 /// Whether a video lane is left out of the picture, or a subtitle lane's
1868 /// words are left out of the screen and the export
1869 /// ([`Project::lane_hidden`]). Kept on the lane, not in a view, so that the
1870 /// editor and an export read one answer.
1871 hidden: bool,
1872 /// Whether an audio lane is silenced in the mix ([`Project::lane_muted`]).
1873 /// Its clips and its volume are untouched, so unmuting restores exactly
1874 /// what was there.
1875 muted: bool,
1876 /// Pure state for the front-end, which refuses edits to a locked lane. The
1877 /// engine's own operations ignore it ([`Project::lane_locked`]).
1878 locked: bool,
1879 /// The display label the user gave this lane ([`Project::lane_name`]); empty
1880 /// for none. The address (V1, A2) is unchanged by it.
1881 name: String,
1882}
1883
1884/// The longest lane name, in characters.
1885pub const MAX_LANE_NAME_CHARS: usize = 40;
1886
1887/// The three per-lane switches a save writes ([`Project::lane_flags`]), as one
1888/// value so that the file and the editor name them the same way.
1889#[derive(Clone, Copy, Debug, Default, PartialEq)]
1890pub struct LaneFlags {
1891 pub hidden: bool,
1892 pub muted: bool,
1893 pub locked: bool,
1894 /// An audio lane's pan ([`Project::lane_pan`]); carried here because it is saved and
1895 /// loaded with the switches.
1896 pub pan: f32,
1897}
1898
1899impl LaneData {
1900 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
1901 Self {
1902 kind,
1903 clips,
1904 subs: Vec::new(),
1905 gain_db: 0.0,
1906 pan: 0.0,
1907 ducks: Vec::new(),
1908 voice: VoiceFx::default(),
1909 hidden: false,
1910 muted: false,
1911 locked: false,
1912 name: String::new(),
1913 }
1914 }
1915
1916 /// The two lanes a project starts with: `V1` then `A1`, in display order.
1917 /// One place, because a freshly opened file is exactly this pair.
1918 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
1919 vec![
1920 LaneData::new(LaneKind::Video, video),
1921 LaneData::new(LaneKind::Audio, audio),
1922 ]
1923 }
1924}
1925
1926/// The placements one group id names, split by the two lists a lane holds:
1927/// what a drag, a trim and a delete each have to walk, now that a group may
1928/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
1929/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
1930/// -- so the pairs are `(lane storage index, index into that lane's list)`.
1931#[derive(Default)]
1932struct Members {
1933 clips: Vec<(usize, usize)>,
1934 subs: Vec<(usize, usize)>,
1935}
1936
1937impl Members {
1938 /// Whether the group is the one placement and no more: what a lift leaves
1939 /// behind, and what every whole-group question answers "not one" for.
1940 fn alone(&self) -> bool {
1941 self.clips.len() + self.subs.len() < 2
1942 }
1943}
1944
1945/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
1946#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1947pub enum Edge {
1948 /// Its first timeline frame; moving it changes where in the source the clip
1949 /// starts reading, so the picture behind the edge slides with it.
1950 Start,
1951 /// One past its last timeline frame; moving it only says how much of the
1952 /// source to keep.
1953 End,
1954}
1955
1956/// The two walls an edge may travel between, `(first, last)` timeline frame
1957/// inclusive, and which of them is the source's own media limit: its head
1958/// (for a start edge) or its tail (for an end edge). The other wall is a
1959/// neighbouring clip, the timeline's first frame, or the clip's own minimum
1960/// length -- never media. `lo_media`/`hi_media` say which, so a front-end can
1961/// tell a trim that ran out of source from one that ran into a clip.
1962#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1963pub struct TrimWalls {
1964 pub lo: u32,
1965 pub hi: u32,
1966 pub lo_media: bool,
1967 pub hi_media: bool,
1968}
1969
1970/// What stops an edge at one of its walls ([`Project::trim_bounds`]): the thing a
1971/// front-end names when a drag or a trim comes to rest there. Wherever a wall is
1972/// the frame a neighbour or the timeline sets, the clip sitting at that wall does
1973/// not say which, so this does.
1974#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1975pub enum WallBound {
1976 /// The source's own limit: its head for a start edge, its tail for an end
1977 /// edge. A clip that has run out of source.
1978 Source,
1979 /// The neighbouring clip on the same lane: the end of the one in front of a
1980 /// start edge, or the start of the one behind an end edge -- at this timeline
1981 /// frame.
1982 Neighbour(u32),
1983 /// The timeline's first frame, with no clip in front of the edge.
1984 Timeline,
1985 /// The clip's own minimum length: one source frame, at its rate.
1986 MinLength,
1987 /// The length a still image is held to -- the table's cap, which is not a
1988 /// source's end (a still has none to run out of).
1989 Cap,
1990}
1991
1992/// The length each source has on each kind of lane, in timeline frames: what a
1993/// trim measures its walls against. A picture and a sound of one file need not
1994/// end on the same frame ([`crate::playback`]'s audio-lane table), and a linked
1995/// take drags both edges together, so a trim of one lane has to hold the other
1996/// to the other's own length.
1997#[derive(Clone, Copy, Debug)]
1998pub struct SourceWalls<'a> {
1999 /// The length on a video lane (and on a subtitle lane, which has none).
2000 pub picture: &'a [u32],
2001 /// The length on an audio lane.
2002 pub sound: &'a [u32],
2003}
2004
2005impl<'a> SourceWalls<'a> {
2006 /// One table for both kinds of lane: for a caller that has only the one.
2007 pub fn same(frames: &'a [u32]) -> Self {
2008 Self {
2009 picture: frames,
2010 sound: frames,
2011 }
2012 }
2013
2014 /// The table a clip on a lane of `kind` is walled by.
2015 fn for_kind(&self, kind: LaneKind) -> &'a [u32] {
2016 if kind == LaneKind::Audio {
2017 self.sound
2018 } else {
2019 self.picture
2020 }
2021 }
2022}
2023
2024/// What a lane holds over one stretch of the timeline: either a placed clip or
2025/// a gap. Returned already trimmed to the position it was asked about, so a
2026/// caller can hand `len` straight to a decoder (or to a black-frame generator).
2027#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2028pub struct Span {
2029 /// Timeline frame the span starts at.
2030 pub start: u32,
2031 /// Frames it covers; `>= 1`.
2032 pub len: u32,
2033 /// `(source index, first source frame)`, or `None` for a gap -- which the
2034 /// engine renders as black frames and as silence.
2035 pub from: Option<(usize, u32)>,
2036 /// The rate the clip this came off plays at ([`Clip::speed`]);
2037 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
2038 /// timeline frames whatever it says -- the speed is how many *source* frames
2039 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
2040 /// come back to the timeline.
2041 pub speed: Speed,
2042 /// The speed ramp of the clip this came off, when it has one ([`Clip::speed_keys`]),
2043 /// based at this span's first frame. A ramped span's [`speed`](Span::speed) is
2044 /// [`Speed::NORMAL`]: a constant rate would be wrong for it, and real time is what
2045 /// a decoder reads every frame at, so every mapping goes through
2046 /// [`source_offset`](Span::source_offset) instead.
2047 pub ramp: Option<SpeedRamp>,
2048 /// Whether the clip this came off plays backwards ([`Clip::reversed`]). Then
2049 /// `from` still names the source frame the span's first timeline frame shows --
2050 /// the highest of the frames it reads -- and every later frame is
2051 /// [`source_offset`](Span::source_offset) *below* it ([`Span::source_at`]); the
2052 /// offsets themselves, [`source_len`](Span::source_len) and
2053 /// [`timeline_at`](Span::timeline_at) count distance walked, as they do forwards.
2054 /// `false` for a gap.
2055 pub reverse: bool,
2056 /// The pitch in semitones of the clip this came off ([`Clip::pitch`]); `0` for a gap.
2057 pub pitch: i8,
2058}
2059
2060impl Span {
2061 /// One past the last timeline frame it covers.
2062 pub fn end(&self) -> u32 {
2063 self.start + self.len
2064 }
2065
2066 /// Source frames from this span's first frame to its `offset`th: the mapping
2067 /// `speed.source_at(offset)` is for a constant rate, and the ramp's integral when
2068 /// the span carries one. Added to the span's `from` source frame it gives the
2069 /// frame the timeline frame at `offset` shows.
2070 pub fn source_offset(&self, offset: u32) -> u32 {
2071 match &self.ramp {
2072 None => self.speed.source_at(offset),
2073 Some(ramp) => ramp.source_offset(offset),
2074 }
2075 }
2076
2077 /// The source frame the timeline frame `offset` into the span shows, given
2078 /// `first`, the span's own first one (`from`'s): up for a span that plays
2079 /// forwards, down for a reversed one.
2080 pub fn source_at(&self, first: u32, offset: u32) -> u32 {
2081 match self.reverse {
2082 false => first + self.source_offset(offset),
2083 true => first.saturating_sub(self.source_offset(offset)),
2084 }
2085 }
2086
2087 /// The half-open range of source frames this span reads, `first..end`, in the
2088 /// order they are numbered in the file whichever way they are played. `None` for
2089 /// a gap. The window a decoder is opened over, and an audio segment's.
2090 pub fn source_window(&self) -> Option<(usize, u32, u32)> {
2091 let (source, first) = self.from?;
2092 let len = self.source_len();
2093 Some(match self.reverse {
2094 false => (source, first, first + len),
2095 true => (source, (first + 1).saturating_sub(len), first + 1),
2096 })
2097 }
2098
2099 /// How many source frames it reads: what a decoder is asked for and how wide
2100 /// an audio window is. `len` at real time, and the one arithmetic both the
2101 /// picture and the sound go through, so they cannot disagree about where a
2102 /// speeded clip ends.
2103 pub fn source_len(&self) -> u32 {
2104 match self.from {
2105 // The last timeline frame's own source frame is the last one needed
2106 // -- never one more, which at a slow rate would read a frame the
2107 // next clip owns and at a fast one would decode a picture nothing
2108 // shows.
2109 Some(_) => self.source_offset(self.len.saturating_sub(1)) + 1,
2110 None => self.len,
2111 }
2112 }
2113
2114 /// Where a source frame of this span lands on the timeline: the stamp
2115 /// playback puts on a decoded frame, through the ceil half of the pair
2116 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
2117 /// frame, so a frame before it stamps at the span's start.
2118 pub fn timeline_at(&self, source_frame: u32) -> u32 {
2119 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
2120 let rel = source_frame.saturating_sub(base);
2121 self.start
2122 + match &self.ramp {
2123 None => self.speed.timeline_at(rel),
2124 Some(ramp) => ramp.timeline_at(rel),
2125 }
2126 }
2127}
2128
2129/// What one speeded audio segment asks of the worker: how many source frames to
2130/// consume per output frame, and how many seconds of timeline it has to fill.
2131/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
2132/// resampling at all.
2133#[derive(Clone, Copy, PartialEq, Debug)]
2134pub struct Stretch {
2135 /// Source frames per output frame -- the speed as a multiplier.
2136 pub step: f64,
2137 /// What the segment owes the timeline, which is what it is padded or
2138 /// trimmed to.
2139 pub timeline_secs: f64,
2140 /// The segment's speed ramp, when it has one: the stretch then follows the ramp's
2141 /// instantaneous rate rather than `step`, which is only the mean it falls back to.
2142 pub ramp: Option<SpeedRamp>,
2143 /// The timeline's frame rate, which the ramp's frames are counted in. The
2144 /// openers do not all know it, so the stretch carries it.
2145 pub fps: f64,
2146 /// Whether the segment's samples are played last to first
2147 /// ([`Clip::reversed`]). Then `step` is `1.0` when only the direction asks for a
2148 /// rate chain at all, and the window the segment names is the one to be reversed.
2149 pub reverse: bool,
2150 /// The pitch in semitones the segment is shifted by ([`Clip::pitch`]), `0` for none.
2151 /// The stretch then runs at `step / 2^(pitch/12)` and the resample at the same ratio
2152 /// up: the pitch moves, the length does not.
2153 pub pitch: i8,
2154}
2155
2156impl Stretch {
2157 /// Whether the segment is only played backwards, at the rate it was recorded:
2158 /// no change of time, so no stretch is built for it.
2159 pub fn is_straight(&self) -> bool {
2160 self.reverse && self.step == 1.0 && self.ramp.is_none() && self.pitch == 0
2161 }
2162
2163 /// The frequency ratio the segment's pitch shift is: `2^(pitch/12)`, `1.0` for none.
2164 pub fn pitch_ratio(&self) -> f64 {
2165 pitch_ratio(self.pitch)
2166 }
2167}
2168
2169/// The frequency ratio of a shift of `semitones`: `2^(semitones/12)`, so `12` is an octave up.
2170pub fn pitch_ratio(semitones: i8) -> f64 {
2171 (f64::from(semitones) / 12.0).exp2()
2172}
2173
2174/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
2175/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
2176/// against where in the *clip* -- not the segment, which may start mid-clip
2177/// on a seek -- this segment's first frame lands.
2178#[derive(Clone, PartialEq, Debug)]
2179pub struct Fade {
2180 /// How many of the clip's own frames already played before this
2181 /// segment's first frame: `0` unless playback started mid-clip.
2182 pub elapsed: u32,
2183 /// The clip's [`Clip::fade_in`].
2184 pub fade_in: u32,
2185 /// The clip's [`Clip::fade_out`].
2186 pub fade_out: u32,
2187 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
2188 /// which this segment may only cover the tail.
2189 pub total: u32,
2190 /// The clip's [`Clip::gain_db`] as a linear multiplier, `1.0` for unity.
2191 /// It rides in the envelope because the envelope is what both the
2192 /// playback feeder and the export are handed, so the two cannot disagree.
2193 pub gain: f32,
2194 /// The left and right multipliers of the clip's pan and its lane's
2195 /// ([`pan_gains`]), `(1.0, 1.0)` for the middle. Only a stereo mix has a
2196 /// side to turn down; any other width plays it as it is.
2197 pub pan: (f32, f32),
2198 /// The clip's [`Clip::gain_keys`] as `(position, dB, ease)` triples, `None` for a
2199 /// clip with none. The position is clip-relative and in this envelope's own
2200 /// unit: timeline frames when [`Project::lane_fades_from`] builds it, audio
2201 /// frames once [`Fade::scaled`] has counted it. Shared, so the envelope
2202 /// stays cheap to hand around.
2203 pub curve: Option<std::sync::Arc<[(f64, f32, KeyEase)]>>,
2204}
2205
2206/// The left and right multipliers of a clip pan and a lane pan, each `-1.0..=1.0`: a
2207/// balance, where the side away from the pan is turned down along a quarter sine
2208/// (`cos(pan * pi/2)`, silent at the far end) and the near side is left alone,
2209/// so the middle is exactly unity.
2210impl Clip {
2211 /// [`Clip::pan`] as `-1.0..=1.0`.
2212 pub fn pan_value(&self) -> f32 {
2213 f32::from(self.pan) / 100.0
2214 }
2215}
2216
2217pub fn pan_gains(clip: f32, lane: f32) -> (f32, f32) {
2218 let side = |p: f32| {
2219 let p = p.clamp(-1.0, 1.0);
2220 (p.max(0.0) * std::f32::consts::FRAC_PI_2, (-p).max(0.0) * std::f32::consts::FRAC_PI_2)
2221 };
2222 let (cl, cr) = side(clip);
2223 let (ll, lr) = side(lane);
2224 // cos(pi/2) is not exactly 0 in f32: the far end is silence, so say so.
2225 let snap = |g: f32| if g < 1e-6 { 0.0 } else { g };
2226 (snap(cl.cos() * ll.cos()), snap(cr.cos() * lr.cos()))
2227}
2228
2229impl Fade {
2230 /// The gain at clip-relative frame `pos`, an equal-power curve on each
2231 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
2232 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
2233 /// ramp, so a fade lands on silence at its very first (or very last)
2234 /// frame and reaches unity smoothly rather than at a constant slope --
2235 /// the same curve [`Project::crossfade`] relies on to keep two clips'
2236 /// sum around one level through the join. Both ramps multiply where a
2237 /// clip is short enough for them to overlap.
2238 fn gain_at(&self, pos: u32) -> f32 {
2239 let mut g = self.gain;
2240 if let Some(curve) = &self.curve {
2241 g *= db_to_linear(lerp_db(curve, |&p| p, f64::from(pos)));
2242 }
2243 if self.fade_in > 0 && pos < self.fade_in {
2244 let t = pos as f32 / self.fade_in as f32;
2245 g *= (t * std::f32::consts::FRAC_PI_2).sin();
2246 }
2247 if self.fade_out > 0 {
2248 let out_start = self.total.saturating_sub(self.fade_out);
2249 if pos >= out_start {
2250 let remaining = self.total.saturating_sub(pos);
2251 let t = remaining as f32 / self.fade_out as f32;
2252 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
2253 }
2254 }
2255 g
2256 }
2257
2258 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
2259 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
2260 pub fn apply(&self, frames: &mut [f32], channels: usize) {
2261 for (i, block) in frames.chunks_mut(channels).enumerate() {
2262 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
2263 for s in block.iter_mut() {
2264 *s *= g;
2265 }
2266 if channels == 2 && block.len() == 2 {
2267 block[0] *= self.pan.0;
2268 block[1] *= self.pan.1;
2269 }
2270 }
2271 }
2272
2273 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
2274 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
2275 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
2276 /// position is in) but [`Self::apply`] multiplies *audio* frames --
2277 /// `channels`-wide sample blocks at whatever rate the mix is running at,
2278 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
2279 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
2280 /// few milliseconds into any clip, so a fade-out silenced the rest of the
2281 /// clip outright and a fade-in finished before a listener's ear caught up
2282 /// -- audible on nothing shorter than a clip a few fps-frames long, which
2283 /// is why 338 green tests never once ran the two curves out of step.
2284 /// `ratio` is `sample_rate / fps`, applied once where the audio session
2285 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
2286 pub fn scaled(self, ratio: f64) -> Fade {
2287 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
2288 Fade {
2289 elapsed: conv(self.elapsed),
2290 fade_in: conv(self.fade_in),
2291 fade_out: conv(self.fade_out),
2292 total: conv(self.total),
2293 gain: self.gain,
2294 pan: self.pan,
2295 curve: self.curve.as_ref().map(|c| {
2296 c.iter()
2297 .map(|&(x, db, ease)| (x * ratio, db, ease))
2298 .collect::<Vec<_>>()
2299 .into()
2300 }),
2301 }
2302 }
2303}
2304
2305/// What a save writes and a load takes back: the sources, every lane in
2306/// display order with its kind, and the equalizer and colour tables their clips
2307/// index into -- [`Project::without_orphan_sources`] out,
2308/// [`Project::from_parts`] in.
2309pub type Parts = (
2310 Vec<Source>,
2311 Vec<(LaneKind, Vec<Clip>)>,
2312 Vec<EqParams>,
2313 Vec<ColorParams>,
2314 Vec<TransformParams>,
2315);
2316
2317/// The next revision id to hand out. Process-wide, so two projects never share
2318/// an id and a revision read from one session means nothing in another.
2319static NEXT_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
2320
2321fn next_revision() -> u64 {
2322 NEXT_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2323}
2324
2325/// How many undo steps a project keeps. One gesture is one step, so 100 is past
2326/// any chain a person walks back by hand, and the oldest step is dropped rather
2327/// than the history growing without end: a snapshot is the whole lane list plus
2328/// the palette and the project's own settings, so on a 1394-clip jumpcut
2329/// timeline this is a bounded ~10 MB instead of a leak that grows for as long
2330/// as the session lasts.
2331const HISTORY_CAP: usize = 100;
2332
2333/// The project's own settings, as one value: the header a `.edith` file carries
2334/// beside the edit list, and what every undo step restores beside the lanes.
2335/// None of it is the media's own -- the scaffolding file's picture and rate
2336/// ([`PlaybackSession::native`]) stay on the session and are never rolled back.
2337#[derive(Clone, Debug, PartialEq)]
2338pub(crate) struct ProjectSettings {
2339 /// The canvas every clip is composed onto: the project resolution, which a
2340 /// clip of another size is placed onto rather than refused for.
2341 pub(crate) resolution: (u32, u32),
2342 /// The rate the timeline is cut at, which every clip and source is
2343 /// conformed to ([`Project::retime`]).
2344 pub(crate) frame_rate: f64,
2345 /// Which encoder an export of this project opens its picture on
2346 /// ([`crate::export::EncoderSeat`]).
2347 pub(crate) encoder_seat: crate::export::EncoderSeat,
2348 /// The rate the mix was picked to run at, or `None` for the one the first
2349 /// audio source derives.
2350 pub(crate) sample_rate: Option<u32>,
2351 /// Whether the picture is decoded from the stand-ins ([`crate::proxy`]).
2352 pub(crate) proxies: bool,
2353 /// Whether a source that wants a stand-in gets one made for it as it
2354 /// arrives ([`crate::proxy::wanted`]).
2355 pub(crate) auto_proxies: bool,
2356 /// Which HDR-to-SDR rendition the picture is watched and exported in.
2357 pub(crate) tone: crate::tonemap::Preset,
2358 /// The master limiter every lane's sound is summed through.
2359 pub(crate) limiter: Limiter,
2360 /// How burned captions animate, the default for `burn_captions`.
2361 pub(crate) caption_style: crate::captionanim::CaptionStyle,
2362 /// The free-text notes the project carries (v52). Empty until somebody writes one.
2363 pub(crate) notes: String,
2364 /// How long a still image is placed for, in seconds (v52).
2365 pub(crate) still_secs: f64,
2366}
2367
2368impl ProjectSettings {
2369 /// What a project built by hand carries before its constructor names the
2370 /// canvas: the defaults every fresh open has -- nobody has picked stand-ins
2371 /// (the films themselves are cut), an encoder or a mix rate, and the
2372 /// rendition and limiter are the reference ones. Every door that builds a
2373 /// session chains [`Project::with_canvas`] straight after, so the zero
2374 /// canvas here is never a project anybody plays from.
2375 fn placeholder() -> Self {
2376 Self {
2377 resolution: (0, 0),
2378 frame_rate: 0.0,
2379 encoder_seat: crate::export::EncoderSeat::default(),
2380 sample_rate: None,
2381 proxies: false,
2382 auto_proxies: false,
2383 tone: crate::tonemap::Preset::default(),
2384 limiter: Limiter::default(),
2385 caption_style: crate::captionanim::CaptionStyle::default(),
2386 notes: String::new(),
2387 still_secs: STILL_DEFAULT_SECS,
2388 }
2389 }
2390}
2391
2392/// One undo step: the lanes, the subtitle palette and the project's own
2393/// settings exactly as they were before the edit that pushed it. Whole values
2394/// rather than the lane list alone, so an undo (or a redo) restores all three
2395/// together and no half of one edit can come back without the others -- which
2396/// is what lets a subtitle removal reindex every placement and still undo: the
2397/// restored palette names the very tracks the restored placements index.
2398/// What a freshly pushed undo step displaced: the redo branch its edit cleared
2399/// and, when the cap was full, the oldest step it evicted. Moved, never cloned.
2400#[derive(Clone, Debug)]
2401struct PendingStep {
2402 redo: Vec<Snapshot>,
2403 evicted: Option<Snapshot>,
2404}
2405
2406#[derive(Clone, Debug)]
2407struct Snapshot {
2408 /// The revision of the state this step restores ([`Project::revision`]).
2409 revision: u64,
2410 /// The name of the edit that pushed this step ([`Project::name_step`]): what
2411 /// Undo and Redo say. `None` for a step nobody named, which reads as plain "Undo".
2412 /// It travels with the step, so an undo's redo entry carries the same name.
2413 label: Option<String>,
2414 lanes: Vec<LaneData>,
2415 subtitles: Vec<SubtitleTrack>,
2416 cue_edits: Vec<(usize, usize, String)>,
2417 cue_adds: Vec<AddedCue>,
2418 titles: Vec<Title>,
2419 chapters: Vec<Chapter>,
2420 markers: Vec<Marker>,
2421 settings: ProjectSettings,
2422 /// The files the clips index into, as the step had them: a relink is undone by putting the
2423 /// old path back here. A [`Source`] is a path and a stream index, so a copy is cheap.
2424 sources: Vec<Source>,
2425 /// The library's bins (v51).
2426 bins: Vec<Bin>,
2427 /// The sequence list: which is active, every name, and the parked ones' data.
2428 seq: Seqs,
2429}
2430
2431/// The source list an undo or redo step puts back: the step's own list, and past its end the
2432/// entries the step never knew of (imported after it). No clip in the step names one of those,
2433/// so keeping them leaves every index the step holds valid, and an undone edit leaves an import
2434/// in the library as an import always does.
2435fn restored_sources(step: Vec<Source>, now: &[Source]) -> Vec<Source> {
2436 let mut out = step;
2437 if now.len() > out.len() {
2438 out.extend_from_slice(&now[out.len()..]);
2439 }
2440 out
2441}
2442
2443/// The redo stack moved out by [`Project::take_redo`]: opaque, and only
2444/// [`Project::restore_redo`] reads it back.
2445pub struct RedoCheckpoint(Vec<Snapshot>);
2446
2447/// A cue somebody added to a subtitle track, which no file has: its track, its
2448/// times on the track's own clock and its words. Kept beside the file's cue
2449/// overrides ([`Project::cue_adds`]) because a `(track, cue, text)` override
2450/// names a cue by where the file has it, and an added cue has no such place.
2451#[derive(Clone, Debug, PartialEq, Eq)]
2452pub struct AddedCue {
2453 pub track: usize,
2454 pub start_us: i64,
2455 pub end_us: i64,
2456 pub text: String,
2457}
2458
2459/// One gap a close-all sweep left open, with the frame it still starts on and
2460/// the same refusal a single [`Project::gap_take_scope`] close would have said.
2461#[derive(Clone, Debug, PartialEq, Eq)]
2462pub struct GapSkip {
2463 pub start: u32,
2464 pub reason: String,
2465}
2466
2467/// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits,
2468/// skipped gaps are the take-safety refusals the sweep did not hide.
2469#[derive(Clone, Debug, Default, PartialEq, Eq)]
2470pub struct GapSweep {
2471 pub closed: usize,
2472 pub skipped: Vec<GapSkip>,
2473}
2474
2475/// A chapter marker: a named frame on the timeline, the point a viewer's chapter
2476/// list jumps to. Sorted by frame, at most one per frame ([`Project::chapters`]).
2477/// Saved as `chapter` lines ([`crate::edith`]).
2478#[derive(Clone, Debug, PartialEq, Eq)]
2479pub struct Chapter {
2480 /// The timeline frame the chapter starts on.
2481 pub frame: u32,
2482 /// What the chapter is called in the list.
2483 pub title: String,
2484}
2485
2486/// The longest chapter name, in characters: the most a video platform's chapter
2487/// list shows.
2488pub const MAX_CHAPTER_CHARS: usize = 100;
2489
2490/// Whether `chapter` is a chapter the project may hold: the checks
2491/// [`Project::add_chapter`] makes and the `.edith` loader makes of every `chapter` line.
2492pub fn check_chapter(chapter: &Chapter) -> crate::Result<()> {
2493 if chapter.title.trim().is_empty() {
2494 return Err("a chapter needs a name".into());
2495 }
2496 if chapter.title.chars().count() > MAX_CHAPTER_CHARS {
2497 return Err(format!("a chapter name holds at most {MAX_CHAPTER_CHARS} characters").into());
2498 }
2499 Ok(())
2500}
2501
2502/// A marker's colour: the small fixed palette an editor's marker strip draws.
2503#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2504pub enum MarkerColor {
2505 Red,
2506 Orange,
2507 Yellow,
2508 Green,
2509 #[default]
2510 Blue,
2511 Purple,
2512}
2513
2514impl MarkerColor {
2515 /// Every colour, in palette order.
2516 pub const ALL: [MarkerColor; 6] = [
2517 MarkerColor::Red,
2518 MarkerColor::Orange,
2519 MarkerColor::Yellow,
2520 MarkerColor::Green,
2521 MarkerColor::Blue,
2522 MarkerColor::Purple,
2523 ];
2524
2525 /// The name the `.edith` file and the MCP tools use.
2526 pub fn name(self) -> &'static str {
2527 match self {
2528 MarkerColor::Red => "red",
2529 MarkerColor::Orange => "orange",
2530 MarkerColor::Yellow => "yellow",
2531 MarkerColor::Green => "green",
2532 MarkerColor::Blue => "blue",
2533 MarkerColor::Purple => "purple",
2534 }
2535 }
2536
2537 /// The colour called `name` (any case), if it is one of the palette.
2538 pub fn from_name(name: &str) -> Option<MarkerColor> {
2539 MarkerColor::ALL.into_iter().find(|c| c.name().eq_ignore_ascii_case(name.trim()))
2540 }
2541
2542 /// The colour after this one in the palette, wrapping: what the GUI's "next colour" steps through.
2543 pub fn next(self) -> MarkerColor {
2544 let i = MarkerColor::ALL.iter().position(|c| *c == self).unwrap_or(0);
2545 MarkerColor::ALL[(i + 1) % MarkerColor::ALL.len()]
2546 }
2547}
2548
2549/// A comment marker: a named, coloured point on the timeline with an optional note, or a
2550/// range when `length` is not 0. Separate from a [`Chapter`]; it moves with the picture the
2551/// same way. Sorted by frame; several may share a frame ([`Project::markers`]). Saved as
2552/// `marker` lines ([`crate::edith`]).
2553#[derive(Clone, Debug, PartialEq, Eq)]
2554pub struct Marker {
2555 /// The timeline frame the marker starts on.
2556 pub frame: u32,
2557 /// How many frames it spans; 0 is a point.
2558 pub length: u32,
2559 pub name: String,
2560 /// A free-text note; may be empty.
2561 pub note: String,
2562 pub color: MarkerColor,
2563}
2564
2565impl Marker {
2566 /// The frame a range marker ends on (exclusive); its start for a point.
2567 pub fn end(&self) -> u32 {
2568 self.frame.saturating_add(self.length)
2569 }
2570}
2571
2572/// The longest marker name, in characters.
2573pub const MAX_MARKER_NAME_CHARS: usize = 100;
2574/// The longest marker note, in characters.
2575pub const MAX_MARKER_NOTE_CHARS: usize = 2000;
2576
2577/// Whether `marker` is a marker the project may hold: the checks [`Project::add_marker`]
2578/// makes and the `.edith` loader makes of every `marker` line.
2579pub fn check_marker(marker: &Marker) -> crate::Result<()> {
2580 if marker.name.trim().is_empty() {
2581 return Err("a marker needs a name".into());
2582 }
2583 if marker.name.chars().count() > MAX_MARKER_NAME_CHARS {
2584 return Err(format!("a marker name holds at most {MAX_MARKER_NAME_CHARS} characters").into());
2585 }
2586 if marker.note.chars().count() > MAX_MARKER_NOTE_CHARS {
2587 return Err(format!("a marker note holds at most {MAX_MARKER_NOTE_CHARS} characters").into());
2588 }
2589 if marker.frame.checked_add(marker.length).is_none_or(|e| e > MAX_TITLE_END) {
2590 return Err("a marker runs past the last frame there is".into());
2591 }
2592 Ok(())
2593}
2594
2595/// The longest text a title can hold, in characters.
2596pub const MAX_TITLE_CHARS: usize = 500;
2597
2598/// The furthest frame a title may end on. Far past any timeline anyone cuts,
2599/// and far below `u32::MAX`, so `start + frames` cannot wrap.
2600pub const MAX_TITLE_END: u32 = 100_000_000;
2601
2602/// A text overlay on the timeline: a title card over black, or a caption such
2603/// as a lower third over the picture. Titles are a project-level list, not a
2604/// lane: they are drawn over the composed picture (black where no clip plays),
2605/// in list order, so a later title sits on top of an earlier one. Saved as
2606/// `title` lines ([`crate::edith`]).
2607#[derive(Clone, Debug, PartialEq)]
2608pub struct Title {
2609 /// The first timeline frame the title shows on.
2610 pub start: u32,
2611 /// How many frames it shows for; `>= 1`.
2612 pub frames: u32,
2613 /// The words, with `\n` as a line break. Non-empty, at most
2614 /// [`MAX_TITLE_CHARS`] characters.
2615 pub text: String,
2616 /// How the words are set. Its size is kept inside [`SIZE_RANGE`].
2617 pub style: TextStyle,
2618 /// Frames the title takes to come up from nothing: the first frame shows
2619 /// `1 / (fade_in + 1)` of it. `0` for no fade-in.
2620 pub fade_in: u32,
2621 /// Frames the title takes to go back to nothing, counted off the end.
2622 /// `0` for no fade-out.
2623 pub fade_out: u32,
2624 /// The animation it comes in with ([`crate::titleanim`]); `None` for none.
2625 pub in_anim: TitleAnim,
2626 /// The animation it goes out with; the reverse of `in_anim`'s motion.
2627 pub out_anim: TitleAnim,
2628 /// How many frames each animation takes; `>= 1` when either is set and at most `frames`.
2629 pub anim_frames: u32,
2630 /// The title's own keyframe animation, counted from its first frame: sorted by `at`, no two
2631 /// at one frame, at most [`MAX_TRANSFORM_KEYS`]. Empty for a title without one.
2632 pub keys: Vec<TitleKey>,
2633}
2634
2635impl Title {
2636 /// One past the last frame the title covers.
2637 pub fn end(&self) -> u32 {
2638 self.start.saturating_add(self.frames)
2639 }
2640
2641 /// How much of the title shows on timeline frame `frame`, 0 to 255: its
2642 /// fades and animations ramp it up and down, and a frame outside the title shows none.
2643 pub fn alpha_at(&self, frame: u32) -> u8 {
2644 self.motion_at(frame).map_or(0, |m| m.alpha)
2645 }
2646}
2647
2648/// A one-click look for a title. The app's title card and MCP's `preset` argument both
2649/// apply these, so the two never disagree on what "lower third" means.
2650#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2651pub enum TitlePreset {
2652 LowerThird,
2653 Centered,
2654 CaptionBar,
2655}
2656
2657impl TitlePreset {
2658 /// Every preset, in the order the app lists them.
2659 pub const ALL: [TitlePreset; 3] = [TitlePreset::LowerThird, TitlePreset::Centered, TitlePreset::CaptionBar];
2660
2661 /// The word that names the preset in MCP: `lower_third`, `centered` or `caption_bar`.
2662 pub fn key(self) -> &'static str {
2663 match self {
2664 TitlePreset::LowerThird => "lower_third",
2665 TitlePreset::Centered => "centered",
2666 TitlePreset::CaptionBar => "caption_bar",
2667 }
2668 }
2669
2670 /// The preset a word names, if it names one.
2671 pub fn from_key(word: &str) -> Option<TitlePreset> {
2672 TitlePreset::ALL.into_iter().find(|p| p.key() == word)
2673 }
2674
2675 /// The style and the fade length in seconds (in and out).
2676 pub fn look(self) -> (TextStyle, f64) {
2677 let base = TextStyle::default();
2678 match self {
2679 TitlePreset::LowerThird => (
2680 TextStyle {
2681 size: 45,
2682 outline: Outline::None,
2683 boxed: true,
2684 place: Place::Bottom,
2685 hplace: HPlace::Left,
2686 align: Align::Left,
2687 weight: Weight::Bold,
2688 ..base
2689 },
2690 0.5,
2691 ),
2692 TitlePreset::Centered => (TextStyle { size: 100, outline: Outline::Thin, boxed: false, place: Place::Centre, ..base }, 0.5),
2693 TitlePreset::CaptionBar => (TextStyle { size: 40, outline: Outline::None, boxed: true, place: Place::Bottom, ..base }, 0.0),
2694 }
2695 }
2696}
2697
2698impl Title {
2699 /// `self` in `preset`'s look. The words and timing stay; fades are held to half the
2700 /// title's length, so in and out never cross.
2701 pub fn apply_preset(&mut self, preset: TitlePreset, fps: f64) {
2702 let (style, fade) = preset.look();
2703 let fade = ((fade * fps).round() as u32).min(self.frames / 2);
2704 self.style = style;
2705 self.fade_in = fade;
2706 self.fade_out = fade;
2707 }
2708}
2709
2710/// Whether `title` is a title the project may hold: the checks [`Project::add_title`]
2711/// makes and the `.edith` loader makes of every `title` line.
2712pub fn check_title(title: &Title) -> crate::Result<()> {
2713 if title.frames == 0 {
2714 return Err("a title must show for at least one frame".into());
2715 }
2716 if title.text.trim().is_empty() {
2717 return Err("a title needs some text".into());
2718 }
2719 if title.text.chars().count() > MAX_TITLE_CHARS {
2720 return Err(format!("a title holds at most {MAX_TITLE_CHARS} characters").into());
2721 }
2722 if title.end() > MAX_TITLE_END {
2723 return Err(format!("a title ends past frame {MAX_TITLE_END}").into());
2724 }
2725 if title.fade_in > title.frames || title.fade_out > title.frames {
2726 return Err("a title's fades are no longer than the title".into());
2727 }
2728 let animated = title.in_anim != TitleAnim::None || title.out_anim != TitleAnim::None;
2729 if animated && (title.anim_frames == 0 || title.anim_frames > title.frames) {
2730 return Err("a title's animations last at least one frame and no longer than the title".into());
2731 }
2732 if !(SIZE_RANGE.0..=SIZE_RANGE.1).contains(&title.style.size) {
2733 return Err(format!(
2734 "a title's size is {}..={} permille of the frame height",
2735 SIZE_RANGE.0, SIZE_RANGE.1
2736 )
2737 .into());
2738 }
2739 if title.keys.len() > MAX_TRANSFORM_KEYS {
2740 return Err(format!("a title holds at most {MAX_TRANSFORM_KEYS} keys").into());
2741 }
2742 for (i, k) in title.keys.iter().enumerate() {
2743 // A NaN fails every range check, so it is refused along with the out-of-range values.
2744 let in_range = (-1.0..=1.0).contains(&k.x)
2745 && (-1.0..=1.0).contains(&k.y)
2746 && (KEY_SCALE_RANGE.0..=KEY_SCALE_RANGE.1).contains(&k.scale)
2747 && (0.0..=1.0).contains(&k.opacity);
2748 if !in_range {
2749 return Err("a title key's x and y are -1..=1, its scale 0.05..=10 and its opacity 0..=1".into());
2750 }
2751 if i > 0 && title.keys[i - 1].at >= k.at {
2752 return Err("a title's keys are in frame order, with no two at one frame".into());
2753 }
2754 }
2755 Ok(())
2756}
2757
2758/// One clip [`Project::clamp_to_walls`] shortened: its lane, its source, and its
2759/// out-point before (`from`) and after (`to`), in source frames.
2760#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2761pub struct WallClamp {
2762 pub lane: Lane,
2763 pub source: usize,
2764 pub from: u32,
2765 pub to: u32,
2766}
2767
2768/// The edit list plus its undo history.
2769#[derive(Clone, Debug)]
2770pub struct Project {
2771 /// Append-only: never popped, never reordered. See the module docs.
2772 sources: Vec<Source>,
2773 /// In display order, which is the order [`Lane::ord`] counts in: the nth
2774 /// lane of a kind here is that kind's `ord` n. Never empty.
2775 lanes: Vec<LaneData>,
2776 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
2777 eq: Vec<EqParams>,
2778 /// The same, for [`Clip::color`].
2779 color: Vec<ColorParams>,
2780 /// The same, for [`Clip::transform`].
2781 transform: Vec<TransformParams>,
2782 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
2783 /// whole lane list, the subtitle palette and the project's own settings,
2784 /// so adding a lane undoes as well and so does picking a resolution. Bounded
2785 /// by [`HISTORY_CAP`]: at the cap the oldest step goes.
2786 history: Vec<Snapshot>,
2787 /// Snapshots `undo` has stepped past; `redo` pops one. Cleared by
2788 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
2789 /// the undone steps came from. Not saved to `.edith`, matching `history`.
2790 redo: Vec<Snapshot>,
2791 /// Every snapshot pushed since the project was made, evicted ones included:
2792 /// [`Project::snapshot`] bumps it on each push. A caller that measures a
2793 /// batch by the history's length cannot, once the cap holds that length at
2794 /// [`HISTORY_CAP`]; this count keeps rising, so a batch's pushes are the
2795 /// difference of two reads. Not saved to `.edith`, and an undo never rolls
2796 /// it back.
2797 pushes: u64,
2798 /// Which state the project is in, as an id no other state of any project
2799 /// has ([`Project::revision`]). Every edit takes a fresh one and every undo
2800 /// or redo puts back the one its step carries, so a caller that saved at one
2801 /// revision knows whether a later undo has walked back to it.
2802 revision: u64,
2803 /// Set by [`Project::begin_batch`]: while it holds, the first snapshot of the
2804 /// batch is the only one kept, so the batch is one undo step however many edits it makes.
2805 batching: bool,
2806 /// Whether the open batch has pushed its one snapshot yet. An undo or redo clears it,
2807 /// since the state it protects is then not the one the batch started from.
2808 batch_snapped: bool,
2809 /// What the newest step pushed took out of the way, so [`Project::settle`]
2810 /// can put it back should that step turn out to have changed nothing. `None`
2811 /// before any step and after an undo or redo.
2812 pending: Option<PendingStep>,
2813 /// Set by [`Project::hold_history`]: while it holds, a snapshot keeps every step
2814 /// (the history may run past [`HISTORY_CAP`]) so a trial batch that is rolled
2815 /// back takes its own steps off again and drops nothing.
2816 hold_cap: bool,
2817 /// Never rolled back by an undo: an id retired by an undone split must not
2818 /// come back and group two clips that were never together.
2819 next_link: u32,
2820 /// The subtitle tracks this timeline shows, in the order they were added.
2821 /// Saved as a *reference* to the file the cues came out of
2822 /// ([`crate::subtitle`]). In the history snapshots since the widened
2823 /// [`Snapshot`]: a placement names a track by index into this list, so a
2824 /// removal that reindexes the placements can only undo together with the
2825 /// palette it removed the row from.
2826 subtitles: Vec<SubtitleTrack>,
2827 /// The cue overrides: `(track, cue, text)`, the track by its position in
2828 /// `subtitles` and the cue by its position in that track. Saved as `cue`
2829 /// lines ([`crate::edith`]) and in every snapshot, so an undo takes a retype
2830 /// back with the words it changed.
2831 cue_edits: Vec<(usize, usize, String)>,
2832 /// The cues added to a track ([`AddedCue`]), in the order they were added.
2833 /// Each sits in its track's cue list at its own start, and a save writes
2834 /// them as `cueadd` lines. In every snapshot, as the overrides are.
2835 cue_adds: Vec<AddedCue>,
2836 /// The title cards and text overlays, in draw order: sorted by start, and
2837 /// overlaps allowed. In every snapshot, as the subtitle palette is.
2838 titles: Vec<Title>,
2839 chapters: Vec<Chapter>,
2840 /// The comment markers, sorted by frame ([`Marker`]). In every snapshot, as the
2841 /// chapters are.
2842 markers: Vec<Marker>,
2843 /// The project's own settings ([`ProjectSettings`]) -- the canvas, the
2844 /// rate, the proxies switches, the encoder seat, the mix rate, the
2845 /// rendition and the limiter. In every snapshot, so each of them undoes
2846 /// like a lane edit: they are the header of the project's own `.edith`
2847 /// file, not this machine's, and a pick a ctrl+z could not take back
2848 /// would be the one setting with no way out.
2849 settings: ProjectSettings,
2850 /// The sequences ([`sequence`]): the active one is the fields above, the rest are parked here.
2851 seq: Seqs,
2852 /// The library's bins (v51), in creation order. In every snapshot.
2853 bins: Vec<Bin>,
2854 /// The next bin id; never rolled back, so an id is never reused.
2855 bin_next: u32,
2856 /// The next sequence id; never rolled back, so an id is never reused.
2857 seq_next: u32,
2858 /// The expanded copy of the active sequence playback reads ([`Project::render_view`]).
2859 flat: FlatCache,
2860}
2861
2862impl Project {
2863 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
2864 /// grouped -- the state of a freshly opened video, where the timeline is the
2865 /// source. `frame_count` of 0 would break the never-empty invariant, so it
2866 /// is clamped to one frame.
2867 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
2868 let clip = Clip {
2869 speed_keys: Vec::new(),
2870 reversed: false,
2871 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
2872 angle: Default::default(),
2873 fade_in: 0,
2874 fade_out: 0,
2875 transition_out: 0,
2876 transition_kind: Default::default(),
2877 visualizer: 0,
2878 viz_paint: 0,
2879 gain_db: 0.0,
2880 gain_keys: Vec::new(),
2881 pan: 0,
2882 pitch: 0,
2883 transform_keys: Vec::new(),
2884 opacity_keys: Vec::new(),
2885 color_keys: Vec::new(),
2886 effects: Vec::new(),
2887 start: 0,
2888 in_frame: 0,
2889 out_frame: frame_count.max(1),
2890 source: 0,
2891 link: Some(0),
2892 eq: None,
2893 color: None,
2894 transform: None,
2895 fit: FitPolicy::default(),
2896 speed: Speed::NORMAL,
2897 };
2898 Self {
2899 // A file is opened on its first audio stream: nothing has picked
2900 // one yet, and every file with audio at all has that one.
2901 sources: vec![Source::new(path, 0)],
2902 lanes: LaneData::two_lanes(vec![clip.clone()], vec![clip]),
2903 eq: Vec::new(),
2904 color: Vec::new(),
2905 transform: Vec::new(),
2906 history: Vec::new(),
2907 redo: Vec::new(),
2908 pushes: 0,
2909 revision: next_revision(),
2910 batching: false,
2911 batch_snapped: false,
2912 pending: None,
2913 hold_cap: false,
2914 next_link: 1,
2915 subtitles: Vec::new(),
2916 cue_edits: Vec::new(),
2917 cue_adds: Vec::new(),
2918 titles: Vec::new(),
2919 chapters: Vec::new(),
2920 markers: Vec::new(),
2921 settings: ProjectSettings::placeholder(),
2922 seq: Seqs::single(),
2923 bins: Vec::new(),
2924 bin_next: 1,
2925 seq_next: 1,
2926 flat: FlatCache::default(),
2927 }
2928 }
2929
2930 /// A project rebuilt from a saved edit list -- the load half of
2931 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
2932 /// an `ord` is a lane's position among the lanes of that kind, exactly as
2933 /// [`Project::lanes`] hands them back. History is *not* saved, so
2934 /// [`Project::undo`] is `false` until the first edit of the new session.
2935 /// This is the one door untrusted parts come in through, so every invariant
2936 /// every other constructor keeps is checked here, by name and in release:
2937 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
2938 /// or a colour) that is not there, a clip whose end overflows, a lane that is
2939 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
2940 /// below.
2941 ///
2942 /// A project whose lanes are all *empty* is not among them: an emptied
2943 /// timeline is a project like any other -- it plays black and silent, it
2944 /// saves, and it loads back. What a project cannot be is laneless, because
2945 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
2946 /// handle indexes into.
2947 pub fn from_parts(
2948 sources: Vec<Source>,
2949 lanes: Vec<(LaneKind, Vec<Clip>)>,
2950 eq: Vec<EqParams>,
2951 color: Vec<ColorParams>,
2952 transform: Vec<TransformParams>,
2953 ) -> crate::Result<Self> {
2954 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
2955 return Err(format!("eq {bad} holds a band that is not a finite number").into());
2956 }
2957 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
2958 return Err(format!("color {bad} holds a value that is not a finite number").into());
2959 }
2960 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
2961 return Err(format!(
2962 "transform {bad} holds a value that is not a finite number in its range"
2963 )
2964 .into());
2965 }
2966 if lanes.is_empty() {
2967 return Err("no lanes at all: that is not a project".into());
2968 }
2969 let lanes: Vec<LaneData> = lanes
2970 .into_iter()
2971 .map(|(kind, clips)| LaneData::new(kind, clips))
2972 .collect();
2973 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
2974 let name = lane.label();
2975 // A subtitle lane carries words and never a picture
2976 // ([`LaneKind::Subtitle`]); a file that puts one there names a
2977 // source on a lane that has nothing to play it with, and every
2978 // media path below would then read a clip off a lane it does not
2979 // know about.
2980 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
2981 return Err(format!(
2982 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
2983 data.clips.len()
2984 )
2985 .into());
2986 }
2987 for c in &data.clips {
2988 // The setters' own rules, which the file loader enforces too: a
2989 // picture has no volume of its own and only a picture is placed
2990 // by keys, and a clip gain outside its range is refused on the way
2991 // back in. A clip that breaks one would save a file that will not
2992 // load.
2993 if data.kind == LaneKind::Video && c.gain_db != 0.0 {
2994 return Err(format!(
2995 "{name} clip at {} has a gain: a picture has no volume of its own",
2996 c.start
2997 )
2998 .into());
2999 }
3000 if data.kind == LaneKind::Audio && !(c.opacity_keys.is_empty() && c.color_keys.is_empty()) {
3001 return Err(format!(
3002 "{name} clip at {} has opacity or colour keys: only a picture is animated by them",
3003 c.start
3004 )
3005 .into());
3006 }
3007 if data.kind == LaneKind::Audio && !c.transform_keys.is_empty() {
3008 return Err(format!(
3009 "{name} clip at {} has placement keys: only a picture is placed by them",
3010 c.start
3011 )
3012 .into());
3013 }
3014 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&c.gain_db) {
3015 return Err(format!(
3016 "{name} clip at {} has a gain of {} dB, outside its range",
3017 c.start, c.gain_db
3018 )
3019 .into());
3020 }
3021 if c.out_frame <= c.in_frame {
3022 return Err(format!(
3023 "{name} clip at {} plays the empty range [{}, {})",
3024 c.start, c.in_frame, c.out_frame
3025 )
3026 .into());
3027 }
3028 if c.source >= sources.len() && !is_sequence_source(c.source) {
3029 return Err(format!(
3030 "{name} clip at {} names source {} of {}",
3031 c.start,
3032 c.source,
3033 sources.len()
3034 )
3035 .into());
3036 }
3037 if c.start.checked_add(c.frames()).is_none() {
3038 return Err(format!(
3039 "{name} clip at {} runs past the last frame there is",
3040 c.start
3041 )
3042 .into());
3043 }
3044 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
3045 return Err(format!(
3046 "{name} clip at {} names eq {} of {}",
3047 c.start,
3048 c.eq.unwrap_or_default(),
3049 eq.len()
3050 )
3051 .into());
3052 }
3053 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
3054 return Err(format!(
3055 "{name} clip at {} names color {} of {}",
3056 c.start,
3057 c.color.unwrap_or_default(),
3058 color.len()
3059 )
3060 .into());
3061 }
3062 if c.transform
3063 .is_some_and(|i| usize::from(i) >= transform.len())
3064 {
3065 return Err(format!(
3066 "{name} clip at {} names transform {} of {}",
3067 c.start,
3068 c.transform.unwrap_or_default(),
3069 transform.len()
3070 )
3071 .into());
3072 }
3073 }
3074 if !sorted_disjoint(&data.clips) {
3075 return Err(format!("the {name} lane is out of order or overlaps itself").into());
3076 }
3077 }
3078 links_are_consistent(&lanes)?;
3079 // The counter sits past every id the file names, on either of a lane's
3080 // lists: a v16 caption may carry the highest link there is, and a
3081 // re-issued id would silently group it with the next placement that
3082 // asks for one -- the loader refusing a save the editor just wrote.
3083 let next_link = lanes
3084 .iter()
3085 .flat_map(|l| {
3086 let clips = l.clips.iter().filter_map(|c| c.link);
3087 let subs = l.subs.iter().filter_map(|s| s.link);
3088 clips.chain(subs)
3089 })
3090 .max()
3091 // Saturating so a crafted file cannot make the counter wrap: at the
3092 // ceiling ids stop being fresh, which loses grouping, not memory.
3093 .map_or(0, |m| m.saturating_add(1));
3094 Ok(Self {
3095 sources: sources
3096 .iter()
3097 .map(|s| Source { fav: s.fav, bin: s.bin, ..Source::new(&s.path, s.audio_stream) })
3098 .collect(),
3099 lanes,
3100 eq,
3101 color,
3102 transform,
3103 history: Vec::new(),
3104 redo: Vec::new(),
3105 pushes: 0,
3106 revision: next_revision(),
3107 batching: false,
3108 batch_snapped: false,
3109 pending: None,
3110 hold_cap: false,
3111 next_link,
3112 subtitles: Vec::new(),
3113 cue_edits: Vec::new(),
3114 cue_adds: Vec::new(),
3115 titles: Vec::new(),
3116 chapters: Vec::new(),
3117 markers: Vec::new(),
3118 settings: ProjectSettings::placeholder(),
3119 seq: Seqs::single(),
3120 bins: Vec::new(),
3121 bin_next: 1,
3122 seq_next: 1,
3123 flat: FlatCache::default(),
3124 })
3125 }
3126
3127 /// The first video lane -- what an export renders and what a single-lane
3128 /// caller still means by "the clips".
3129 pub fn clips(&self) -> &[Clip] {
3130 self.lane(Lane::V1)
3131 }
3132
3133 /// The clips of `lane`, or nothing at all for a lane that is not there.
3134 pub fn lane(&self, lane: Lane) -> &[Clip] {
3135 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
3136 }
3137
3138 /// Shortens every clip whose out-point runs past its source's wall: `picture` is
3139 /// the wall of a video lane's clip and `sound` of an audio lane's, per source (the
3140 /// tables a playback session holds each lane to). Each lane is held to its own
3141 /// wall, as the load check holds it. Returns what was shortened, so a save can say
3142 /// so. Sequence sources and walls of zero are left alone.
3143 pub fn clamp_to_walls(&mut self, picture: &[u32], sound: &[u32]) -> Vec<WallClamp> {
3144 let wall = |kind: LaneKind, source: usize| -> Option<u32> {
3145 let table = if kind == LaneKind::Audio { sound } else { picture };
3146 table.get(source).copied().filter(|&w| w > 0)
3147 };
3148 let mut clamps = Vec::new();
3149 for (lane, data) in handles(&self.lanes).into_iter().zip(self.lanes.iter_mut()) {
3150 for c in data.clips.iter_mut().filter(|c| !is_sequence_source(c.source)) {
3151 let Some(cap) = wall(data.kind, c.source) else { continue };
3152 if c.out_frame > cap {
3153 clamps.push(WallClamp { lane, source: c.source, from: c.out_frame, to: cap });
3154 c.out_frame = cap;
3155 }
3156 }
3157 }
3158 clamps
3159 }
3160
3161 /// Every lane's handle, in display order -- what a walk over "all lanes"
3162 /// iterates, and what a front-end lays out top to bottom.
3163 pub fn lanes(&self) -> Vec<Lane> {
3164 handles(&self.lanes)
3165 }
3166
3167 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
3168 /// for every `ord` below it, and none at or above it.
3169 pub fn lane_count(&self, kind: LaneKind) -> usize {
3170 self.lanes.iter().filter(|l| l.kind == kind).count()
3171 }
3172
3173 /// Appends an empty lane of `kind` and hands back its handle. One undo
3174 /// step, because the lane list is state a front-end shows: an added lane
3175 /// that could not be taken back would be the one edit with no way out.
3176 /// Nothing plays differently until something is placed on it.
3177 ///
3178 /// An empty lane is a lane like any other -- so is a whole project of them
3179 /// ([`Project::from_parts`]); nothing plays until something is placed.
3180 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
3181 self.snapshot();
3182 self.lanes.push(LaneData::new(kind, Vec::new()));
3183 Lane::new(kind, self.lane_count(kind) - 1)
3184 }
3185
3186 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
3187 /// one undo step like it, which restores the lane where it stood.
3188 ///
3189 /// Refused, changing nothing, while the lane holds anything: the refusal
3190 /// names the clips (file and first frame), because a track removal that
3191 /// deleted takes with it would be the one edit nobody sees coming. Refused
3192 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
3193 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
3194 /// kind and *skips* a kind that is not there), so a project without one
3195 /// would swallow half of every file dropped on it, silently.
3196 ///
3197 /// The lanes below it move up one `ord`, so a handle a caller was holding
3198 /// (a selection, an open card) names the lane after it from here on -- the
3199 /// one thing a front-end owes this call.
3200 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
3201 let Some(i) = self.index(lane) else {
3202 return Err(format!("there is no {} to remove", lane.label()).into());
3203 };
3204 // A subtitle lane is not in that rule: nothing lands on one by itself
3205 // -- a project starts without any and one is added when a caption is --
3206 // so the last of them comes off like any other empty track.
3207 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
3208 return Err(format!(
3209 "{} is the only {} track: every import lands on it",
3210 lane.label(),
3211 match lane.kind {
3212 LaneKind::Video => "video",
3213 LaneKind::Audio => "audio",
3214 // Unreachable while the guard above lets the last subtitle
3215 // lane go, and its own word here so the sentence stays true
3216 // if that rule is ever relaxed.
3217 LaneKind::Subtitle => "subtitle",
3218 }
3219 )
3220 .into());
3221 }
3222 if !self.lanes[i].subs.is_empty() {
3223 // Three names and a count, exactly as the clips below get: the way
3224 // out of the refusal is the drag, so the words say so.
3225 let named: Vec<String> = self.lanes[i]
3226 .subs
3227 .iter()
3228 .take(3)
3229 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
3230 .collect();
3231 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
3232 0 => String::new(),
3233 n => format!(" and {n} more"),
3234 };
3235 return Err(format!(
3236 "{} still holds {}{rest}: delete those captions (or drag them to \
3237 another track) first",
3238 lane.label(),
3239 named.join(", ")
3240 )
3241 .into());
3242 }
3243 let clips = &self.lanes[i].clips;
3244 if !clips.is_empty() {
3245 // Three names and a count: a lane can hold forty clips and a
3246 // refusal nobody reads to the end says nothing at all.
3247 let named: Vec<String> = clips
3248 .iter()
3249 .take(3)
3250 .map(|c| {
3251 let name = self.sources.get(c.source).map_or_else(
3252 || format!("source {}", c.source),
3253 |s| s.path.display().to_string(),
3254 );
3255 format!("{name} at frame {}", c.start)
3256 })
3257 .collect();
3258 let rest = match clips.len().saturating_sub(named.len()) {
3259 0 => String::new(),
3260 n => format!(" and {n} more"),
3261 };
3262 return Err(format!(
3263 "{} still holds {}{rest}: delete those clips (or drag them to \
3264 another track) first",
3265 lane.label(),
3266 named.join(", ")
3267 )
3268 .into());
3269 }
3270 self.snapshot();
3271 self.lanes.remove(i);
3272 Ok(())
3273 }
3274
3275 /// Moves `lane` to display position `to` -- an index into
3276 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
3277 /// the handle it answers to from now on. `None`, changing nothing and
3278 /// snapshotting nothing, for a lane that is not there, a position that is
3279 /// not, and a lane already standing in it.
3280 ///
3281 /// The whole track travels: its clips, its gain, its kind. Nothing is
3282 /// remapped, so no take changes lane and no group is broken -- this is the
3283 /// *order* of the lanes and nothing else, which is why one call is one undo
3284 /// step like an add or a removal.
3285 ///
3286 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
3287 /// last video lane covering a frame, so moving one video lane past another
3288 /// changes which picture wins, in the preview and in an export alike. The
3289 /// audio lanes are summed and their sum does not care about order, so an
3290 /// audio track moved among the video ones is a rearrangement of the screen
3291 /// alone.
3292 ///
3293 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
3294 /// position among the lanes of that kind), so a lane that crosses one of
3295 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
3296 /// `V1`, clips and all -- while one that crosses only lanes of the other
3297 /// kind keeps its name. That is the returned handle: unchanged means every
3298 /// handle a caller holds still names the track it named before.
3299 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
3300 let i = self.index(lane)?;
3301 if to >= self.lanes.len() || to == i {
3302 return None;
3303 }
3304 self.snapshot();
3305 let data = self.lanes.remove(i);
3306 self.lanes.insert(to, data);
3307 Some(handles(&self.lanes)[to])
3308 }
3309
3310 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
3311 /// not there. The one place a handle becomes a position.
3312 fn index(&self, lane: Lane) -> Option<usize> {
3313 self.lanes
3314 .iter()
3315 .enumerate()
3316 .filter(|(_, l)| l.kind == lane.kind)
3317 .map(|(i, _)| i)
3318 .nth(lane.ord)
3319 }
3320
3321 /// For an export of `range` only: drops the clips that lie wholly outside it and read a file
3322 /// `present` says is not there, so a range that never touches a missing source can be written
3323 /// without opening it. Nothing is dropped when that would shorten the timeline below what the
3324 /// range needs (the length of the file would change). A snapshot's edit, never the project's.
3325 pub fn drop_offline_outside(&mut self, range: (u32, u32), present: impl Fn(&Path) -> bool) {
3326 let gone: Vec<bool> = self.sources.iter().map(|s| !present(&s.path)).collect();
3327 if !gone.iter().any(|g| *g) {
3328 return;
3329 }
3330 let keep_len = self.timeline_frames().min(range.1);
3331 let saved: Vec<Vec<Clip>> = self.lanes.iter().map(|l| l.clips.clone()).collect();
3332 for lane in self.lanes.iter_mut().filter(|l| l.kind != LaneKind::Subtitle) {
3333 lane.clips.retain(|c| {
3334 let outside = c.end() <= range.0 || c.start >= range.1;
3335 !(outside && gone.get(c.source).copied().unwrap_or(false))
3336 });
3337 }
3338 if self.timeline_frames() < keep_len {
3339 for (lane, clips) in self.lanes.iter_mut().zip(saved) {
3340 lane.clips = clips;
3341 }
3342 }
3343 }
3344
3345 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
3346 let i = self.index(lane)?;
3347 Some(&mut self.lanes[i].clips)
3348 }
3349
3350 /// The files the clips index into, in import order; index 0 is the file the
3351 /// project was opened with.
3352 pub fn sources(&self) -> &[Source] {
3353 &self.sources
3354 }
3355
3356 /// Points source `idx` at `path`, a file the caller has already checked is
3357 /// the same material. No clip changes; a source's index is its identity.
3358 /// One undo step, which puts the old path back ([`Snapshot::sources`]); a
3359 /// relink to the path the source already has is no change and no step.
3360 pub fn relink_source(&mut self, idx: usize, path: &Path) -> crate::Result<()> {
3361 let Some(source) = self.sources.get(idx) else {
3362 return Err(format!("there is no source {idx}").into());
3363 };
3364 let to = canonical(path);
3365 if source.path == to {
3366 return Ok(());
3367 }
3368 self.snapshot();
3369 self.sources[idx].path = to;
3370 Ok(())
3371 }
3372
3373 /// Points several sources at new files in one undo step ([`Self::relink_source`] for each,
3374 /// unchecked: the caller has copies of the same material). Sources already there and indexes
3375 /// that name nothing are left alone; no step when nothing moves. Returns how many moved.
3376 pub fn relink_sources(&mut self, pairs: &[(usize, PathBuf)]) -> usize {
3377 let moves: Vec<(usize, PathBuf)> = pairs
3378 .iter()
3379 .filter(|(i, to)| self.sources.get(*i).is_some_and(|s| s.path != canonical(to)))
3380 .map(|(i, to)| (*i, canonical(to)))
3381 .collect();
3382 if moves.is_empty() {
3383 return 0;
3384 }
3385 self.snapshot();
3386 for (i, to) in &moves {
3387 self.sources[*i].path = to.clone();
3388 }
3389 moves.len()
3390 }
3391
3392 /// Takes `other`'s timeline over as one undo step: what this project was
3393 /// before the call is one step back, and it is what a recovery does with an
3394 /// autosave once the saved project is open. The lanes, the subtitle palette,
3395 /// the cue edits and adds, the titles, the chapters, the markers, the settings
3396 /// and the sources all come from `other`. Its clip effect tables (equalizer, colour, transform) are
3397 /// appended to this project's own and its clips re-pointed at them, so the
3398 /// indexes a step in the history holds stay valid; the link counter is raised
3399 /// past `other`'s links, so a new split never reuses one. `false`, with
3400 /// nothing changed, when the appended tables would not fit a clip's `u16`.
3401 pub fn adopt_as_step(&mut self, other: &Project) -> bool {
3402 let fits = |have: usize, add: usize| have + add <= usize::from(u16::MAX);
3403 if !fits(self.eq.len(), other.eq.len())
3404 || !fits(self.color.len(), other.color.len())
3405 || !fits(self.transform.len(), other.transform.len())
3406 {
3407 return false;
3408 }
3409 let (eq_at, color_at, transform_at) = (self.eq.len(), self.color.len(), self.transform.len());
3410 // A `u16` index shifted past the appended table: the fit check above keeps it in range.
3411 let shift = |i: u16, by: usize| (usize::from(i) + by) as u16;
3412 let mut lanes = other.lanes.clone();
3413 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
3414 c.eq = c.eq.map(|i| shift(i, eq_at));
3415 c.color = c.color.map(|i| shift(i, color_at));
3416 c.transform = c.transform.map(|i| shift(i, transform_at));
3417 }
3418 self.snapshot();
3419 self.eq.extend(other.eq.iter().cloned());
3420 self.color.extend(other.color.iter().cloned());
3421 self.transform.extend(other.transform.iter().cloned());
3422 let mut parked = other.seq.parked.clone();
3423 for c in parked.iter_mut().flat_map(|(_, d)| d.lanes.iter_mut()).flat_map(|l| &mut l.clips) {
3424 c.eq = c.eq.map(|i| shift(i, eq_at));
3425 c.color = c.color.map(|i| shift(i, color_at));
3426 c.transform = c.transform.map(|i| shift(i, transform_at));
3427 }
3428 self.seq = Seqs { active: other.seq.active, names: other.seq.names.clone(), parked, mcam: other.seq.mcam.clone(), nested: Vec::new() };
3429 self.seq_next = self.seq_next.max(other.seq_next);
3430 self.flat.clear();
3431 self.lanes = lanes;
3432 self.subtitles = other.subtitles.clone();
3433 self.cue_edits = other.cue_edits.clone();
3434 self.cue_adds = other.cue_adds.clone();
3435 self.titles = other.titles.clone();
3436 // The active sequence's chapters and markers are the other timeline's too: left
3437 // out, a recovery drops them and undo cannot bring them back.
3438 self.chapters = other.chapters.clone();
3439 self.markers = other.markers.clone();
3440 self.settings = other.settings.clone();
3441 self.sources = other.sources.clone();
3442 self.bins = other.bins.clone();
3443 self.bin_next = self.bin_next.max(other.bin_next);
3444 self.next_link = self.next_link.max(other.next_link);
3445 true
3446 }
3447
3448 /// The same list in the `(path, stream)` shape the audio engine indexes
3449 /// into -- [`crate::AudioSession::open_multi_streams`] and
3450 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
3451 /// was placed with is the stream that plays *and* the stream that exports.
3452 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
3453 self.sources
3454 .iter()
3455 .map(|s| (s.path.clone(), s.audio_stream))
3456 .collect()
3457 }
3458
3459 /// Index for `path` played on `audio_stream`, appending it if it is new.
3460 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
3461 /// by two paths imports once and two streams of one file are two sources.
3462 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
3463 /// no history: a source entry alone changes nothing playable.
3464 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
3465 let source = Source::new(path, audio_stream);
3466 match self.sources.iter().position(|s| *s == source) {
3467 Some(idx) => idx,
3468 None => {
3469 self.sources.push(source);
3470 self.sources.len() - 1
3471 }
3472 }
3473 }
3474
3475 /// Append a whole-file clip of `source` to the end of every *media* lane,
3476 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
3477 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
3478 /// come in through [`Project::add_subtitles`], which is the palette.
3479 ///
3480 /// One history snapshot, so an import is one undo step, and undoing it
3481 /// leaves the (harmless) source entry behind, because indexes are forever.
3482 /// Refused for an unknown source index.
3483 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
3484 if source >= self.sources.len() {
3485 return false;
3486 }
3487 self.snapshot();
3488 let start = self.timeline_frames();
3489 let clip = Clip {
3490 speed_keys: Vec::new(),
3491 reversed: false,
3492 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
3493 angle: Default::default(),
3494 fade_in: 0,
3495 fade_out: 0,
3496 transition_out: 0,
3497 transition_kind: Default::default(),
3498 visualizer: 0,
3499 viz_paint: 0,
3500 gain_db: 0.0,
3501 gain_keys: Vec::new(),
3502 pan: 0,
3503 pitch: 0,
3504 transform_keys: Vec::new(),
3505 opacity_keys: Vec::new(),
3506 color_keys: Vec::new(),
3507 effects: Vec::new(),
3508 start,
3509 in_frame: 0,
3510 out_frame: frame_count.max(1),
3511 source,
3512 link: Some(self.new_link()),
3513 eq: None,
3514 color: None,
3515 transform: None,
3516 fit: FitPolicy::default(),
3517 speed: Speed::NORMAL,
3518 };
3519 for data in self
3520 .lanes
3521 .iter_mut()
3522 .filter(|l| l.kind != LaneKind::Subtitle)
3523 {
3524 data.clips.push(clip.clone());
3525 }
3526 true
3527 }
3528
3529 /// Drops a source entry -- the file a library row *is* -- and renumbers
3530 /// every clip that indexed past it, which is why this is more than a
3531 /// `Vec::remove`.
3532 ///
3533 /// Refused, changing nothing, while any clip still plays from it: the
3534 /// refusal names the lanes and how many clips each holds, so a caller can
3535 /// say what has to be deleted first. The *last* entry goes like any other
3536 /// -- a project may name no file at all, which is an empty library over an
3537 /// empty timeline (nothing can play, since a clip would have refused the
3538 /// removal). What a front-end does with that is its own decision: `edith`'s
3539 /// window goes back to the empty state it launches in, and
3540 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
3541 /// refuses to write a project that names nothing, because no such file
3542 /// could be opened again.
3543 ///
3544 /// Every index past `idx` moves down by one, so a caller holding a *raw*
3545 /// source index of its own -- a clipboard, which is the one thing outside
3546 /// this type that does -- has to fix it up or drop it, or a paste plays a
3547 /// different file. [`PlaybackSession::remove_source`] hands back the index
3548 /// that went for exactly that.
3549 ///
3550 /// corner-cut: this retires the undo stack. `history` holds the lanes, the
3551 /// subtitle palette and the project's own settings -- no source list -- so a
3552 /// snapshot older than the removal can name the very source being removed
3553 /// (delete a file's clips, then remove the file) and restoring it would
3554 /// point a clip at an entry that is gone. The upgrade path is snapshotting
3555 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
3556 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
3557 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
3558 /// exists) currently rules out.
3559 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
3560 let Some(source) = self.sources.get(idx) else {
3561 return Err(format!("there is no source {idx} to remove").into());
3562 };
3563 let name = source.path.display().to_string();
3564 let used: Vec<String> = handles(&self.lanes)
3565 .into_iter()
3566 .zip(&self.lanes)
3567 .filter_map(|(lane, data)| {
3568 match data.clips.iter().filter(|c| c.source == idx).count() {
3569 0 => None,
3570 1 => Some(format!("{} (1 clip)", lane.label())),
3571 n => Some(format!("{} ({n} clips)", lane.label())),
3572 }
3573 })
3574 .collect();
3575 if !used.is_empty() {
3576 return Err(format!("{name} still plays on {}", used.join(", ")).into());
3577 }
3578 if let Some((id, _)) = self
3579 .seq
3580 .parked
3581 .iter()
3582 .find(|(_, d)| d.lanes.iter().any(|l| l.clips.iter().any(|c| c.source == idx)))
3583 {
3584 let who = self.sequence_name(*id).unwrap_or("another sequence").to_string();
3585 return Err(format!("{name} still plays in the sequence \"{who}\"").into());
3586 }
3587 self.sources.remove(idx);
3588 let all = self
3589 .lanes
3590 .iter_mut()
3591 .chain(self.seq.parked.iter_mut().flat_map(|(_, d)| d.lanes.iter_mut()));
3592 for c in all.flat_map(|l| &mut l.clips) {
3593 if c.source > idx && !is_sequence_source(c.source) {
3594 c.source -= 1;
3595 }
3596 }
3597 self.flat.clear();
3598 // The redo steps renumber nothing and name the old indexes: they go with the history.
3599 self.history.clear();
3600 self.redo.clear();
3601 Ok(())
3602 }
3603
3604 /// Drops the **last** source, if nothing names it, and leaves the undo
3605 /// history exactly as it was. The narrow door behind a rollback: a source
3606 /// imported by a batch that then failed is the newest entry and nothing on
3607 /// the timeline plays it, so taking it back out renumbers nothing and
3608 /// invalidates no step.
3609 ///
3610 /// Refused, with the source left in place, when it is not the last entry (a
3611 /// removal below it would renumber every index above, which is what
3612 /// [`remove_source`](Project::remove_source) does and why that one clears
3613 /// history), or when a clip plays it or an undo or redo step does. The steps
3614 /// that held the entry past the new end are cut to the list that is left, so
3615 /// no restore brings it back.
3616 pub fn remove_unused_source(&mut self, idx: usize) -> crate::Result<()> {
3617 if idx >= self.sources.len() {
3618 return Err(format!("there is no source {idx} to remove").into());
3619 }
3620 let name = self.sources[idx].path.display().to_string();
3621 if idx + 1 != self.sources.len() {
3622 return Err(format!(
3623 "{name} is not the last source, so removing it would renumber the sources after it"
3624 )
3625 .into());
3626 }
3627 let named = |lanes: &[LaneData]| {
3628 lanes.iter().any(|l| l.clips.iter().any(|c| c.source == idx))
3629 };
3630 let parked = |seq: &Seqs| seq.parked.iter().any(|(_, d)| named(&d.lanes));
3631 if named(&self.lanes)
3632 || parked(&self.seq)
3633 || self.history.iter().any(|s| named(&s.lanes) || parked(&s.seq))
3634 || self.redo.iter().any(|s| named(&s.lanes) || parked(&s.seq))
3635 {
3636 return Err(format!("{name} is still played by a clip or an undo step").into());
3637 }
3638 self.sources.pop();
3639 // The steps that hold the entry past the new end (none of them names it) are cut to the
3640 // list that is left, so an undo does not bring the removed entry back.
3641 for step in self.history.iter_mut().chain(self.redo.iter_mut()) {
3642 step.sources.truncate(idx);
3643 }
3644 Ok(())
3645 }
3646
3647 /// The sources, equalizer and colour tables, and transform table a save
3648 /// writes, with the clips reindexed onto their pruned copies. Every
3649 /// imported source is kept, in session order, so a source's index in the
3650 /// file is the index it had in the session and stays put across save and
3651 /// open. Equalizer, colour and transform entries nothing names are still
3652 /// pruned: an undone `set_eq`/`set_color` leaves a setting nothing plays
3653 /// behind, and those indexes are re-assigned by first use -- lane by lane,
3654 /// in display order -- so the same project always emits the same bytes.
3655 ///
3656 /// Every lane comes out, in display order and with its kind: that is what a
3657 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
3658 /// takes back.
3659 ///
3660 /// The equalizer and colour tables are pruned the same way and for the same
3661 /// reason: an undone [`set_eq`](Project::set_eq) or
3662 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
3663 /// and this is the one moment they can go -- the indexes that survive it are
3664 /// only the ones a clip names.
3665 ///
3666 /// Keeping every source (rather than only the ones a clip names) means an
3667 /// emptied timeline still has the file it is scaffolded from on reopen --
3668 /// the frame rate is written nowhere else -- and a source a clip no longer
3669 /// plays stays a library entry at the index a reload expects. Source 0 is
3670 /// whatever was imported first, which may be a still or a song;
3671 /// `PlaybackSession::open_project` picks its rate and its audio reference by
3672 /// what a source *is*, never by where it sits.
3673 pub fn without_orphan_sources(&self) -> Parts {
3674 // Every source comes out, in session order: an import is not an undo
3675 // step, so a source nothing plays is a deliberate library entry, and
3676 // its index is the one a reload must find it at again.
3677 let sources = self.sources.clone();
3678 let mut moved_eq = vec![None; self.eq.len()];
3679 let mut eq = Vec::new();
3680 let mut moved_color = vec![None; self.color.len()];
3681 let mut color = Vec::new();
3682 let mut moved_transform = vec![None; self.transform.len()];
3683 let mut transform = Vec::new();
3684 let mut lanes = self.lanes.clone();
3685 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
3686 if let Some(old) = c.eq.map(usize::from) {
3687 c.eq = Some(match moved_eq[old] {
3688 Some(new) => new,
3689 None => {
3690 eq.push(self.eq[old].clone());
3691 let new = (eq.len() - 1) as u16;
3692 moved_eq[old] = Some(new);
3693 new
3694 }
3695 });
3696 }
3697 if let Some(old) = c.color.map(usize::from) {
3698 c.color = Some(match moved_color[old] {
3699 Some(new) => new,
3700 None => {
3701 color.push(self.color[old]);
3702 let new = (color.len() - 1) as u16;
3703 moved_color[old] = Some(new);
3704 new
3705 }
3706 });
3707 }
3708 if let Some(old) = c.transform.map(usize::from) {
3709 c.transform = Some(match moved_transform[old] {
3710 Some(new) => new,
3711 None => {
3712 transform.push(self.transform[old]);
3713 let new = (transform.len() - 1) as u16;
3714 moved_transform[old] = Some(new);
3715 new
3716 }
3717 });
3718 }
3719 }
3720 (
3721 sources,
3722 // Every lane, subtitle ones included: they hold no [`Clip`], so what
3723 // comes out for one is an empty list, and its *place* in the display
3724 // order is what a save writes it for. What is on it travels beside
3725 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
3726 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
3727 eq,
3728 color,
3729 transform,
3730 )
3731 }
3732
3733 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
3734 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
3735 /// track moves by it, which is what makes it a different control from a
3736 /// clip's equalizer (one frequency range of one take) and from the master
3737 /// volume (what this machine monitors at, which no file carries).
3738 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
3739 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
3740 }
3741
3742 /// The first auto-duck on `lane`, if it has one: the one
3743 /// [`lane_duck_list`](Project::lane_duck_list) starts with. `None` for a lane
3744 /// without one and for a lane that is not there. A lane with several ducks
3745 /// has them all in `lane_duck_list`; this names only the first.
3746 pub fn lane_duck(&self, lane: Lane) -> Option<Duck> {
3747 self.lane_duck_list(lane).first().copied()
3748 }
3749
3750 /// Every auto-duck on `lane`, one per key lane, in the order they were set.
3751 /// Empty for a lane without one and for a lane that is not there.
3752 pub fn lane_duck_list(&self, lane: Lane) -> Vec<Duck> {
3753 self.index(lane)
3754 .map_or_else(Vec::new, |i| self.lanes[i].ducks.clone())
3755 }
3756
3757 /// Sets an auto-duck on an audio lane: while the key lane `duck.under` is
3758 /// loud, this lane drops by `depth_db` ([`crate::duck`]). A lane can be
3759 /// ducked under several keys at once: a duck under a key this lane already
3760 /// has replaces that one, and a duck under a new key is added beside the
3761 /// rest. `None` clears every duck on the lane. One undo step, like a volume.
3762 ///
3763 /// `false`, and no history, for a lane that is not an audio lane or is not
3764 /// there, for a key that is not another audio lane of this project (`under`
3765 /// is the key's [`Lane::ord`]), for a number that is not finite, and for a
3766 /// duck already set exactly so. The numbers are clamped as the duck's own
3767 /// ranges clamp them.
3768 pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<Duck>) -> bool {
3769 let Some(i) = self.index(lane) else {
3770 return false;
3771 };
3772 if lane.kind != LaneKind::Audio {
3773 return false;
3774 }
3775 let next = match duck {
3776 Some(d) => {
3777 let Some(d) = d.clamped() else {
3778 return false;
3779 };
3780 let key = Lane::new(LaneKind::Audio, d.under);
3781 if key == lane || self.index(key).is_none() {
3782 return false;
3783 }
3784 let mut ducks = self.lanes[i].ducks.clone();
3785 match ducks.iter_mut().find(|x| x.under == d.under) {
3786 Some(slot) if *slot == d => return false,
3787 Some(slot) => *slot = d,
3788 None => ducks.push(d),
3789 }
3790 ducks
3791 }
3792 None => {
3793 if self.lanes[i].ducks.is_empty() {
3794 return false;
3795 }
3796 Vec::new()
3797 }
3798 };
3799 self.snapshot();
3800 self.lanes[i].ducks = next;
3801 true
3802 }
3803
3804 /// Removes the duck `lane` has under the key `under` (the key's
3805 /// [`Lane::ord`]), leaving its other ducks. One undo step. `false`, and no
3806 /// history, for a lane with no duck under that key.
3807 pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool {
3808 let Some(i) = self.index(lane) else {
3809 return false;
3810 };
3811 if !self.lanes[i].ducks.iter().any(|d| d.under == under) {
3812 return false;
3813 }
3814 self.snapshot();
3815 self.lanes[i].ducks.retain(|d| d.under != under);
3816 true
3817 }
3818
3819 /// The voice processors of `lane` ([`crate::voice`]): all off, and the
3820 /// default, for a lane that has none, is not an audio lane or is not there.
3821 pub fn lane_voice(&self, lane: Lane) -> VoiceFx {
3822 self.index(lane)
3823 .map_or_else(VoiceFx::default, |i| self.lanes[i].voice.clone())
3824 }
3825
3826 /// Sets the voice processors of an audio lane. One undo step. The numbers are
3827 /// clamped to their ranges. `false`, and no history, for a lane that is not an
3828 /// audio lane or is not there, for a number that is not finite, for a noise
3829 /// reduction switched on without a profile to subtract, and for a setting the
3830 /// lane already has.
3831 pub fn set_lane_voice(&mut self, lane: Lane, voice: VoiceFx) -> bool {
3832 let Some(i) = self.index(lane) else {
3833 return false;
3834 };
3835 if lane.kind != LaneKind::Audio {
3836 return false;
3837 }
3838 let Some(voice) = voice.clamped() else {
3839 return false;
3840 };
3841 if voice.nr.on && voice.nr.profile.is_empty() {
3842 return false;
3843 }
3844 if self.lanes[i].voice == voice {
3845 return false;
3846 }
3847 self.snapshot();
3848 self.lanes[i].voice = voice;
3849 true
3850 }
3851
3852 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
3853 /// One undo step like every other edit -- it is in the lane list, so an
3854 /// undo restores it with the rest. `false`, and no history, for a lane that
3855 /// is not there, for a value that is not finite, and for one already set.
3856 ///
3857 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
3858 /// a value nobody reads: words have no loudness, so a slider that appeared
3859 /// to move one would be a control with no effect. (A video lane's gain is
3860 /// meaningless in the same way but is kept settable: it is the pair `A1`
3861 /// carries for a take, and mixing reads it off the audio lane alone.)
3862 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
3863 let Some(i) = self.index(lane) else {
3864 return false;
3865 };
3866 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
3867 return false;
3868 }
3869 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
3870 if self.lanes[i].gain_db == db {
3871 return false;
3872 }
3873 self.snapshot();
3874 self.lanes[i].gain_db = db;
3875 true
3876 }
3877
3878 /// The pan of an audio lane ([`Self::set_lane_pan`]), `0.0` for the middle and for a lane
3879 /// that is not there.
3880 pub fn lane_pan(&self, lane: Lane) -> f32 {
3881 self.index(lane).map_or(0.0, |i| self.lanes[i].pan)
3882 }
3883
3884 /// Give an audio lane this pan, clamped to `-1.0..=1.0`. One undo step; `false` for a lane
3885 /// that is not there or not audio, a value that is not finite, or one already set.
3886 pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool {
3887 let Some(i) = self.index(lane) else {
3888 return false;
3889 };
3890 if !pan.is_finite() || lane.kind != LaneKind::Audio {
3891 return false;
3892 }
3893 let pan = pan.clamp(-1.0, 1.0);
3894 if self.lanes[i].pan == pan {
3895 return false;
3896 }
3897 self.snapshot();
3898 self.lanes[i].pan = pan;
3899 true
3900 }
3901
3902 /// Whether `lane` is hidden: a video lane left out of the picture, or a
3903 /// subtitle lane whose words are left off the screen and the export. `false`
3904 /// for a lane that is not there.
3905 pub fn lane_hidden(&self, lane: Lane) -> bool {
3906 self.index(lane).is_some_and(|i| self.lanes[i].hidden)
3907 }
3908
3909 /// Whether `lane` is muted: an audio lane silenced in the mix
3910 /// ([`audio_gains`](Project::audio_gains) reads it as 0). `false` for a lane
3911 /// that is not there.
3912 pub fn lane_muted(&self, lane: Lane) -> bool {
3913 self.index(lane).is_some_and(|i| self.lanes[i].muted)
3914 }
3915
3916 /// Whether `lane` is locked. The engine does not look at it: an edit to a
3917 /// locked lane is refused by the front-end, which is where the toast that
3918 /// offers Unlock lives.
3919 pub fn lane_locked(&self, lane: Lane) -> bool {
3920 self.index(lane).is_some_and(|i| self.lanes[i].locked)
3921 }
3922
3923 /// The name the user gave `lane`, `None` when it has none (or is not there).
3924 pub fn lane_name(&self, lane: Lane) -> Option<&str> {
3925 self.index(lane).map(|i| self.lanes[i].name.as_str()).filter(|n| !n.is_empty())
3926 }
3927
3928 /// What a header shows for `lane`: its name, else its address (`V1`).
3929 pub fn lane_title(&self, lane: Lane) -> String {
3930 self.lane_name(lane).map_or_else(|| lane.label(), str::to_string)
3931 }
3932
3933 /// Names `lane`; an empty (or all-blank) name clears it. One undo step.
3934 /// `Ok(false)`, and no history, for a lane that is not there or no change.
3935 /// Refused: more than [`MAX_LANE_NAME_CHARS`] characters, control characters.
3936 pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> {
3937 let name = name.trim();
3938 if name.chars().count() > MAX_LANE_NAME_CHARS {
3939 return Err(format!("a lane name is at most {MAX_LANE_NAME_CHARS} characters"));
3940 }
3941 if name.chars().any(char::is_control) {
3942 return Err("a lane name holds no control characters".into());
3943 }
3944 let Some(i) = self.index(lane) else {
3945 return Ok(false);
3946 };
3947 if self.lanes[i].name == name {
3948 return Ok(false);
3949 }
3950 self.snapshot();
3951 self.lanes[i].name = name.to_string();
3952 Ok(true)
3953 }
3954
3955 /// Every lane's name (empty for none), in display order and in step with
3956 /// [`lane_gains`](Project::lane_gains) -- what a save writes.
3957 pub fn lane_names(&self) -> Vec<String> {
3958 self.lanes.iter().map(|l| l.name.clone()).collect()
3959 }
3960
3961 /// The names a *load* puts back, with no undo step (as
3962 /// [`with_voices`](Project::with_voices)).
3963 pub fn with_lane_names(mut self, names: &[String]) -> Self {
3964 for (data, name) in self.lanes.iter_mut().zip(names) {
3965 data.name = name.clone();
3966 }
3967 self
3968 }
3969
3970 /// Hides or shows a lane. One undo step. `false`, and no history, for a lane
3971 /// that is not there, for one already in that state, and for an audio lane:
3972 /// there is no picture or caption on one to leave out (the mute is its
3973 /// switch), so a hide on it would be a control with no effect.
3974 pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool {
3975 self.set_flag(lane, hidden, |k| k != LaneKind::Audio, |l| &mut l.hidden)
3976 }
3977
3978 /// Mutes or unmutes an audio lane. One undo step. `false`, and no history,
3979 /// for a lane that is not there, for one already in that state, and for any
3980 /// lane but an audio one -- the video lane's sound is never mixed.
3981 pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool {
3982 self.set_flag(lane, muted, |k| k == LaneKind::Audio, |l| &mut l.muted)
3983 }
3984
3985 /// Locks or unlocks a lane. One undo step. `false`, and no history, for a
3986 /// lane that is not there and for one already in that state. The engine
3987 /// accepts edits on a locked lane all the same; see
3988 /// [`lane_locked`](Project::lane_locked).
3989 pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool {
3990 self.set_flag(lane, locked, |_| true, |l| &mut l.locked)
3991 }
3992
3993 /// The one door the three switches go through: refuse what the lane kind
3994 /// cannot have, refuse a no-op, otherwise snapshot and set.
3995 fn set_flag(
3996 &mut self,
3997 lane: Lane,
3998 on: bool,
3999 allowed: fn(LaneKind) -> bool,
4000 field: fn(&mut LaneData) -> &mut bool,
4001 ) -> bool {
4002 let Some(i) = self.index(lane) else {
4003 return false;
4004 };
4005 if !allowed(lane.kind) || *field(&mut self.lanes[i]) == on {
4006 return false;
4007 }
4008 self.snapshot();
4009 *field(&mut self.lanes[i]) = on;
4010 true
4011 }
4012
4013 /// Every lane's switches, in display order and in step with
4014 /// [`lane_gains`](Project::lane_gains) -- what a save writes beside them.
4015 pub fn lane_flags(&self) -> Vec<LaneFlags> {
4016 self.lanes
4017 .iter()
4018 .map(|l| LaneFlags {
4019 hidden: l.hidden,
4020 muted: l.muted,
4021 locked: l.locked,
4022 pan: l.pan,
4023 })
4024 .collect()
4025 }
4026
4027 /// The switches a *load* puts back, beside [`with_mix`](Project::with_mix)
4028 /// and for the same reason: no undo step. A short list leaves the rest
4029 /// clear, which is what a file from before the switches means.
4030 pub fn with_lane_flags(mut self, flags: &[LaneFlags]) -> Self {
4031 for (data, f) in self.lanes.iter_mut().zip(flags) {
4032 data.hidden = f.hidden;
4033 data.muted = f.muted;
4034 data.locked = f.locked;
4035 data.pan = f.pan;
4036 }
4037 self
4038 }
4039
4040 /// Every lane's volume in dB, in display order -- what a save writes,
4041 /// beside the lanes [`Project::without_orphan_sources`] hands back.
4042 ///
4043 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
4044 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
4045 /// one): a save zips the two lists, so a lane that is in one and not the
4046 /// other would hand every track below it the volume of the track above.
4047 pub fn lane_gains(&self) -> Vec<f32> {
4048 self.lanes.iter().map(|l| l.gain_db).collect()
4049 }
4050
4051 /// Every lane's ducks, in step with [`lane_gains`](Project::lane_gains) --
4052 /// what a save writes beside them. Empty for every lane but an audio lane
4053 /// with a duck.
4054 pub fn lane_ducks(&self) -> Vec<Vec<Duck>> {
4055 self.lanes.iter().map(|l| l.ducks.clone()).collect()
4056 }
4057
4058 /// Every lane's voice processors, in step with [`lane_gains`](Project::lane_gains)
4059 /// -- what a save writes beside them.
4060 pub fn lane_voices(&self) -> Vec<VoiceFx> {
4061 self.lanes.iter().map(|l| l.voice.clone()).collect()
4062 }
4063
4064 /// What is placed on every lane, in display order and in step with
4065 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
4066 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
4067 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
4068 ///
4069 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
4070 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
4071 /// clip's source there is no orphan to prune and no index to move.
4072 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
4073 self.lanes.iter().map(|l| l.subs.clone()).collect()
4074 }
4075
4076 /// The placements a *load* puts back, one list per lane in display order --
4077 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
4078 /// same reason. Called *after*
4079 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
4080 /// names.
4081 ///
4082 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
4083 /// like it, by name and in release, because it is the same untrusted file:
4084 /// a placement on a lane that is not a subtitle lane, an empty span or an
4085 /// empty window, a track the palette does not have, a span running past the
4086 /// last frame there is, and a lane that is out of order or overlaps itself
4087 /// ([`place_sub`] refuses every one of those on the live timeline).
4088 ///
4089 /// [`place_sub`]: Project::place_sub
4090 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
4091 let names = handles(&self.lanes);
4092 let palette = self.subtitles.len();
4093 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
4094 let name = lane.label();
4095 if list.is_empty() {
4096 continue;
4097 }
4098 if data.kind != LaneKind::Subtitle {
4099 return Err(format!(
4100 "{name} is not a subtitle track and holds {} caption(s): words go on a \
4101 subtitle track",
4102 list.len()
4103 )
4104 .into());
4105 }
4106 for s in &list {
4107 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
4108 return Err(format!(
4109 "{name} caption at {} is empty: {} frames of [{}, {})",
4110 s.start, s.frames, s.in_us, s.out_us
4111 )
4112 .into());
4113 }
4114 // The width of that window, which the check above cannot see:
4115 // [`edith`](crate::edith) asks the same question at the parse
4116 // and this repeats it, because `with_subs` is the door a
4117 // hand-built `Project` comes through and a caller is not more
4118 // trustworthy than a file.
4119 if s.out_us - s.in_us > MAX_WINDOW_US {
4120 return Err(format!(
4121 "{name} caption at {} is a {}us window, past the {}us a caption can hold",
4122 s.start,
4123 s.out_us - s.in_us,
4124 MAX_WINDOW_US
4125 )
4126 .into());
4127 }
4128 if s.track >= palette {
4129 return Err(format!(
4130 "{name} caption at {} names subtitle track {} of {palette}",
4131 s.start, s.track
4132 )
4133 .into());
4134 }
4135 if s.start.checked_add(s.frames).is_none() {
4136 return Err(format!(
4137 "{name} caption at {} runs past the last frame there is",
4138 s.start
4139 )
4140 .into());
4141 }
4142 }
4143 if !subs_sorted_disjoint(&list) {
4144 return Err(format!("the {name} lane is out of order or overlaps itself").into());
4145 }
4146 data.subs = list;
4147 // The counter also has to clear the ids these captions carry: this
4148 // is the door a load's placements come through, *after*
4149 // [`from_parts`](Project::from_parts) seeded it from the clips, and
4150 // a hand-grouped caption may carry the highest id in the file.
4151 self.next_link = self.next_link.max(
4152 data.subs
4153 .iter()
4154 .filter_map(|s| s.link)
4155 .max()
4156 .map_or(0, |m| m.saturating_add(1)),
4157 );
4158 }
4159 Ok(self)
4160 }
4161
4162 /// The mix settings a *load* puts back: lane volumes in display order (a
4163 /// short list leaves the rest at unity) and the master limiter, both
4164 /// clamped as their setters clamp them.
4165 ///
4166 /// The load's own door, beside [`from_parts`](Project::from_parts): the
4167 /// setters push an undo step, and a project that arrives one undo away from
4168 /// a state it was never in is a project whose first ctrl+z is a surprise.
4169 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
4170 for (data, &db) in self.lanes.iter_mut().zip(gains) {
4171 if db.is_finite() {
4172 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
4173 }
4174 }
4175 self.settings.limiter = limiter.with_ceiling(limiter.ceiling_db);
4176 self
4177 }
4178
4179 /// The ducks a *load* puts back, in display order and beside
4180 /// [`with_mix`](Project::with_mix), with no undo step for the same reason.
4181 /// A short list leaves the rest without one; a duck the file named is
4182 /// already validated by [`crate::edith`].
4183 pub fn with_ducks(mut self, ducks: &[Vec<Duck>]) -> Self {
4184 for (data, lane_ducks) in self.lanes.iter_mut().zip(ducks) {
4185 data.ducks = lane_ducks.clone();
4186 }
4187 self
4188 }
4189
4190 /// The voice processors a *load* puts back, in display order, with no undo
4191 /// step for the reason [`with_mix`](Project::with_mix) gives. A short list
4192 /// leaves the rest with none.
4193 pub fn with_voices(mut self, voices: &[VoiceFx]) -> Self {
4194 for (data, voice) in self.lanes.iter_mut().zip(voices) {
4195 data.voice = voice.clone();
4196 }
4197 self
4198 }
4199
4200 /// The HDR rendition a *load* puts back -- the same door
4201 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
4202 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
4203 self.settings.tone = preset;
4204 self
4205 }
4206
4207 /// The canvas and rate a *load* or a fresh open names -- the project
4208 /// resolution and the rate every clip is counted in. The same door
4209 /// [`with_mix`](Project::with_mix) is, and no undo step for the same
4210 /// reason: a project that arrives one undo away from a state it was never
4211 /// in is a project whose first ctrl+z is a surprise.
4212 pub fn with_canvas(mut self, width: u32, height: u32, frame_rate: f64) -> Self {
4213 self.settings.resolution = (width, height);
4214 self.settings.frame_rate = frame_rate;
4215 self
4216 }
4217
4218 /// The saved switches a *load* puts back: whether the picture is cut on
4219 /// the stand-ins, whether new ones are made on arrival, which encoder an
4220 /// export opens, and the rate the mix was picked to run at. The load half
4221 /// of [`set_proxies`](Project::set_proxies) and its siblings, and no undo
4222 /// step for [`with_mix`](Project::with_mix)'s reason.
4223 pub fn with_switches(
4224 mut self,
4225 proxies: bool,
4226 auto_proxies: bool,
4227 encoder_seat: crate::export::EncoderSeat,
4228 sample_rate: Option<u32>,
4229 ) -> Self {
4230 self.settings.proxies = proxies;
4231 self.settings.auto_proxies = auto_proxies;
4232 self.settings.encoder_seat = encoder_seat;
4233 self.settings.sample_rate = sample_rate;
4234 self
4235 }
4236
4237 /// The word times a *load* puts back, `(track, cue, words)`, after the cue edits and
4238 /// additions have made the cue list they index. No undo step, as [`with_tone`](Project::with_tone).
4239 pub(crate) fn with_cue_words(mut self, rows: &[CueWordRow]) -> Self {
4240 for (track, cue, words) in rows {
4241 if let Some(c) = self.subtitles.get_mut(*track).and_then(|t| t.cues.get_mut(*cue)) {
4242 c.words = words.clone();
4243 }
4244 }
4245 self
4246 }
4247
4248 /// Gives the cues of `track` the word times of `timed`, the cues they were written from:
4249 /// each track cue takes the next timed cue with the same text that starts within a
4250 /// millisecond of it (an SRT keeps milliseconds). A cue none matches keeps none. Not an undo
4251 /// step of its own: it completes the import that made the track.
4252 pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) {
4253 let Some(t) = self.subtitles.get_mut(track) else {
4254 return;
4255 };
4256 let norm = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
4257 let mut from = 0;
4258 for cue in &mut t.cues {
4259 let hit = timed[from..]
4260 .iter()
4261 .position(|w| (w.start_us - cue.start_us).abs() <= 1000 && norm(&w.text) == norm(&cue.text));
4262 if let Some(k) = hit {
4263 cue.words = timed[from + k].words.clone();
4264 from += k + 1;
4265 }
4266 }
4267 }
4268
4269 /// How burned captions animate in this project ([`crate::captionanim`]).
4270 pub fn caption_style(&self) -> crate::captionanim::CaptionStyle {
4271 self.settings.caption_style
4272 }
4273
4274 /// Sets it (clamped). `false` for the style already in force; otherwise one undo step.
4275 pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool {
4276 let style = style.clamped();
4277 if self.settings.caption_style == style {
4278 return false;
4279 }
4280 self.snapshot();
4281 self.settings.caption_style = style;
4282 true
4283 }
4284
4285 /// The caption style a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4286 pub(crate) fn with_caption_style(mut self, style: crate::captionanim::CaptionStyle) -> Self {
4287 self.settings.caption_style = style.clamped();
4288 self
4289 }
4290
4291 /// Which HDR-to-SDR rendition this project is watched and exported in. A
4292 /// project setting, not a clip's: one picture, one look
4293 /// ([`crate::tonemap::Preset`]).
4294 pub fn tone(&self) -> crate::tonemap::Preset {
4295 self.settings.tone
4296 }
4297
4298 /// The project's notes: free text, several lines allowed, empty until one is written.
4299 pub fn notes(&self) -> &str {
4300 &self.settings.notes
4301 }
4302
4303 /// Sets the notes. `false` for the text already in force; otherwise one undo step.
4304 pub fn set_notes(&mut self, notes: &str) -> bool {
4305 if self.settings.notes == notes {
4306 return false;
4307 }
4308 self.snapshot();
4309 self.settings.notes = notes.to_string();
4310 true
4311 }
4312
4313 /// The notes a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4314 pub(crate) fn with_notes(mut self, notes: String) -> Self {
4315 self.settings.notes = notes;
4316 self
4317 }
4318
4319 /// How long a still image is placed for, in seconds: [`STILL_DEFAULT_SECS`] until the
4320 /// project picks another length.
4321 pub fn still_secs(&self) -> f64 {
4322 self.settings.still_secs
4323 }
4324
4325 /// Sets it, clamped to [`STILL_MIN_SECS`]..[`STILL_MAX_SECS`]. `false` for the length already
4326 /// in force; otherwise one undo step. Only stills placed after this change take the new length.
4327 pub fn set_still_secs(&mut self, secs: f64) -> bool {
4328 let secs = if secs.is_finite() { secs.clamp(STILL_MIN_SECS, STILL_MAX_SECS) } else { STILL_DEFAULT_SECS };
4329 if self.settings.still_secs == secs {
4330 return false;
4331 }
4332 self.snapshot();
4333 self.settings.still_secs = secs;
4334 true
4335 }
4336
4337 /// The still length a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4338 pub(crate) fn with_still_secs(mut self, secs: Option<f64>) -> Self {
4339 self.settings.still_secs = secs.map_or(STILL_DEFAULT_SECS, |s| s.clamp(STILL_MIN_SECS, STILL_MAX_SECS));
4340 self
4341 }
4342
4343 /// Sets it. `false` for the one already in force, which is what keeps a
4344 /// re-pick of the current rendition from costing a reseek. One undo step
4345 /// like every other project-setting pick.
4346 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
4347 if self.settings.tone == preset {
4348 return false;
4349 }
4350 self.snapshot();
4351 self.settings.tone = preset;
4352 true
4353 }
4354
4355 /// The subtitle tracks a *load* puts back, in the order they were saved --
4356 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
4357 /// the same reason.
4358 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
4359 self.subtitles = tracks;
4360 self
4361 }
4362
4363 /// The languages a *load* puts back over the palette ([`with_subtitles`](
4364 /// Project::with_subtitles) must come first): `(track, code)` pairs, the
4365 /// track by its position in the palette, as the `sublang` lines name it.
4366 /// No undo step, as with the palette itself. A pair naming no row is
4367 /// ignored; the reader has already refused a line that names one.
4368 pub fn with_sub_langs(mut self, langs: &[(usize, String)]) -> Self {
4369 for (track, code) in langs {
4370 if let Some(t) = self.subtitles.get_mut(*track) {
4371 crate::subtitle::set_language(t, code);
4372 }
4373 }
4374 self
4375 }
4376
4377 /// Names the language of subtitle track `track`: an ISO 639-2 code as
4378 /// [`crate::subtitle::language_code`] gives it, or `und`. One undo step, and
4379 /// `false` (no step) for a track that is not there or already reads that.
4380 /// Kept in the project file (`sublang` lines), and an export writes it as
4381 /// the track's language.
4382 pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool {
4383 match self.subtitles.get(track) {
4384 Some(t) if t.language != code => {}
4385 _ => return false,
4386 }
4387 self.snapshot();
4388 crate::subtitle::set_language(&mut self.subtitles[track], code);
4389 true
4390 }
4391
4392 /// The title cards and text overlays, in draw order: sorted by start, and
4393 /// where two share a start, in the order they were added.
4394 pub fn titles(&self) -> &[Title] {
4395 &self.titles
4396 }
4397
4398 /// Adds a title and returns its index in [`titles`](Project::titles). It is
4399 /// kept sorted by start, so a title lands after the ones that start no
4400 /// later than it. Overlaps are allowed; the later one draws over the earlier.
4401 ///
4402 /// Refused, changing nothing and taking no undo step, when [`check_title`]
4403 /// refuses the title. A title may start past the last clip: the timeline
4404 /// runs on to cover it, over black where no clip plays.
4405 pub fn add_title(&mut self, title: Title) -> crate::Result<usize> {
4406 check_title(&title)?;
4407 self.snapshot();
4408 let idx = self.titles.partition_point(|t| t.start <= title.start);
4409 self.titles.insert(idx, title);
4410 Ok(idx)
4411 }
4412
4413 /// Replaces the title at `idx` with `title`, then re-sorts the list by start
4414 /// -- so the title may move, and a caller that holds its index looks it up
4415 /// again. `false`, changing nothing, for an index that is not there, a title
4416 /// [`check_title`] refuses, or a title the same as the one it replaces.
4417 pub fn set_title(&mut self, idx: usize, title: Title) -> bool {
4418 if idx >= self.titles.len() || check_title(&title).is_err() || self.titles[idx] == title {
4419 return false;
4420 }
4421 self.snapshot();
4422 self.titles[idx] = title;
4423 self.titles.sort_by_key(|t| t.start);
4424 true
4425 }
4426
4427 /// Takes the title at `idx` off the list. `false`, changing nothing, for an
4428 /// index that is not there.
4429 pub fn remove_title(&mut self, idx: usize) -> bool {
4430 if idx >= self.titles.len() {
4431 return false;
4432 }
4433 self.snapshot();
4434 self.titles.remove(idx);
4435 true
4436 }
4437
4438 /// The frame the last title ends on, or 0 with none: what the timeline
4439 /// runs on to, past its media.
4440 fn title_end(&self) -> u32 {
4441 self.titles.iter().map(Title::end).max().unwrap_or(0)
4442 }
4443
4444 /// The chapter markers, sorted by frame, at most one per frame.
4445 pub fn chapters(&self) -> &[Chapter] {
4446 &self.chapters
4447 }
4448
4449 /// Adds a chapter and returns its index in [`chapters`](Project::chapters).
4450 /// Refused, changing nothing and taking no undo step, when [`check_chapter`]
4451 /// refuses it or another chapter already sits on its frame.
4452 pub fn add_chapter(&mut self, chapter: Chapter) -> crate::Result<usize> {
4453 check_chapter(&chapter)?;
4454 if let Some(other) = self.chapters.iter().find(|c| c.frame == chapter.frame) {
4455 return Err(format!("chapter {:?} already starts at frame {}", other.title, other.frame).into());
4456 }
4457 self.snapshot();
4458 let idx = self.chapters.partition_point(|c| c.frame < chapter.frame);
4459 self.chapters.insert(idx, chapter);
4460 Ok(idx)
4461 }
4462
4463 /// Takes the chapter at `idx` off the list. `false`, changing nothing, for an
4464 /// index that is not there.
4465 pub fn remove_chapter(&mut self, idx: usize) -> bool {
4466 if idx >= self.chapters.len() {
4467 return false;
4468 }
4469 self.snapshot();
4470 self.chapters.remove(idx);
4471 true
4472 }
4473
4474 /// Renames the chapter at `idx`. `false`, changing nothing, for an index that
4475 /// is not there, a name [`check_chapter`] refuses, or the name it already has.
4476 pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool {
4477 let Some(current) = self.chapters.get(idx) else {
4478 return false;
4479 };
4480 let renamed = Chapter { frame: current.frame, title: title.to_string() };
4481 if current.title == title || check_chapter(&renamed).is_err() {
4482 return false;
4483 }
4484 self.snapshot();
4485 self.chapters[idx] = renamed;
4486 true
4487 }
4488
4489 /// Moves the chapter at `idx` to `frame`, and returns its new index. Refused,
4490 /// changing nothing, for an index that is not there or a frame another chapter
4491 /// already holds; a move to the frame it is on is a no-op that takes no step.
4492 pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> {
4493 let Some(current) = self.chapters.get(idx) else {
4494 return Err("no chapter there to move".into());
4495 };
4496 if current.frame == frame {
4497 return Ok(idx);
4498 }
4499 if let Some(other) = self.chapters.iter().find(|c| c.frame == frame) {
4500 return Err(format!("chapter {:?} already starts at frame {frame}", other.title).into());
4501 }
4502 self.snapshot();
4503 let mut chapter = self.chapters.remove(idx);
4504 chapter.frame = frame;
4505 let at = self.chapters.partition_point(|c| c.frame < frame);
4506 self.chapters.insert(at, chapter);
4507 Ok(at)
4508 }
4509
4510 /// Maps every chapter's frame through `map` in one undo step, for an edit that
4511 /// moves time: a cut, a ripple, a rate change. Two chapters that land on one
4512 /// frame keep the first in the list and drop the other, which is why the
4513 /// count of chapters dropped is returned. `0`, changing nothing and taking no
4514 /// step, when no frame moves.
4515 pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize {
4516 let before = self.chapters.len();
4517 let mut mapped: Vec<Chapter> = self
4518 .chapters
4519 .iter()
4520 .map(|c| Chapter { frame: map(c.frame), title: c.title.clone() })
4521 .collect();
4522 if mapped == self.chapters {
4523 return 0;
4524 }
4525 self.snapshot();
4526 // Stable sort keeps list order among chapters on one frame, so the first
4527 // one written keeps its frame.
4528 mapped.sort_by_key(|c| c.frame);
4529 mapped.dedup_by_key(|c| c.frame);
4530 let dropped = before - mapped.len();
4531 self.chapters = mapped;
4532 dropped
4533 }
4534
4535 /// Sets the whole chapter list at once, for a loader: sorted by frame, a
4536 /// second chapter on a frame dropped. Not an edit, so no undo step.
4537 pub(crate) fn with_chapters(mut self, mut chapters: Vec<Chapter>) -> Self {
4538 chapters.sort_by_key(|c| c.frame);
4539 chapters.dedup_by_key(|c| c.frame);
4540 self.chapters = chapters;
4541 self
4542 }
4543
4544 /// The comment markers, sorted by frame (several may share one).
4545 pub fn markers(&self) -> &[Marker] {
4546 &self.markers
4547 }
4548
4549 /// Adds a marker and returns its index in [`markers`](Project::markers); after any
4550 /// marker already on its frame. Refused, changing nothing and taking no undo step,
4551 /// when [`check_marker`] refuses it.
4552 pub fn add_marker(&mut self, marker: Marker) -> crate::Result<usize> {
4553 check_marker(&marker)?;
4554 self.snapshot();
4555 let idx = self.markers.partition_point(|m| m.frame <= marker.frame);
4556 self.markers.insert(idx, marker);
4557 Ok(idx)
4558 }
4559
4560 /// Takes the marker at `idx` off. `false`, changing nothing, for an index that is not there.
4561 pub fn remove_marker(&mut self, idx: usize) -> bool {
4562 if idx >= self.markers.len() {
4563 return false;
4564 }
4565 self.snapshot();
4566 self.markers.remove(idx);
4567 true
4568 }
4569
4570 /// Replaces the marker at `idx` and returns its new index (it re-sorts when its frame
4571 /// moves). Refused, changing nothing, for an index that is not there, a marker
4572 /// [`check_marker`] refuses, or one equal to what is there.
4573 pub fn set_marker(&mut self, idx: usize, marker: Marker) -> crate::Result<usize> {
4574 let Some(current) = self.markers.get(idx) else {
4575 return Err("no marker there to change".into());
4576 };
4577 check_marker(&marker)?;
4578 if *current == marker {
4579 return Err("the marker is already so".into());
4580 }
4581 self.snapshot();
4582 if self.markers[idx].frame == marker.frame {
4583 self.markers[idx] = marker;
4584 return Ok(idx);
4585 }
4586 self.markers.remove(idx);
4587 let at = self.markers.partition_point(|m| m.frame <= marker.frame);
4588 self.markers.insert(at, marker);
4589 Ok(at)
4590 }
4591
4592 /// Maps every marker's start and end through `map` in one undo step, for an edit that
4593 /// moves time, as [`remap_chapters`](Project::remap_chapters) does. A range keeps at
4594 /// least a point of itself; markers never merge, so none is lost. `false`, changing
4595 /// nothing and taking no step, when nothing moves.
4596 pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool {
4597 let mut mapped: Vec<Marker> = self
4598 .markers
4599 .iter()
4600 .map(|m| {
4601 let frame = map(m.frame);
4602 let length = if m.length == 0 { 0 } else { map(m.end()).saturating_sub(frame) };
4603 Marker { frame, length, ..m.clone() }
4604 })
4605 .collect();
4606 if mapped == self.markers {
4607 return false;
4608 }
4609 self.snapshot();
4610 mapped.sort_by_key(|m| m.frame);
4611 self.markers = mapped;
4612 true
4613 }
4614
4615 /// Sets the whole marker list at once, for a loader: sorted by frame. Not an edit, so no undo step.
4616 pub(crate) fn with_markers(mut self, mut markers: Vec<Marker>) -> Self {
4617 markers.sort_by_key(|m| m.frame);
4618 self.markers = markers;
4619 self
4620 }
4621
4622 /// Sets the whole title list at once, for a loader: the file's own order is
4623 /// kept, sorted by start as [`add_title`](Project::add_title) keeps it. Not an
4624 /// edit, so no undo step.
4625 pub(crate) fn with_titles(mut self, mut titles: Vec<Title>) -> Self {
4626 titles.sort_by_key(|t| t.start);
4627 self.titles = titles;
4628 self
4629 }
4630
4631 /// What this timeline shows over the picture, in the order they were added:
4632 /// what a front-end lists and what a save writes.
4633 pub fn subtitles(&self) -> &[SubtitleTrack] {
4634 &self.subtitles
4635 }
4636
4637 /// Adds a track, unless the very same one -- same file, same track number
4638 /// inside it -- is already on the list. `false` for that repeat: importing
4639 /// the same `.srt` twice is one subtitle track, not two identical ones.
4640 /// Adds every track of an import that is not already on the list, as one undo
4641 /// step: a failed batch that imported a track rolls the import back with it.
4642 /// Returns how many were added (none, and no step, when every one is a repeat).
4643 pub fn add_subtitles_all(&mut self, tracks: &[SubtitleTrack]) -> usize {
4644 let fresh: Vec<&SubtitleTrack> = tracks
4645 .iter()
4646 .filter(|t| !self.subtitles.iter().any(|o| o.path == t.path && o.track == t.track))
4647 .collect();
4648 if fresh.is_empty() {
4649 return 0;
4650 }
4651 self.snapshot();
4652 let n = fresh.len();
4653 self.subtitles.extend(fresh.into_iter().cloned());
4654 n
4655 }
4656
4657 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
4658 if self
4659 .subtitles
4660 .iter()
4661 .any(|t| t.path == track.path && t.track == track.track)
4662 {
4663 return false;
4664 }
4665 self.subtitles.push(track.clone());
4666 true
4667 }
4668
4669 /// Takes the track at `idx` off the list -- what a row's own remove goes
4670 /// through, so whatever an import added can be taken back out. Refused by
4671 /// name for a row this project does not have, rather than a silent no-op:
4672 /// a front-end holding a stale index has picked the wrong row and needs to
4673 /// hear it.
4674 ///
4675 /// Every index past `idx` moves down by one, as [`remove_source`](
4676 /// Project::remove_source)'s do: a caller holding a picked row (an export's
4677 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
4678 /// it, or it names a different track afterwards. The placements on the
4679 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
4680 /// index into this very list, so every one past `idx` is walked down with
4681 /// it here -- the reindex [`remove_source`](Project::remove_source) does
4682 /// for its clips, for its reason.
4683 ///
4684 /// Refused, changing nothing, while anything placed on a subtitle lane
4685 /// plays *this* row: the placement would have to be deleted or retargeted,
4686 /// and either one is an edit nobody asked for. The refusal names the lane
4687 /// and the frame it is at, up to three of them --
4688 /// [`remove_source`](Project::remove_source) refuses the same way for the
4689 /// same silent corruption.
4690 ///
4691 /// One undo step, and the reindex with it: every placement names a track
4692 /// by index into the palette ([`crate::subtitle`]), so a removal that
4693 /// renumbers them can only come back together with the palette it took
4694 /// the row from -- which is what the history entry holds, beside the
4695 /// lanes it also carries ([`Snapshot`]). The inverse, for a caller that
4696 /// wants the file's tracks back, is [`crate::PlaybackSession::import_subtitles`]
4697 /// -- the panel's own door, which reads the subtitles of a file and
4698 /// nothing else.
4699 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
4700 if idx >= self.subtitles.len() {
4701 return Err(format!("there is no subtitle track {idx} to remove").into());
4702 }
4703 let placed: Vec<String> = handles(&self.lanes)
4704 .into_iter()
4705 .zip(&self.lanes)
4706 .flat_map(|(lane, data)| {
4707 data.subs
4708 .iter()
4709 .filter(move |s| s.track == idx)
4710 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
4711 })
4712 .take(3)
4713 .collect();
4714 if !placed.is_empty() {
4715 return Err(format!(
4716 "{} is on the timeline ({}): delete those clips first",
4717 self.track_name(idx),
4718 placed.join(", ")
4719 )
4720 .into());
4721 }
4722 self.snapshot();
4723 self.subtitles.remove(idx);
4724 // The overrides follow their tracks down, as the placements do, and the
4725 // removed row's own go with it: a row added again later is a new read of
4726 // the file, and its words are the file's.
4727 self.cue_edits.retain(|(t, _, _)| *t != idx);
4728 for (t, _, _) in &mut self.cue_edits {
4729 if *t > idx {
4730 *t -= 1;
4731 }
4732 }
4733 self.cue_adds.retain(|a| a.track != idx);
4734 for a in &mut self.cue_adds {
4735 if a.track > idx {
4736 a.track -= 1;
4737 }
4738 }
4739 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
4740 if s.track > idx {
4741 s.track -= 1;
4742 }
4743 }
4744 Ok(())
4745 }
4746
4747 /// What a refusal calls a palette row: the name the panel shows, and the
4748 /// index alone for a row that is not there.
4749 fn track_name(&self, track: usize) -> String {
4750 self.subtitles
4751 .get(track)
4752 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
4753 }
4754
4755 /// The subtitle lanes in display order -- what a front-end lays out and
4756 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
4757 /// [`audio_lanes`](Project::audio_lanes).
4758 pub fn subtitle_lanes(&self) -> Vec<Lane> {
4759 self.lanes()
4760 .into_iter()
4761 .filter(|l| l.kind == LaneKind::Subtitle)
4762 .collect()
4763 }
4764
4765 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
4766 /// for a subtitle track, and empty for every other lane and for one that is
4767 /// not there.
4768 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
4769 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
4770 }
4771
4772 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
4773 /// twin, with one deliberate difference: it **refuses** an overlap instead
4774 /// of overwriting what it lands on.
4775 ///
4776 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
4777 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
4778 /// carries is a *window of a track* and where the hand let go, and the
4779 /// second of those is the argument. So a caller builds the placement once
4780 /// (from the palette row it dragged) and drops it at as many frames as it
4781 /// likes without rewriting the field each time.
4782 ///
4783 /// A picture placed over a picture hides it and the hidden one is still
4784 /// there to drag back out; two captions in one frame are two lines nobody
4785 /// asked to stack, and the words that lost are gone from the screen with
4786 /// nothing to show for it. So the refusal names the placement in the way,
4787 /// and the caller picks another frame or another lane -- which is what a
4788 /// second subtitle lane is for.
4789 ///
4790 /// One undo step on success, and none on any refusal: an empty window or an
4791 /// empty span, a track the palette does not have
4792 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
4793 /// subtitle lane, a span that would run past the last frame there is, and
4794 /// the overlap above.
4795 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
4796 if lane.kind != LaneKind::Subtitle {
4797 return Err(format!(
4798 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
4799 the others",
4800 lane.label()
4801 )
4802 .into());
4803 }
4804 let Some(i) = self.index(lane) else {
4805 return Err(format!("there is no {} to place on", lane.label()).into());
4806 };
4807 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
4808 return Err(format!(
4809 "that placement is empty: {} frames of [{}, {})",
4810 sub.frames, sub.in_us, sub.out_us
4811 )
4812 .into());
4813 }
4814 // The width of that window, which the check above cannot see: the same
4815 // bound the two file doors hold a placement to
4816 // ([`edith`](crate::edith)'s parse and [`with_subs`]), asked here
4817 // because this is the door a *dragged* caption comes through and the
4818 // hand that dragged it builds the `SubClip` itself.
4819 if sub.out_us - sub.in_us > MAX_WINDOW_US {
4820 return Err(format!(
4821 "that placement is a {}us window, past the {}us a caption can hold",
4822 sub.out_us - sub.in_us,
4823 MAX_WINDOW_US
4824 )
4825 .into());
4826 }
4827 if sub.track >= self.subtitles.len() {
4828 return Err(format!(
4829 "it names subtitle track {} of {}",
4830 sub.track,
4831 self.subtitles.len()
4832 )
4833 .into());
4834 }
4835 // The placement belongs to no group, for [`place`]'s reason: a caption
4836 // dragged out of the palette arrives alone, and grouping it with what
4837 // is under it is a hand's decision ([`Project::group_all`]).
4838 let sub = SubClip {
4839 start: at,
4840 link: None,
4841 ..sub
4842 };
4843 if at.checked_add(sub.frames).is_none() {
4844 return Err(
4845 format!("a placement at frame {at} runs past the last frame there is").into(),
4846 );
4847 }
4848 if let Some(other) = self.lanes[i]
4849 .subs
4850 .iter()
4851 .find(|o| o.end() > sub.start && o.start < sub.end())
4852 {
4853 return Err(format!(
4854 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
4855 on another subtitle track",
4856 lane.label(),
4857 other.start,
4858 other.start,
4859 other.end()
4860 )
4861 .into());
4862 }
4863 self.snapshot();
4864 let subs = &mut self.lanes[i].subs;
4865 let idx = subs.partition_point(|o| o.start < sub.start);
4866 subs.insert(idx, sub);
4867 debug_assert!(subs_sorted_disjoint(subs));
4868 Ok(())
4869 }
4870
4871 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
4872 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
4873 /// refused an overlap where that one clamps to it, for
4874 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
4875 /// still and no picture under it that a landing would hide, so "as far as
4876 /// it goes" would silently be a frame nobody named.
4877 ///
4878 /// A caption *in* a group drags the group: one delta for every member --
4879 /// its clips and its other captions -- clamped to the room each of them
4880 /// has, exactly as a clip's drag always has. That is the point of putting
4881 /// a caption in a group: the words go where the picture goes.
4882 ///
4883 /// The window travels untouched: a caption dragged later says the same
4884 /// words later, exactly as a clip dragged later plays the same pictures
4885 /// later.
4886 ///
4887 /// One undo step on success; nothing changed and no step on a refusal --
4888 /// an index that is not there, a lane that is not a subtitle lane or is not
4889 /// there, and (for a caption in no group) an overlap. A drop that changes
4890 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
4891 /// up and put it back has done nothing wrong, and a front-end showing every
4892 /// `Err` would say so.
4893 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
4894 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
4895 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
4896 };
4897 if to.kind != LaneKind::Subtitle {
4898 return Err(format!(
4899 "{} is not a subtitle track: a caption cannot play on it",
4900 to.label()
4901 )
4902 .into());
4903 }
4904 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
4905 return Err(format!("there is no {} to move onto", to.label()).into());
4906 };
4907 if (here, start) == (dest, sub.start) {
4908 // A pick-up-put-back: the drag ended where it began, which is not a
4909 // mistake to name -- `Ok`, and no undo step, because nothing
4910 // changed. A refusal here would toast a hand that did nothing.
4911 return Ok(());
4912 }
4913 if start.checked_add(sub.frames).is_none() {
4914 return Err(
4915 format!("a placement at frame {start} runs past the last frame there is").into(),
4916 );
4917 }
4918 // A grouped caption carries its group, clamped to the room the whole
4919 // group has rather than refused ([`Project::move_room]) -- one drag, one
4920 // delta, one undo step.
4921 let members = self.group_of(from, idx).expect("the subtitle was found");
4922 if !members.alone() {
4923 if members
4924 .subs
4925 .iter()
4926 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
4927 {
4928 return Err(format!(
4929 "a group is one caption per track: {} already carries this group",
4930 to.label()
4931 )
4932 .into());
4933 }
4934 let want = i64::from(start) - i64::from(sub.start);
4935 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start)), None) else {
4936 return Err(format!(
4937 "another placement already covers those frames on {}",
4938 to.label()
4939 )
4940 .into());
4941 };
4942 let delta = want.clamp(lo, hi);
4943 self.snapshot();
4944 for &(l, i) in &members.clips {
4945 let c = &mut self.lanes[l].clips[i];
4946 c.start = (i64::from(c.start) + delta) as u32;
4947 }
4948 for &(l, i) in &members.subs {
4949 let s = &mut self.lanes[l].subs[i];
4950 s.start = (i64::from(s.start) + delta) as u32;
4951 }
4952 let moved = self.lanes[here].subs.remove(idx);
4953 let subs = &mut self.lanes[dest].subs;
4954 let at = subs.partition_point(|o| o.start < moved.start);
4955 subs.insert(at, moved);
4956 debug_assert!(subs_sorted_disjoint(subs));
4957 debug_assert!(
4958 members
4959 .clips
4960 .iter()
4961 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips))
4962 );
4963 return Ok(());
4964 }
4965 let moved = SubClip { start, ..sub };
4966 if let Some(other) = self.lanes[dest]
4967 .subs
4968 .iter()
4969 .enumerate()
4970 .find(|&(j, o)| {
4971 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
4972 })
4973 .map(|(_, o)| *o)
4974 {
4975 return Err(format!(
4976 "the {} subtitle at frame {} already covers [{}, {})",
4977 to.label(),
4978 other.start,
4979 other.start,
4980 other.end()
4981 )
4982 .into());
4983 }
4984 self.snapshot();
4985 self.lanes[here].subs.remove(idx);
4986 let subs = &mut self.lanes[dest].subs;
4987 let at = subs.partition_point(|o| o.start < moved.start);
4988 subs.insert(at, moved);
4989 debug_assert!(subs_sorted_disjoint(subs));
4990 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
4991 Ok(())
4992 }
4993
4994 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
4995 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
4996 /// pulling an edge past what is legal means "as far as it goes".
4997 ///
4998 /// The window follows the edge, in the seconds the frames are worth at
4999 /// `fps`: a head pulled in starts the caption later *in its track* (the
5000 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
5001 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
5002 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
5003 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
5004 /// needed here and nowhere else in this file, because a trim is the only
5005 /// edit that changes a *duration*.
5006 ///
5007 /// The walls: one frame always survives, an edge never crosses the
5008 /// neighbouring subtitle on its own lane, a head never walks back past the
5009 /// track's own start (`in_us` of 0), and a tail never runs past the last
5010 /// cue the track has -- which is the source length a media trim needs a
5011 /// caller's table for, and which this one can simply read.
5012 ///
5013 /// `Err`, with nothing changed and no undo step, for an index that is not
5014 /// there and an unusable `fps`. An edge that ends up where it already was
5015 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
5016 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
5017 /// reason: a drag that stops at a wall is not a mistake to report.
5018 pub fn trim_sub(
5019 &mut self,
5020 lane: Lane,
5021 idx: usize,
5022 edge: Edge,
5023 to: u32,
5024 fps: f64,
5025 ) -> crate::Result<()> {
5026 if !(fps.is_finite() && fps > 0.0) {
5027 return Err(format!("{fps} is not a frame rate to trim against").into());
5028 }
5029 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
5030 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
5031 };
5032 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
5033 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
5034 };
5035 let to = to.clamp(lo, hi);
5036 let at = match edge {
5037 Edge::Start => sub.start,
5038 Edge::End => sub.end(),
5039 };
5040 if to == at {
5041 // The edge is where it was asked to go -- either the hand did not
5042 // move it, or the clamp above stopped it at a wall it was already
5043 // standing against. Both are a drag that changed nothing: `Ok`, no
5044 // undo step, and no toast for a box that simply stopped moving.
5045 return Ok(());
5046 }
5047 self.snapshot();
5048 let members = self.group_of(lane, idx).expect("the subtitle was found");
5049 let i = self.index(lane).expect("the subtitle was found on it");
5050 let s = &mut self.lanes[i].subs[idx];
5051 match edge {
5052 // The words that stay are the words that were there, so the window
5053 // moves with the head -- a trim, not a slip.
5054 Edge::Start => {
5055 // The head moves and the words that stay are the words that
5056 // were there, so `in_us` follows it -- a trim, not a slip.
5057 // Falling `in_us` makes the window *wider* (the ceiling bounds
5058 // a difference), which is the half of this nothing here can
5059 // see: `set_window` is what puts the width back inside.
5060 set_window(
5061 s,
5062 s.in_us
5063 .saturating_add(us_of(i64::from(to) - i64::from(s.start), fps)),
5064 s.out_us,
5065 );
5066 s.frames = s.end() - to;
5067 s.start = to;
5068 }
5069 Edge::End => {
5070 // ...and the tail, for [`set_window`]'s reason: the End room
5071 // is walled at the ceiling, but `set_window` is what holds it
5072 // for every other composer too, including this one when a
5073 // caller hands `trim_sub` a `to` past its own room.
5074 set_window(
5075 s,
5076 s.in_us,
5077 s.out_us
5078 .saturating_add(us_of(i64::from(to) - i64::from(s.end()), fps)),
5079 );
5080 s.frames = to - s.start;
5081 }
5082 }
5083 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5084 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
5085 // A caption in a group drags its group's edge with it, exactly as a
5086 // clip's trim does: one delta, each member clamped to its own room.
5087 // No source table to grow by, which only tightens how far a member may
5088 // follow -- never whether it may.
5089 self.follow_group(
5090 &members,
5091 &(i, idx),
5092 edge,
5093 i64::from(to) - i64::from(at),
5094 SourceWalls::same(&[]),
5095 );
5096 Ok(())
5097 }
5098
5099 /// How far that edge may travel, `(first, last)` timeline frame inclusive
5100 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
5101 /// drawing the box during a drag asks. `None` for an index that is not
5102 /// there.
5103 pub fn trim_sub_room(
5104 &self,
5105 lane: Lane,
5106 idx: usize,
5107 edge: Edge,
5108 fps: f64,
5109 ) -> Option<(u32, u32)> {
5110 let subs = self.sub_lane(lane);
5111 let s = *subs.get(idx)?;
5112 // How many timeline frames a stretch of the track is worth, which is
5113 // what turns its two walls -- its own start, and its last cue -- into
5114 // frames. A rate that is not a rate leaves the window where it is.
5115 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
5116 true => ((us as f64) * fps / 1e6)
5117 .round()
5118 .max(0.0)
5119 .min(f64::from(u32::MAX)) as u32,
5120 false => 0,
5121 };
5122 Some(match edge {
5123 Edge::Start => (
5124 s.start
5125 .saturating_sub(frames_of(s.in_us))
5126 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
5127 s.end() - 1,
5128 ),
5129 Edge::End => {
5130 // Out to the end of the track it reads, and never over the
5131 // subtitle behind it. A track the palette no longer has (or one
5132 // with no cues at all) may not grow, exactly as a source with no
5133 // entry in a media trim's table may not.
5134 let track_end = self
5135 .subtitles
5136 .get(s.track)
5137 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
5138 .unwrap_or(s.out_us);
5139 // ...and never past [`grow_window`]'s ceiling, which is the
5140 // wall that matters here: a front-end asks this to draw the
5141 // drag, then trims to whatever it is told. An engine that
5142 // offers room its own trim would refuse is a drag that snaps
5143 // back at the end of the gesture -- so the room stops where
5144 // the window stops, and the two agree by construction.
5145 let wall_us = track_end.min(s.in_us.saturating_add(MAX_WINDOW_US));
5146 (
5147 s.start + 1,
5148 s.start
5149 .saturating_add(frames_of((wall_us - s.in_us).max(1)))
5150 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5151 )
5152 }
5153 })
5154 }
5155
5156 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
5157 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
5158 /// `false` for an index that is not there (which a lane that is not a
5159 /// subtitle lane always is).
5160 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
5161 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
5162 return false;
5163 };
5164 self.snapshot();
5165 self.lanes[i].subs.remove(idx);
5166 true
5167 }
5168
5169 /// Retypes one cue's words: cue `cue` of subtitle track `track`. The words
5170 /// belong to the **track**, not to one placement, so every placement of that
5171 /// track shows the new text -- a subtitle file's line is one line however
5172 /// many times the film plays it, and that is why this is a palette edit and
5173 /// not a placement one.
5174 ///
5175 /// `false`, changing nothing and taking no undo step, for a row or a cue
5176 /// that is not there, for a picture cue (a display set has no words), and
5177 /// for text the cue already has. Empty text is not a blank cue: it deletes
5178 /// the cue ([`delete_cue`](Project::delete_cue)), which is the one way a cue
5179 /// leaves a track. The edit is kept in [`cue_edits`](Project::cue_edits),
5180 /// which a save writes and a reopen puts back over the file's own words
5181 /// ([`with_cue_edits`](Project::with_cue_edits)).
5182 pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool {
5183 if text.is_empty() {
5184 return self.delete_cue(track, cue);
5185 }
5186 let Some(c) = self.subtitles.get(track).and_then(|t| t.cues.get(cue)) else {
5187 return false;
5188 };
5189 if c.image.is_some() || c.text == text {
5190 return false;
5191 }
5192 let added = self.added_index(track, cue);
5193 let orig = if added.is_none() { self.original_cue_index(track, cue) } else { 0 };
5194 self.snapshot();
5195 self.subtitles[track].cues[cue].text = text.to_string();
5196 match added {
5197 Some(i) => self.cue_adds[i].text = text.to_string(),
5198 None => self.record_cue_edit(track, orig, text),
5199 }
5200 true
5201 }
5202
5203 /// Removes one cue from subtitle track `track`, as [`set_cue_text`](Project::set_cue_text)
5204 /// names it. The track is the palette every placement of it shows, so the
5205 /// cue is gone from each of them; no placement moves, since a cue's place is
5206 /// its own time in the file, and the cues after it keep theirs. One undo step.
5207 ///
5208 /// `false` for a track or cue that is not there. A picture cue can go too.
5209 /// The removal is kept in [`cue_edits`](Project::cue_edits) as an empty text
5210 /// on the cue's file index, so a reopen takes the same cue out again.
5211 pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool {
5212 if self.subtitles.get(track).is_none_or(|t| cue >= t.cues.len()) {
5213 return false;
5214 }
5215 self.snapshot();
5216 self.drop_cue(track, cue);
5217 true
5218 }
5219
5220 /// Adds a cue to subtitle track `track`, on the track's own clock: `start_us`
5221 /// to `end_us` in microseconds, with `text` (`\n` between lines). It is kept
5222 /// in the track's cue list at its start, shows in every placement of the
5223 /// track, and is written by a save as a [`AddedCue`]. Returns its index in
5224 /// the track.
5225 ///
5226 /// Refused, changing nothing and taking no undo step, for a track that is
5227 /// not there, empty text, an end that is not after the start, a picture
5228 /// track, and a cue that overlaps one already there -- unless `overwrite`,
5229 /// which removes every overlapped cue first. Both the add and those removals
5230 /// are one undo step.
5231 pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> {
5232 let Some(t) = self.subtitles.get(track) else {
5233 return Err(format!("there is no subtitle track {track}").into());
5234 };
5235 if text.is_empty() {
5236 return Err("a cue needs words: empty text adds no cue".into());
5237 }
5238 if end_us <= start_us {
5239 return Err(format!("a cue must end after it starts ({start_us} µs to {end_us} µs)").into());
5240 }
5241 if t.cues.iter().any(|c| c.image.is_some()) {
5242 return Err(format!("track {track} is pictures, not text: a text cue cannot be added to it").into());
5243 }
5244 let clash: Vec<usize> = t
5245 .cues
5246 .iter()
5247 .enumerate()
5248 .filter(|(_, c)| c.start_us < end_us && start_us < c.end_us)
5249 .map(|(i, _)| i)
5250 .collect();
5251 if let (false, Some(&first)) = (overwrite, clash.first()) {
5252 return Err(format!("track {track} cue {first} overlaps the new cue: pass overwrite to replace it").into());
5253 }
5254 self.snapshot();
5255 // Highest first, so each position still names the cue it named.
5256 for &i in clash.iter().rev() {
5257 self.drop_cue(track, i);
5258 }
5259 let at = self.subtitles[track].cues.partition_point(|c| c.start_us <= start_us);
5260 self.subtitles[track].cues.insert(
5261 at,
5262 crate::subtitle::Cue { start_us, end_us, text: text.to_string(), image: None, words: Vec::new(), karaoke: Vec::new() },
5263 );
5264 self.cue_adds.push(AddedCue { track, start_us, end_us, text: text.to_string() });
5265 Ok(at)
5266 }
5267
5268 /// Divides every text cue of track `track` that straddles `t_us` (on the
5269 /// track's own clock) into two cues at `t_us`, one undo step. Each cue's
5270 /// words are shared out at the word boundary nearest the proportional point
5271 /// ([`split_words`]), so a window edge that falls inside a sentence leaves
5272 /// each side only the words it covers, and a piece with no words is dropped.
5273 ///
5274 /// `false`, changing nothing and taking no undo step, when no cue straddles
5275 /// `t_us`. A picture cue is never split.
5276 pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool {
5277 let straddles = self
5278 .subtitles
5279 .get(track)
5280 .is_some_and(|t| {
5281 t.cues
5282 .iter()
5283 .any(|c| c.image.is_none() && c.start_us < t_us && t_us < c.end_us && split_words(c, t_us).is_some())
5284 });
5285 if !straddles {
5286 return false;
5287 }
5288 self.snapshot();
5289 self.split_cue_raw(track, t_us, false);
5290 true
5291 }
5292
5293 /// The room cue `cue` of track `track` has to move or trim in, on the track's
5294 /// own clock: from the end of the cue before it (or 0) to the start of the cue
5295 /// after it (or the end of time). `None` for a cue that is not there.
5296 pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> {
5297 let t = self.subtitles.get(track)?;
5298 let c = t.cues.get(cue)?;
5299 let lo = cue.checked_sub(1).map_or(0, |p| t.cues[p].end_us.min(c.start_us));
5300 let hi = t.cues.get(cue + 1).map_or(i64::MAX, |n| n.start_us.max(c.end_us));
5301 Some((lo, hi))
5302 }
5303
5304 /// Where timeline time `tl_us` falls on the track's own clock, through the
5305 /// placement on `lane` that shows cue `cue` of `track` (extrapolated when it is
5306 /// outside the cue's shown part). `None` when no placement on `lane` shows it.
5307 pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64, fps: f64) -> Option<i64> {
5308 let s = self.sub_lane_cue_spans(lane, fps).into_iter().find(|s| s.track == track && s.cue == cue)?;
5309 let (shown, window) = ((s.end_us - s.start_us).max(1) as f64, (s.window.1 - s.window.0) as f64);
5310 Some(s.window.0 + ((tl_us - s.start_us) as f64 * window / shown).round() as i64)
5311 }
5312
5313 /// Gives cue `cue` of `track` new times and words, kept the way a cue add keeps
5314 /// them: an added cue's entry is updated, a file cue is removed as
5315 /// [`drop_cue`](Project::drop_cue) does and re-added with its new times. The cue
5316 /// keeps its place in the track. No undo step of its own.
5317 fn rewrite_cue_raw(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64, text: &str) {
5318 match self.added_index(track, cue) {
5319 Some(i) => {
5320 let a = &mut self.cue_adds[i];
5321 (a.start_us, a.end_us, a.text) = (start_us, end_us, text.to_string());
5322 }
5323 None => {
5324 let orig = self.original_cue_index(track, cue);
5325 self.cue_edits.retain(|(t, c, _)| !(*t == track && *c == orig));
5326 self.cue_edits.push((track, orig, String::new()));
5327 self.cue_adds.push(AddedCue { track, start_us, end_us, text: text.to_string() });
5328 }
5329 }
5330 let c = &mut self.subtitles[track].cues[cue];
5331 (c.start_us, c.end_us, c.text) = (start_us, end_us, text.to_string());
5332 }
5333
5334 /// Moves or trims one cue: new `start_us` and `end_us` on the track's own clock,
5335 /// kept inside its neighbours ([`cue_room`](Project::cue_room)) and at least
5336 /// [`MIN_CUE_US`] long. One undo step. `Ok(false)`, with none, when the times are
5337 /// the cue's own; `Err` for a cue that is not there, a picture cue, or times
5338 /// that break those rules.
5339 pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> {
5340 let Some((lo, hi)) = self.cue_room(track, cue) else {
5341 return Err(format!("track {track} has no cue {cue}").into());
5342 };
5343 let c = &self.subtitles[track].cues[cue];
5344 if c.image.is_some() {
5345 return Err("a picture cue has no times to set".into());
5346 }
5347 if (c.start_us, c.end_us) == (start_us, end_us) {
5348 return Ok(false);
5349 }
5350 if end_us - start_us < MIN_CUE_US {
5351 return Err(format!("a cue is at least {} ms long", MIN_CUE_US / 1000).into());
5352 }
5353 if start_us < lo || end_us > hi {
5354 return Err("the cue would run into its neighbour".into());
5355 }
5356 let text = c.text.clone();
5357 self.snapshot();
5358 self.rewrite_cue_raw(track, cue, start_us, end_us, &text);
5359 Ok(true)
5360 }
5361
5362 /// Joins cue `cue` of `track` with the one after it: one cue from the first's
5363 /// start to the second's end, the words one after the other (a space between),
5364 /// whatever lay between them now inside it. One undo step. `Err`, changing
5365 /// nothing, for a cue with none after it or a picture cue.
5366 pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> {
5367 let Some(t) = self.subtitles.get(track) else {
5368 return Err(format!("there is no subtitle track {track}").into());
5369 };
5370 let (Some(a), Some(b)) = (t.cues.get(cue), t.cues.get(cue + 1)) else {
5371 return Err("there is no cue after it to merge with".into());
5372 };
5373 if a.image.is_some() || b.image.is_some() {
5374 return Err("a picture cue cannot be merged".into());
5375 }
5376 let text = format!("{} {}", a.text.trim_end(), b.text.trim_start());
5377 let (start_us, end_us) = (a.start_us, b.end_us.max(a.end_us));
5378 let (words, karaoke) = (b.words.clone(), b.karaoke.clone());
5379 self.snapshot();
5380 self.drop_cue(track, cue + 1);
5381 self.rewrite_cue_raw(track, cue, start_us, end_us, &text);
5382 let c = &mut self.subtitles[track].cues[cue];
5383 c.words.extend(words);
5384 c.karaoke.extend(karaoke);
5385 Ok(())
5386 }
5387
5388 /// Splits the cues of every subtitle lane in `on` at the window edges a cut
5389 /// at each of `frames` would make: a placement that strictly straddles a
5390 /// frame gets its window's point there ([`SubClip::window_at`]), and each
5391 /// cue crossing that point is divided. No undo step of its own; the caller
5392 /// has taken its snapshot. Called before the lanes move, so the windows are
5393 /// the ones the cut will split.
5394 ///
5395 /// `both_sides` keeps a one-word cue on both sides of a point
5396 /// ([`cut_pieces`]), for a cut: which side the cut leaves in a window is
5397 /// only known after the ripple, so the caller drops the other one with
5398 /// [`drop_unplaced`](Project::drop_unplaced). A split (`false`) keeps the
5399 /// word on one side only. Returns the pieces made, `(track, start_us, end_us)`.
5400 fn split_cues_across(&mut self, on: &[usize], frames: &[u32], both_sides: bool) -> Vec<(usize, i64, i64)> {
5401 let mut points: Vec<(usize, i64)> = Vec::new();
5402 // A placement that both edges of a cut fall inside: its track and the two window points.
5403 let mut spans: Vec<(usize, i64, i64)> = Vec::new();
5404 for &i in on {
5405 for s in &self.lanes[i].subs {
5406 let inside: Vec<i64> = frames
5407 .iter()
5408 .filter(|&&f| s.start < f && f < s.end())
5409 .map(|&f| s.window_at(f))
5410 .collect();
5411 points.extend(inside.iter().map(|&t| (s.track, t)));
5412 if let [a, b] = inside[..] {
5413 spans.push((s.track, a, b));
5414 }
5415 }
5416 }
5417 let mut pieces = Vec::new();
5418 for (track, a, b) in spans {
5419 pieces.extend(self.keep_one_word_outside(track, a, b));
5420 }
5421 for (track, t) in points {
5422 pieces.extend(self.split_cue_raw(track, t, both_sides));
5423 }
5424 pieces
5425 }
5426
5427 /// A cut from `a` to `b` through the middle of a one-word cue: the word is
5428 /// kept on whichever side the cut leaves longer (ties: the side before), and
5429 /// the removed middle and the other side are dropped, as [`split_words`]
5430 /// does for a single edge. A cue with more words is left for
5431 /// [`split_cue_raw`](Project::split_cue_raw) to divide at each edge.
5432 fn keep_one_word_outside(&mut self, track: usize, a: i64, b: i64) -> Vec<(usize, i64, i64)> {
5433 let Some(t) = self.subtitles.get(track) else {
5434 return Vec::new();
5435 };
5436 let crossing: Vec<usize> = t
5437 .cues
5438 .iter()
5439 .enumerate()
5440 .filter(|(_, c)| {
5441 c.image.is_none() && c.start_us < a && b < c.end_us && c.text.split_whitespace().count() == 1
5442 })
5443 .map(|(i, _)| i)
5444 .collect();
5445 let mut pieces = Vec::new();
5446 for &i in crossing.iter().rev() {
5447 let cue = self.subtitles[track].cues[i].clone();
5448 let text = cue.text.trim().to_string();
5449 let (start_us, end_us) = if a - cue.start_us >= cue.end_us - b {
5450 (cue.start_us, a)
5451 } else {
5452 (b, cue.end_us)
5453 };
5454 self.drop_cue(track, i);
5455 self.add_piece(track, start_us, end_us, text);
5456 pieces.push((track, start_us, end_us));
5457 }
5458 pieces
5459 }
5460
5461 /// Puts one piece of a divided cue into `track` at its start time, and keeps
5462 /// it the way a cue add keeps it (an [`AddedCue`]), so a save and a reopen
5463 /// give back the same cues.
5464 fn add_piece(&mut self, track: usize, start_us: i64, end_us: i64, text: String) {
5465 let at = self.subtitles[track].cues.partition_point(|c| c.start_us <= start_us);
5466 self.subtitles[track]
5467 .cues
5468 .insert(at, crate::subtitle::Cue { start_us, end_us, text: text.clone(), image: None, words: Vec::new(), karaoke: Vec::new() });
5469 self.cue_adds.push(AddedCue { track, start_us, end_us, text });
5470 }
5471
5472 /// [`split_cues_at`](Project::split_cues_at) with no snapshot and no check:
5473 /// each cue of `track` straddling `t_us` is replaced by its pieces, cut by
5474 /// [`cut_pieces`] with `both_sides`. The pieces are kept the way a cue add
5475 /// keeps them -- the file's cue is removed as [`drop_cue`](Project::drop_cue)
5476 /// does and each piece is an [`AddedCue`] -- so a save and a reopen give back
5477 /// the same cues. Returns the pieces made, `(track, start_us, end_us)`.
5478 fn split_cue_raw(&mut self, track: usize, t_us: i64, both_sides: bool) -> Vec<(usize, i64, i64)> {
5479 let Some(t) = self.subtitles.get(track) else {
5480 return Vec::new();
5481 };
5482 let crossing: Vec<usize> = t
5483 .cues
5484 .iter()
5485 .enumerate()
5486 .filter(|(_, c)| c.image.is_none() && c.start_us < t_us && t_us < c.end_us)
5487 .map(|(i, _)| i)
5488 .collect();
5489 let mut made = Vec::new();
5490 // Highest first, so each index still names the cue it named.
5491 for &i in crossing.iter().rev() {
5492 let cue = self.subtitles[track].cues[i].clone();
5493 let Some(pieces) = cut_pieces(&cue, t_us, both_sides) else {
5494 continue;
5495 };
5496 self.drop_cue(track, i);
5497 for (start_us, end_us, text) in pieces {
5498 self.add_piece(track, start_us, end_us, text);
5499 made.push((track, start_us, end_us));
5500 }
5501 }
5502 made
5503 }
5504
5505 /// The tracks a cut over the lanes `on` can change the windows of: the
5506 /// tracks their placements show, each once.
5507 fn caption_tracks_on(&self, on: &[usize]) -> Vec<usize> {
5508 let mut tracks: Vec<usize> = on.iter().flat_map(|&i| self.lanes[i].subs.iter().map(|s| s.track)).collect();
5509 tracks.sort_unstable();
5510 tracks.dedup();
5511 tracks
5512 }
5513
5514 /// Every placement window of every lane, as `(track, in_us, out_us)`.
5515 fn windows(&self) -> Vec<(usize, i64, i64)> {
5516 self.lanes
5517 .iter()
5518 .flat_map(|l| l.subs.iter())
5519 .map(|s| (s.track, s.in_us, s.out_us))
5520 .collect()
5521 }
5522
5523 /// The cues of `tracks` that some placement window covers now (overlaps
5524 /// it), as `(track, start_us, end_us)`.
5525 fn placed_cues(&self, tracks: &[usize]) -> Vec<(usize, i64, i64)> {
5526 let windows = self.windows();
5527 let mut out = Vec::new();
5528 for &t in tracks {
5529 let Some(track) = self.subtitles.get(t) else {
5530 continue;
5531 };
5532 for c in &track.cues {
5533 if windows.iter().any(|&(w, a, b)| w == t && c.start_us < b && a < c.end_us) {
5534 out.push((t, c.start_us, c.end_us));
5535 }
5536 }
5537 }
5538 out
5539 }
5540
5541 /// After a cut, drops the track cues it left outside every placement window
5542 /// of their track. A cue is dropped only if it is one the cut touched:
5543 /// `placed` is the cues a window covered before the cut, and `pieces` the
5544 /// ones the cut made ([`split_cues_across`](Project::split_cues_across)). A
5545 /// cue no placement ever covered (a caption placed over a part of its track,
5546 /// say) is not the cut's to remove, so it stays for a later placement.
5547 ///
5548 /// The cut leaves the words it removed, or the side of a divided cue it
5549 /// cut away, outside every window -- those are the orphans this drops. The
5550 /// piece a window still covers stays, with its words.
5551 fn drop_unplaced(&mut self, tracks: &[usize], placed: &[(usize, i64, i64)], pieces: &[(usize, i64, i64)]) {
5552 let windows = self.windows();
5553 for &t in tracks {
5554 let Some(mut i) = self.subtitles.get(t).map(|tr| tr.cues.len()) else {
5555 continue;
5556 };
5557 // Last first, so dropping one leaves the indices before it true.
5558 while i > 0 {
5559 i -= 1;
5560 let Some(c) = self.subtitles.get(t).and_then(|tr| tr.cues.get(i)) else {
5561 continue;
5562 };
5563 let key = (t, c.start_us, c.end_us);
5564 let touched = placed.contains(&key) || pieces.contains(&key);
5565 let covered = windows.iter().any(|&(w, a, b)| w == t && c.start_us < b && a < c.end_us);
5566 if touched && !covered {
5567 self.drop_cue(t, i);
5568 }
5569 }
5570 }
5571 }
5572
5573 /// Takes cue `cue` out of track `track` with no undo step of its own. An
5574 /// added cue leaves the added list; a file cue's removal is kept as an
5575 /// empty override on its file index.
5576 fn drop_cue(&mut self, track: usize, cue: usize) {
5577 match self.added_index(track, cue) {
5578 Some(i) => {
5579 self.cue_adds.remove(i);
5580 }
5581 None => {
5582 let orig = self.original_cue_index(track, cue);
5583 self.cue_edits.retain(|(t, c, _)| !(*t == track && *c == orig));
5584 self.cue_edits.push((track, orig, String::new()));
5585 }
5586 }
5587 self.subtitles[track].cues.remove(cue);
5588 }
5589
5590 /// Which entry of [`cue_adds`](Project::cue_adds) cue `cue` of track `track`
5591 /// is, if it was added rather than read from the file. An added cue is found
5592 /// by its times: no file cue overlaps one, since adding it refused that.
5593 fn added_index(&self, track: usize, cue: usize) -> Option<usize> {
5594 let c = self.subtitles.get(track)?.cues.get(cue)?;
5595 self.cue_adds
5596 .iter()
5597 .position(|a| a.track == track && a.start_us == c.start_us && a.end_us == c.end_us)
5598 }
5599
5600 /// The file's index of cue `cue` of track `track`, which is not an added
5601 /// one. The cue overrides name cues by where the file has them, so a cue
5602 /// after a removed one keeps its index there while its position in the
5603 /// track moves down: this counts the file's cues before `cue` in the track
5604 /// (added ones have no file index), then walks the file past the removed
5605 /// ones to that survivor.
5606 fn original_cue_index(&self, track: usize, cue: usize) -> usize {
5607 let removed: Vec<usize> = self
5608 .cue_edits
5609 .iter()
5610 .filter(|(t, _, text)| *t == track && text.is_empty())
5611 .map(|(_, c, _)| *c)
5612 .collect();
5613 let before = self.subtitles[track]
5614 .cues
5615 .iter()
5616 .take(cue)
5617 .filter(|c| !self.cue_adds.iter().any(|a| a.track == track && a.start_us == c.start_us && a.end_us == c.end_us))
5618 .count();
5619 let (mut orig, mut seen) = (0usize, 0usize);
5620 loop {
5621 if !removed.contains(&orig) {
5622 if seen == before {
5623 return orig;
5624 }
5625 seen += 1;
5626 }
5627 orig += 1;
5628 }
5629 }
5630
5631 /// Keeps one override in the save list, replacing an earlier one for the
5632 /// same cue so a cue is written once however often it was retyped. `cue` is
5633 /// the file's index ([`original_cue_index`](Project::original_cue_index)).
5634 fn record_cue_edit(&mut self, track: usize, cue: usize, text: &str) {
5635 match self
5636 .cue_edits
5637 .iter_mut()
5638 .find(|(t, c, _)| *t == track && *c == cue)
5639 {
5640 Some(edit) => edit.2 = text.to_string(),
5641 None => self.cue_edits.push((track, cue, text.to_string())),
5642 }
5643 }
5644
5645 /// The cue overrides a save writes, `(track, cue, text)` each, the cue by
5646 /// its index in the file it came from; empty text is a cue removed -- see
5647 /// [`set_cue_text`](Project::set_cue_text) and [`delete_cue`](Project::delete_cue).
5648 pub fn cue_edits(&self) -> &[(usize, usize, String)] {
5649 &self.cue_edits
5650 }
5651
5652 /// The cues added to tracks ([`AddedCue`]), in the order they were added: what
5653 /// a save writes after [`cue_edits`](Project::cue_edits).
5654 pub fn cue_adds(&self) -> &[AddedCue] {
5655 &self.cue_adds
5656 }
5657
5658 /// Puts saved added cues back into their tracks, after the file's cues and
5659 /// the overrides ([`with_cue_edits`](Project::with_cue_edits)), each at its
5660 /// start. An added cue naming a track the file no longer has is kept, so a
5661 /// re-save does not lose it, and is not shown.
5662 pub fn with_cue_adds(mut self, adds: &[AddedCue]) -> Self {
5663 for a in adds {
5664 if let Some(t) = self.subtitles.get_mut(a.track) {
5665 let at = t.cues.partition_point(|c| c.start_us <= a.start_us);
5666 t.cues.insert(
5667 at,
5668 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() },
5669 );
5670 }
5671 self.cue_adds.push(a.clone());
5672 }
5673 self
5674 }
5675
5676 /// Puts saved cue overrides back over the tracks a load read -- the door a
5677 /// load uses, like [`with_subtitles`](Project::with_subtitles), and no undo
5678 /// step for the same reason. Retyped words go on first, then the removed
5679 /// cues come out, last index first, so each still names the file's cue. An
5680 /// override naming a track or cue the file no longer has is kept, so a
5681 /// re-save does not lose it, and changes nothing.
5682 pub fn with_cue_edits(mut self, edits: &[(usize, usize, String)]) -> Self {
5683 let mut removed: Vec<(usize, usize)> = Vec::new();
5684 for (track, cue, text) in edits {
5685 if text.is_empty() {
5686 removed.push((*track, *cue));
5687 } else if let Some(c) = self
5688 .subtitles
5689 .get_mut(*track)
5690 .and_then(|t| t.cues.get_mut(*cue))
5691 .filter(|c| c.image.is_none())
5692 {
5693 c.text = text.clone();
5694 }
5695 self.record_cue_edit(*track, *cue, text);
5696 }
5697 removed.sort_unstable_by(|a, b| b.cmp(a));
5698 removed.dedup();
5699 for (track, cue) in removed {
5700 if let Some(t) = self.subtitles.get_mut(track).filter(|t| cue < t.cues.len()) {
5701 t.cues.remove(cue);
5702 }
5703 }
5704 self
5705 }
5706
5707 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
5708 /// window of its track, clipped to that window and shifted to where the
5709 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
5710 /// carried through the picture's spans -- this is its twin for a track that
5711 /// is placed on a lane of its own, and it is what a preview draws and what
5712 /// an export of the lane would write.
5713 ///
5714 /// Cut, not stretched: a cue half inside the window keeps the half that is
5715 /// inside, and a cue wholly outside it is gone -- the same rule the media
5716 /// spans follow. `fps` is the timeline's rate, needed here because a
5717 /// placement's *position* is in frames while its words are in microseconds.
5718 ///
5719 /// Pure and cheap enough to ask per repaint (a walk of the placements and
5720 /// of their cues, no file opened), which is how a front-end asks it.
5721 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
5722 self.sub_lane_cue_spans(lane, fps)
5723 .into_iter()
5724 .filter_map(|s| {
5725 let cue = self.subtitles.get(s.track)?.cues.get(s.cue)?;
5726 Some(SubtitleCue {
5727 start_us: s.start_us,
5728 end_us: s.end_us,
5729 text: cue.text.clone(),
5730 image: cue.image.clone(),
5731 words: crate::subtitle::map_words(&cue.words, s.window, (s.start_us, s.end_us)),
5732 karaoke: crate::subtitle::map_karaoke(&cue.karaoke, s.window, (s.start_us, s.end_us)),
5733 })
5734 })
5735 .collect()
5736 }
5737
5738 /// [`sub_lane_cues`](Project::sub_lane_cues) with the cue each entry is: the
5739 /// same entries in the same order, as `(start_us, end_us, track, cue)`, so a
5740 /// front-end can hit-test a drawn cue and name the words it would edit
5741 /// ([`set_cue_text`](Project::set_cue_text)). Built by the same walk, so the
5742 /// two cannot disagree about which cue is where.
5743 pub fn sub_lane_cue_refs(&self, lane: Lane, fps: f64) -> Vec<(i64, i64, usize, usize)> {
5744 self.sub_lane_cue_spans(lane, fps)
5745 .into_iter()
5746 .map(|s| (s.start_us, s.end_us, s.track, s.cue))
5747 .collect()
5748 }
5749
5750 /// [`sub_lane_cue_refs`](Project::sub_lane_cue_refs) with the stretch of the cue's own clock
5751 /// each entry shows, which is what its words are moved by ([`crate::subtitle::map_words`]).
5752 pub fn sub_lane_cue_spans(&self, lane: Lane, fps: f64) -> Vec<CueSpan> {
5753 // A hidden lane has no cues at all: the screen draws none and the
5754 // export writes no track for it (its empty cue list is what drops it).
5755 if !(fps.is_finite() && fps > 0.0) || self.lane_hidden(lane) {
5756 return Vec::new();
5757 }
5758 let mut out = Vec::new();
5759 for s in self.sub_lane(lane) {
5760 let Some(track) = self.subtitles.get(s.track) else {
5761 // A placement whose track was taken off the palette
5762 // ([`Project::remove_subtitles`]) shows nothing rather than
5763 // showing another track's words.
5764 continue;
5765 };
5766 // Where the placement's own first microsecond lands on the
5767 // timeline, and how many microseconds of timeline one microsecond
5768 // of the window is worth: the placement's own proportion, which a
5769 // group's re-rate changes (the frames compress, the window does
5770 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
5771 // every cue lands where it always did; at 2x the words cross the
5772 // screen in half the time, cue for cue.
5773 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
5774 let onto = |t: i64| {
5775 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
5776 };
5777 for (i, cue) in track.cues.iter().enumerate() {
5778 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
5779 if b <= a {
5780 continue; // wholly outside the window this placement keeps
5781 }
5782 let (from, to) = (onto(a), onto(b));
5783 // Frames the cue keeps on the timeline (the +1 is the microsecond
5784 // rounding gives back).
5785 let kept = ((to - from) as f64 + 1.0) * fps / 1e6;
5786 // Shorter than one timeline frame: a timeline cannot show it. A
5787 // cue a window edge shortened (a cut met it, or a trim) is also
5788 // a sliver under [`CUT_SLIVER_FRAMES`]: the words a cut leaves
5789 // at the very edge of a cue flash past too quickly to read, so
5790 // they are not a cue. A cue short in the file itself keeps the
5791 // one-frame floor, as it always had.
5792 let clipped = a != cue.start_us || b != cue.end_us;
5793 if kept < 1.0 || (clipped && kept < CUT_SLIVER_FRAMES) {
5794 continue;
5795 }
5796 out.push(CueSpan { start_us: from, end_us: to, track: s.track, cue: i, window: (a, b) });
5797 }
5798 }
5799 // The placements come in timeline order, but two lanes' worth (or a
5800 // track whose cues a window reordered) do not.
5801 out.sort_by_key(|c| c.start_us);
5802 out
5803 }
5804
5805 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
5806 /// lanes is multiplied by on its way into the mix: the same lanes in the
5807 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
5808 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
5809 /// the bit-exact path.
5810 ///
5811 /// A muted lane is `0.0`: silence in the same sum, so the mix, the single
5812 /// stream test ([`AudioSession::is_mixed`]) and the export all see the one
5813 /// answer. Its clips and its volume are left as they are.
5814 pub fn audio_gains(&self) -> Vec<f32> {
5815 self.audio_lanes()
5816 .into_iter()
5817 .map(|lane| match self.lane_muted(lane) {
5818 true => 0.0,
5819 false => db_to_linear(self.lane_gain_db(lane)),
5820 })
5821 .collect()
5822 }
5823
5824 /// The ducks, in the same order and as long as
5825 /// [`audio_gains`](Project::audio_gains): what the mixer reads beside the
5826 /// gains. A duck names its key by the key's [`Lane::ord`], which is stable
5827 /// while lanes are emptied and refilled; here it is rewritten to the key's
5828 /// position in the mix, and dropped when that key is not in the mix at all
5829 /// (an empty audio lane is not one), which leaves the lane unducked rather
5830 /// than ducked under silence it could not hear.
5831 pub fn audio_ducks(&self) -> Vec<Vec<Duck>> {
5832 let mixed = self.audio_lanes();
5833 mixed
5834 .iter()
5835 .map(|&lane| {
5836 self.lane_duck_list(lane)
5837 .into_iter()
5838 .filter_map(|duck| {
5839 let key = Lane::new(LaneKind::Audio, duck.under);
5840 let at = mixed.iter().position(|&l| l == key)?;
5841 Some(Duck { under: at, ..duck })
5842 })
5843 .collect()
5844 })
5845 .collect()
5846 }
5847
5848 /// The voice processors, in the same order and as long as
5849 /// [`audio_gains`](Project::audio_gains): what the mix opens each lane
5850 /// through. All off for a project nobody has cleaned, which is the path
5851 /// that decodes the same samples it always did.
5852 pub fn audio_voices(&self) -> Vec<VoiceFx> {
5853 self.audio_lanes()
5854 .into_iter()
5855 .map(|lane| self.lane_voice(lane))
5856 .collect()
5857 }
5858
5859 /// The master limiter the mix is summed through. A project setting, not a
5860 /// clip's and not a lane's: there is one mix.
5861 pub fn limiter(&self) -> Limiter {
5862 self.settings.limiter
5863 }
5864
5865 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
5866 /// for a setting already in force. One undo step like every other
5867 /// project-setting pick.
5868 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
5869 let limiter = limiter.with_ceiling(limiter.ceiling_db);
5870 if self.settings.limiter == limiter {
5871 return false;
5872 }
5873 self.snapshot();
5874 self.settings.limiter = limiter;
5875 true
5876 }
5877
5878 /// What the clip at `idx` of `lane` plays through, or `None` for one that
5879 /// plays flat (and for an index that is not there) -- what a feeder and an
5880 /// export ask before they build an [`crate::eq::EqState`].
5881 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
5882 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
5883 }
5884
5885 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
5886 /// take them off. One undo step, like every other edit. `false` -- and no
5887 /// history -- for an index that is not there and for params holding a value
5888 /// that is not finite, which is the one thing the file format could not
5889 /// write and read back.
5890 ///
5891 /// Settings equal to ones already in the table share their entry, so a
5892 /// project that puts the same curve on twenty clips writes it once.
5893 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
5894 if idx >= self.lane(lane).len() {
5895 return false;
5896 }
5897 let slot = match params {
5898 None => None,
5899 Some(params) => {
5900 if !finite(&params) {
5901 return false;
5902 }
5903 Some(match self.eq.iter().position(|p| *p == params) {
5904 Some(at) => at as u16,
5905 // corner-cut: the table is append-only within a session (see
5906 // the module docs) and `Clip::eq` is a u16, so the 65535th
5907 // *distinct* setting of one session is refused rather than
5908 // silently aliased. Upgrade path if a UI ever drags a slider
5909 // that far: widen `Clip::eq` to u32 (Clip has the room) or
5910 // snapshot the table into the history and compact it here.
5911 None if self.eq.len() >= usize::from(u16::MAX) => return false,
5912 None => {
5913 self.eq.push(params);
5914 (self.eq.len() - 1) as u16
5915 }
5916 })
5917 }
5918 };
5919 self.snapshot();
5920 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
5921 true
5922 }
5923
5924 /// The clip's own gain in dB ([`Clip::gain_db`]) at `idx` of `lane`, or
5925 /// `None` for an index that is not there. `0.0` is unity.
5926 pub fn clip_gain(&self, lane: Lane, idx: usize) -> Option<f32> {
5927 self.lane(lane).get(idx).map(|c| c.gain_db)
5928 }
5929
5930 /// Give the clip at `idx` of `lane` this gain in dB, clamped to
5931 /// [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. One undo step, like every
5932 /// other edit. `false` -- and no history -- for an index that is not there,
5933 /// a value that is not finite, a video lane (a picture has no volume of its
5934 /// own to set: the gain is on the audio clip the take was split into, not
5935 /// relayed to it), or a value already set exactly so.
5936 pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
5937 if lane.kind != LaneKind::Audio || !db.is_finite() {
5938 return false;
5939 }
5940 let Some(current) = self.lane(lane).get(idx).map(|c| c.gain_db) else {
5941 return false;
5942 };
5943 let db = db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
5944 if current == db {
5945 return false;
5946 }
5947 self.snapshot();
5948 self.lane_mut(lane).expect("checked above")[idx].gain_db = db;
5949 true
5950 }
5951
5952 /// The clip's pan ([`Clip::pan`]) at `idx` of `lane`, or `None` for an index that is not there.
5953 pub fn clip_pan(&self, lane: Lane, idx: usize) -> Option<f32> {
5954 self.lane(lane).get(idx).map(Clip::pan_value)
5955 }
5956
5957 /// Give the clip at `idx` of `lane` this pan, clamped to `-1.0..=1.0`. One undo step.
5958 /// `false` -- and no history -- for an index that is not there, a value that is not
5959 /// finite, a non-audio lane, or a value already set.
5960 pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool {
5961 if lane.kind != LaneKind::Audio || !pan.is_finite() {
5962 return false;
5963 }
5964 let Some(current) = self.lane(lane).get(idx).map(|c| c.pan) else {
5965 return false;
5966 };
5967 let pan = (pan.clamp(-1.0, 1.0) * 100.0).round() as i8;
5968 if current == pan {
5969 return false;
5970 }
5971 self.snapshot();
5972 self.lane_mut(lane).expect("checked above")[idx].pan = pan;
5973 true
5974 }
5975
5976 /// Give the clip at `idx` of `lane` this pitch in semitones, clamped to `-12..=12`.
5977 /// One undo step. `false` -- and no history -- for an index that is not there, a
5978 /// non-audio lane, or a value already set.
5979 pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
5980 if lane.kind != LaneKind::Audio {
5981 return false;
5982 }
5983 let Some(current) = self.lane(lane).get(idx).map(|c| c.pitch) else {
5984 return false;
5985 };
5986 let semitones = semitones.clamp(i32::from(MIN_CLIP_PITCH), i32::from(MAX_CLIP_PITCH)) as i8;
5987 if current == semitones {
5988 return false;
5989 }
5990 self.snapshot();
5991 self.lane_mut(lane).expect("checked above")[idx].pitch = semitones;
5992 true
5993 }
5994
5995 /// The pitch in semitones of the clip at `idx` of `lane`, or `None` for an index that
5996 /// is not there.
5997 pub fn clip_pitch(&self, lane: Lane, idx: usize) -> Option<i8> {
5998 self.lane(lane).get(idx).map(|c| c.pitch)
5999 }
6000
6001 /// The placement animation of the clip at `idx` of `lane`, sorted by source
6002 /// frame ([`Clip::transform_keys`]). Empty for no keys and for an index
6003 /// that is not there.
6004 pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[TransformKey] {
6005 self.lane(lane)
6006 .get(idx)
6007 .map_or(&[][..], |c| c.transform_keys.as_slice())
6008 }
6009
6010 /// Replace the whole placement animation of the clip at `idx` of `lane`; an
6011 /// empty list clears it back to [`Clip::transform`]. Sorted here, one undo
6012 /// step. `false` -- and no history -- for an audio lane, an index that is not
6013 /// there, more than [`MAX_TRANSFORM_KEYS`] keys, a key whose placement is not
6014 /// finite, two keys at one source frame, or a list already exactly so. An
6015 /// opacity is clamped to `0..=1`, as [`TransformParams::opacity`] requires.
6016 pub fn set_transform_keys(
6017 &mut self,
6018 lane: Lane,
6019 idx: usize,
6020 mut keys: Vec<TransformKey>,
6021 ) -> bool {
6022 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6023 return false;
6024 }
6025 if keys.iter().any(|k| !transform_finite(&k.params)) {
6026 return false;
6027 }
6028 keys.sort_by_key(|k| k.at);
6029 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6030 return false;
6031 }
6032 for k in &mut keys {
6033 k.params.opacity = k.params.opacity.clamp(0.0, 1.0);
6034 }
6035 let Some(current) = self.lane(lane).get(idx).map(|c| &c.transform_keys) else {
6036 return false;
6037 };
6038 if *current == keys {
6039 return false;
6040 }
6041 self.snapshot();
6042 self.lane_mut(lane).expect("checked above")[idx].transform_keys = keys;
6043 true
6044 }
6045
6046 /// The opacity animation of the clip at `idx` of `lane`, sorted by source
6047 /// frame ([`Clip::opacity_keys`]). Empty for no keys and for an index that
6048 /// is not there.
6049 pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[OpacityKey] {
6050 self.lane(lane)
6051 .get(idx)
6052 .map_or(&[][..], |c| c.opacity_keys.as_slice())
6053 }
6054
6055 /// Replace the whole opacity animation of the clip at `idx` of `lane`; an
6056 /// empty list clears it. Sorted here, one undo step; opacities are clamped to
6057 /// `0..=1`. `false` -- and no history -- for an audio lane, an index that is
6058 /// not there, more than [`MAX_TRANSFORM_KEYS`] keys, a non-finite opacity, two
6059 /// keys at one source frame, or a list already exactly so.
6060 pub fn set_opacity_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<OpacityKey>) -> bool {
6061 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6062 return false;
6063 }
6064 if keys.iter().any(|k| !k.opacity.is_finite()) {
6065 return false;
6066 }
6067 keys.sort_by_key(|k| k.at);
6068 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6069 return false;
6070 }
6071 for k in &mut keys {
6072 k.opacity = k.opacity.clamp(0.0, 1.0);
6073 }
6074 let Some(current) = self.lane(lane).get(idx).map(|c| &c.opacity_keys) else {
6075 return false;
6076 };
6077 if *current == keys {
6078 return false;
6079 }
6080 self.snapshot();
6081 self.lane_mut(lane).expect("checked above")[idx].opacity_keys = keys;
6082 true
6083 }
6084
6085 /// The colour animation of the clip at `idx` of `lane`, sorted by source
6086 /// frame ([`Clip::color_keys`]). Empty for no keys and for an index that is
6087 /// not there.
6088 pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[ColorKey] {
6089 self.lane(lane)
6090 .get(idx)
6091 .map_or(&[][..], |c| c.color_keys.as_slice())
6092 }
6093
6094 /// The effects stack of the clip at `idx` of `lane` ([`Clip::effects`]).
6095 /// Empty for none and for an index that is not there.
6096 pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] {
6097 self.lane(lane).get(idx).map_or(&[], |c| &c.effects)
6098 }
6099
6100 /// Replaces the effects stack of the clip at `idx` of `lane` (an empty list
6101 /// clears it), each effect's values clamped into range. One undo step; `false`
6102 /// for a lane that is not a video lane, a clip that is not there, more than
6103 /// [`crate::effects::MAX_EFFECTS`] effects, and a stack equal to the current one.
6104 pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool {
6105 if lane.kind != LaneKind::Video || effects.len() > crate::effects::MAX_EFFECTS {
6106 return false;
6107 }
6108 let effects: Vec<_> = effects.into_iter().map(crate::effects::Effect::clamped).collect();
6109 let Some(current) = self.lane(lane).get(idx).map(|c| &c.effects) else {
6110 return false;
6111 };
6112 if *current == effects {
6113 return false;
6114 }
6115 self.snapshot();
6116 self.lane_mut(lane).expect("checked above")[idx].effects = effects;
6117 true
6118 }
6119
6120 /// The keys of the effect at stack position `slot` of the clip at `idx` of `lane`
6121 /// ([`crate::effects::Effect::keys`]); empty for an effect with none.
6122 pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] {
6123 self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)).map_or(&[], |e| &e.keys)
6124 }
6125
6126 /// Replaces the keys of the effect at stack position `slot` of the clip at `idx` of
6127 /// `lane`; an empty list clears them. Keys are source-frame keyed and sorted here with
6128 /// no two alike. Each value is clamped into its parameter's range, a parameter that is
6129 /// not keyable (a switch or a choice) takes the effect's static value, and the unused
6130 /// tail is zeroed. Refused for a clip that is not a picture clip on a video lane, more
6131 /// than [`MAX_TRANSFORM_KEYS`] keys, a non-finite value, or a list equal to the current
6132 /// one. One undo step.
6133 pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, mut keys: Vec<crate::effects::EffectKey>) -> bool {
6134 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6135 return false;
6136 }
6137 keys.sort_by_key(|k| k.at);
6138 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6139 return false;
6140 }
6141 let Some(current) = self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)) else {
6142 return false;
6143 };
6144 let specs = current.kind.params();
6145 if keys.iter().any(|k| k.values[..specs.len()].iter().any(|v| !v.is_finite())) {
6146 return false;
6147 }
6148 for k in &mut keys {
6149 for (i, v) in k.values.iter_mut().enumerate() {
6150 *v = match specs.get(i) {
6151 Some(s) if s.keyable() => v.clamp(s.min, s.max),
6152 Some(_) => current.values[i],
6153 None => 0.0,
6154 };
6155 }
6156 }
6157 if current.keys == keys {
6158 return false;
6159 }
6160 self.snapshot();
6161 self.lane_mut(lane).expect("checked above")[idx].effects[slot].keys = keys;
6162 true
6163 }
6164
6165 /// Replace the whole colour animation of the clip at `idx` of `lane`; an
6166 /// empty list clears it. Sorted here, one undo step; each field is clamped to
6167 /// its range (brightness and tint `-1..=1`, contrast and saturation `0..=2`).
6168 /// `false` -- and no history -- for an audio lane, an index that is not there,
6169 /// more than [`MAX_COLOR_KEYS`] keys, a non-finite value, two keys at one
6170 /// source frame, or a list already exactly so.
6171 pub fn set_color_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<ColorKey>) -> bool {
6172 if lane.kind != LaneKind::Video || keys.len() > MAX_COLOR_KEYS {
6173 return false;
6174 }
6175 if keys.iter().any(|k| !color_finite(&k.params)) {
6176 return false;
6177 }
6178 keys.sort_by_key(|k| k.at);
6179 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6180 return false;
6181 }
6182 for k in &mut keys {
6183 let p = &mut k.params;
6184 p.brightness = p.brightness.clamp(-1.0, 1.0);
6185 p.contrast = p.contrast.clamp(0.0, 2.0);
6186 p.saturation = p.saturation.clamp(0.0, 2.0);
6187 p.tint = p.tint.clamp(-1.0, 1.0);
6188 }
6189 let Some(current) = self.lane(lane).get(idx).map(|c| &c.color_keys) else {
6190 return false;
6191 };
6192 if *current == keys {
6193 return false;
6194 }
6195 self.snapshot();
6196 self.lane_mut(lane).expect("checked above")[idx].color_keys = keys;
6197 true
6198 }
6199
6200 /// The source frame the keys of the clip at `idx` of `lane` are read at for
6201 /// timeline `frame`, rounded to the nearest whole frame: where a key set "at
6202 /// the playhead" lands. `None` for an index that is not there, a frame
6203 /// outside the clip and a lane that is not a video lane.
6204 pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> {
6205 let c = self.lane(lane).get(idx)?;
6206 if lane.kind != LaneKind::Video || timeline_frame < c.start || timeline_frame >= c.end() {
6207 return None;
6208 }
6209 Some(key_pos(c, timeline_frame).round() as u32)
6210 }
6211
6212 /// Whether the clip has any key of `kind` at all.
6213 pub fn is_keyed(&self, lane: Lane, idx: usize, kind: KeyKind) -> bool {
6214 self.lane(lane).get(idx).is_some_and(|c| match kind {
6215 KeyKind::Placement => !c.transform_keys.is_empty(),
6216 KeyKind::Opacity => !c.opacity_keys.is_empty(),
6217 KeyKind::Color => !c.color_keys.is_empty(),
6218 })
6219 }
6220
6221 /// The ease of the key of `kind` that sits exactly on timeline `frame`
6222 /// ([`key_source_frame`](Self::key_source_frame)), `None` with no key there.
6223 pub fn key_ease_at(&self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32) -> Option<KeyEase> {
6224 let at = self.key_source_frame(lane, idx, timeline_frame)?;
6225 let c = self.lane(lane).get(idx)?;
6226 match kind {
6227 KeyKind::Placement => c.transform_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6228 KeyKind::Opacity => c.opacity_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6229 KeyKind::Color => c.color_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6230 }
6231 }
6232
6233 /// The stopwatch: puts a key of `kind` on timeline `frame` holding the value the
6234 /// clip shows there (so the picture does not change), or takes the key that is
6235 /// there off. `Some(true)` for a key added, `Some(false)` for one removed, `None`
6236 /// -- and no history -- where no key can go (see
6237 /// [`key_source_frame`](Self::key_source_frame)) or the keys are full. One undo
6238 /// step. Removing the last key puts the clip back on its single value.
6239 pub fn toggle_key(&mut self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32) -> Option<bool> {
6240 let at = self.key_source_frame(lane, idx, timeline_frame)?;
6241 let had = self.key_ease_at(lane, idx, kind, timeline_frame).is_some();
6242 let c = self.lane(lane).get(idx)?.clone();
6243 let ok = match kind {
6244 KeyKind::Placement => {
6245 let mut keys = c.transform_keys.clone();
6246 if had {
6247 keys.retain(|k| k.at != at);
6248 } else {
6249 let params = self.transform_at(lane, idx, timeline_frame).unwrap_or_default();
6250 keys.push(TransformKey { at, params, ease: KeyEase::Linear });
6251 }
6252 self.set_transform_keys(lane, idx, keys)
6253 }
6254 KeyKind::Opacity => {
6255 let mut keys = c.opacity_keys.clone();
6256 if had {
6257 keys.retain(|k| k.at != at);
6258 } else {
6259 let opacity = self.opacity_at(lane, idx, timeline_frame);
6260 keys.push(OpacityKey { at, opacity, ease: KeyEase::Linear });
6261 }
6262 self.set_opacity_keys(lane, idx, keys)
6263 }
6264 KeyKind::Color => {
6265 let mut keys = c.color_keys.clone();
6266 if had {
6267 keys.retain(|k| k.at != at);
6268 } else {
6269 let params = self.color_at(lane, idx, timeline_frame).unwrap_or_default();
6270 keys.push(ColorKey { at, params, ease: KeyEase::Linear });
6271 }
6272 self.set_color_keys(lane, idx, keys)
6273 }
6274 };
6275 ok.then_some(!had)
6276 }
6277
6278 /// Sets the ease of the key of `kind` on timeline `frame`. `false` -- and no
6279 /// history -- with no key there or one already so. One undo step.
6280 pub fn set_key_ease_at(&mut self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32, ease: KeyEase) -> bool {
6281 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6282 return false;
6283 };
6284 if self.key_ease_at(lane, idx, kind, timeline_frame).is_none_or(|e| e == ease) {
6285 return false;
6286 }
6287 let Some(c) = self.lane(lane).get(idx) else {
6288 return false;
6289 };
6290 match kind {
6291 KeyKind::Placement => {
6292 let mut keys = c.transform_keys.clone();
6293 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6294 self.set_transform_keys(lane, idx, keys)
6295 }
6296 KeyKind::Opacity => {
6297 let mut keys = c.opacity_keys.clone();
6298 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6299 self.set_opacity_keys(lane, idx, keys)
6300 }
6301 KeyKind::Color => {
6302 let mut keys = c.color_keys.clone();
6303 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6304 self.set_color_keys(lane, idx, keys)
6305 }
6306 }
6307 }
6308
6309 /// Writes `keys` as the clip's keys of one kind with the undo step only when
6310 /// `snapshot`: the shape of a drag, whose first sample is a step and the
6311 /// rest are not. The lists were validated by the caller.
6312 fn put_key<K: Keyed>(
6313 &mut self,
6314 lane: Lane,
6315 idx: usize,
6316 snapshot: bool,
6317 key: K,
6318 slot: impl Fn(&mut Clip) -> &mut Vec<K>,
6319 ) -> bool {
6320 if lane.kind != LaneKind::Video {
6321 return false;
6322 }
6323 let Some(clip) = self.lane_mut(lane).and_then(|c| c.get_mut(idx)) else {
6324 return false;
6325 };
6326 let mut keys = slot(clip).clone();
6327 match keys.iter_mut().find(|k| k.at() == key.at()) {
6328 Some(k) => *k = key.placed(key.at(), k.ease()),
6329 None => {
6330 keys.push(key);
6331 keys.sort_by_key(|k| k.at());
6332 }
6333 }
6334 if keys.len() > MAX_TRANSFORM_KEYS {
6335 return false;
6336 }
6337 if snapshot {
6338 self.snapshot();
6339 }
6340 *slot(&mut self.lane_mut(lane).expect("checked")[idx]) = keys;
6341 true
6342 }
6343
6344 /// Sets the placement at timeline `frame` as a key there: a new key, or the
6345 /// existing key's value with its ease kept. The write a slider makes on a clip
6346 /// whose placement is keyed. `snapshot` is the undo step
6347 /// ([`set_transform_live`](Self::set_transform_live)'s rule). `false` where no
6348 /// key can go ([`key_source_frame`](Self::key_source_frame)) or a value is not finite.
6349 pub fn put_transform_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, params: TransformParams, snapshot: bool) -> bool {
6350 self.flat.clear();
6351 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6352 return false;
6353 };
6354 if !transform_finite(&params) {
6355 return false;
6356 }
6357 let params = TransformParams { opacity: params.opacity.clamp(0.0, 1.0), ..params };
6358 self.put_key(lane, idx, snapshot, TransformKey { at, params, ease: KeyEase::Linear }, |c| &mut c.transform_keys)
6359 }
6360
6361 /// [`put_transform_key_at`](Self::put_transform_key_at) for the opacity.
6362 pub fn put_opacity_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, opacity: f32, snapshot: bool) -> bool {
6363 self.flat.clear();
6364 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6365 return false;
6366 };
6367 if !opacity.is_finite() {
6368 return false;
6369 }
6370 let opacity = opacity.clamp(0.0, 1.0);
6371 self.put_key(lane, idx, snapshot, OpacityKey { at, opacity, ease: KeyEase::Linear }, |c| &mut c.opacity_keys)
6372 }
6373
6374 /// [`put_transform_key_at`](Self::put_transform_key_at) for the grade.
6375 pub fn put_color_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, params: ColorParams, snapshot: bool) -> bool {
6376 self.flat.clear();
6377 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6378 return false;
6379 };
6380 if !color_finite(&params) {
6381 return false;
6382 }
6383 let params = ColorParams {
6384 brightness: params.brightness.clamp(-1.0, 1.0),
6385 contrast: params.contrast.clamp(0.0, 2.0),
6386 saturation: params.saturation.clamp(0.0, 2.0),
6387 tint: params.tint.clamp(-1.0, 1.0),
6388 // Keys animate the sliders; the look is the clip's base grade's.
6389 look: crate::color::Look::default(),
6390 };
6391 self.put_key(lane, idx, snapshot, ColorKey { at, params, ease: KeyEase::Linear }, |c| &mut c.color_keys)
6392 }
6393
6394 /// The grade the clip at `idx` of `lane` shows at timeline `frame`: its
6395 /// colour keys evaluated at the source frame that frame plays, or its single
6396 /// grade when it has none. `None` for an index that is not there or a clip
6397 /// with no grade at all and no keys.
6398 pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> {
6399 let c = self.lane(lane).get(idx)?;
6400 if c.color_keys.is_empty() {
6401 return self.color_of(lane, idx).copied();
6402 }
6403 Some(clip_color_at(c, self.color_of(lane, idx).copied().unwrap_or_default(), timeline_frame))
6404 }
6405
6406 /// The opacity the clip at `idx` of `lane` shows at timeline `frame`, the
6407 /// fades not counted: its opacity keys evaluated at the source frame that
6408 /// frame plays, else its placement's (keyed or not). `1.0` for an index
6409 /// that is not there.
6410 pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 {
6411 let Some(c) = self.lane(lane).get(idx) else {
6412 return 1.0;
6413 };
6414 let base = self
6415 .transform_at(lane, idx, timeline_frame)
6416 .map_or(1.0, |t| t.opacity);
6417 clip_opacity_at(c, base, timeline_frame)
6418 }
6419
6420 /// The placement the clip at `idx` of `lane` shows at timeline `frame`: its
6421 /// keys evaluated at the source frame that frame plays
6422 /// ([`keyed_transform`]), or its single [`Clip::transform`] when it has no
6423 /// keys. `None` for an index that is not there or a clip with no
6424 /// transform at all, which is the identity.
6425 pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> {
6426 let c = self.lane(lane).get(idx)?;
6427 if c.transform_keys.is_empty() {
6428 return self.transform_of(lane, idx).copied();
6429 }
6430 Some(clip_transform_at(c, self.transform_of(lane, idx).copied().unwrap_or_default(), timeline_frame))
6431 }
6432
6433 /// The volume envelope of the clip at `idx` of `lane`, sorted by source
6434 /// frame ([`Clip::gain_keys`]). Empty for a clip with no points, and for an
6435 /// index that is not there.
6436 pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] {
6437 self.lane(lane)
6438 .get(idx)
6439 .map_or(&[][..], |c| c.gain_keys.as_slice())
6440 }
6441
6442 /// Replace the whole volume envelope of the clip at `idx` of `lane`; an
6443 /// empty list clears it. The points are sorted here, and each dB is clamped
6444 /// to [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. One undo step.
6445 ///
6446 /// `false` -- and no history -- for a video lane, an index that is not
6447 /// there, more than [`MAX_GAIN_KEYS`] points, a point that is not finite,
6448 /// two points at one source frame, or an envelope already exactly so.
6449 pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<GainKey>) -> bool {
6450 if lane.kind != LaneKind::Audio || keys.len() > MAX_GAIN_KEYS {
6451 return false;
6452 }
6453 if keys.iter().any(|k| !k.db.is_finite()) {
6454 return false;
6455 }
6456 keys.sort_by_key(|k| k.at);
6457 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6458 return false;
6459 }
6460 for k in &mut keys {
6461 k.db = k.db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
6462 }
6463 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6464 return false;
6465 };
6466 if *current == keys {
6467 return false;
6468 }
6469 self.snapshot();
6470 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6471 true
6472 }
6473
6474 /// Put one point into the volume envelope of the clip at `idx` of `lane`:
6475 /// it replaces the point already at `key.at`, or is added in source order.
6476 /// The dB is clamped as [`set_gain_keys`](Self::set_gain_keys) clamps it.
6477 /// One undo step.
6478 ///
6479 /// `false` -- and no history -- for a video lane, an index that is not
6480 /// there, a dB that is not finite, a new point past
6481 /// [`MAX_GAIN_KEYS`], or a point already exactly as it is.
6482 pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool {
6483 if lane.kind != LaneKind::Audio || !key.db.is_finite() {
6484 return false;
6485 }
6486 let key = GainKey {
6487 db: key.db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB),
6488 ..key
6489 };
6490 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6491 return false;
6492 };
6493 let mut keys = current.clone();
6494 match keys.binary_search_by_key(&key.at, |k| k.at) {
6495 Ok(at) => {
6496 if keys[at] == key {
6497 return false;
6498 }
6499 keys[at] = key;
6500 }
6501 Err(at) => {
6502 if keys.len() >= MAX_GAIN_KEYS {
6503 return false;
6504 }
6505 keys.insert(at, key);
6506 }
6507 }
6508 self.snapshot();
6509 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6510 true
6511 }
6512
6513 /// Take the point at source frame `at` out of the volume envelope of the
6514 /// clip at `idx` of `lane`. One undo step.
6515 ///
6516 /// `false` -- and no history -- for a video lane, an index that is not
6517 /// there, or no point at `at`.
6518 pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool {
6519 if lane.kind != LaneKind::Audio {
6520 return false;
6521 }
6522 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6523 return false;
6524 };
6525 let Ok(pos) = current.binary_search_by_key(&at, |k| k.at) else {
6526 return false;
6527 };
6528 let mut keys = current.clone();
6529 keys.remove(pos);
6530 self.snapshot();
6531 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6532 true
6533 }
6534
6535 /// The envelope's effective dB at timeline frame `timeline_frame` of the
6536 /// clip at `idx` of `lane`: its [`Clip::gain_db`] plus its keyed envelope
6537 /// at the source frame that timeline frame plays. The fades are not in it.
6538 /// `None` for a video lane or an index that is not there. Timeline frames
6539 /// before the clip read as its first frame.
6540 pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> {
6541 if lane.kind != LaneKind::Audio {
6542 return None;
6543 }
6544 let c = self.lane(lane).get(idx)?;
6545 Some(c.gain_db + gain_keys_db_at(&c.gain_keys, key_pos(c, timeline_frame)))
6546 }
6547
6548 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
6549 /// ungraded (and for an index that is not there) -- what the renderer and
6550 /// the export ask before they call [`crate::color::apply_yuv`].
6551 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
6552 self.color
6553 .get(usize::from(self.lane(lane).get(idx)?.color?))
6554 }
6555
6556 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
6557 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
6558 /// (and no history) for an index that is not there or a value that is not
6559 /// finite, and equal settings share a table entry.
6560 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
6561 self.write_color(lane, idx, params, true)
6562 }
6563
6564 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
6565 /// one pointer drag, whose first write (a plain `set_color`) already took the
6566 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
6567 /// not one per pixel -- and undoing it lands where the hand picked it up.
6568 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
6569 self.flat.clear();
6570 self.write_color(lane, idx, params, false)
6571 }
6572
6573 fn write_color(
6574 &mut self,
6575 lane: Lane,
6576 idx: usize,
6577 params: Option<ColorParams>,
6578 snapshot: bool,
6579 ) -> bool {
6580 if idx >= self.lane(lane).len() {
6581 return false;
6582 }
6583 let slot = match params {
6584 None => None,
6585 Some(params) => {
6586 if !color_finite(&params) {
6587 return false;
6588 }
6589 Some(match self.color.iter().position(|p| *p == params) {
6590 Some(at) => at as u16,
6591 // corner-cut: the 65535th *distinct* grade of one session is
6592 // refused rather than silently aliased, exactly as `set_eq`
6593 // refuses the 65535th curve; same upgrade path.
6594 None if self.color.len() >= usize::from(u16::MAX) => return false,
6595 None => {
6596 self.color.push(params);
6597 (self.color.len() - 1) as u16
6598 }
6599 })
6600 }
6601 };
6602 if snapshot {
6603 self.snapshot();
6604 }
6605 self.lane_mut(lane).expect("checked above")[idx].color = slot;
6606 true
6607 }
6608
6609 /// Every `.cube` file a clip's grade names, each once, in table order.
6610 pub fn luts(&self) -> Vec<crate::cube::LutRef> {
6611 let used: std::collections::HashSet<u16> =
6612 self.lanes.iter().flat_map(|l| l.clips.iter().filter_map(|c| c.color)).collect();
6613 let mut out = Vec::new();
6614 for (i, p) in self.color.iter().enumerate() {
6615 if let Some(r) = p.look.lut
6616 && used.contains(&(i as u16))
6617 && !out.contains(&r)
6618 {
6619 out.push(r);
6620 }
6621 }
6622 out
6623 }
6624
6625 /// The `.cube` files clips name that cannot be used, and why -- a missing
6626 /// file or a malformed one. Such a clip plays and exports without its LUT
6627 /// (the rest of its grade still applies); this is the warning that says so.
6628 pub fn lut_problems(&self) -> Vec<(PathBuf, String)> {
6629 self.luts().into_iter().filter_map(|r| r.problem().map(|e| (r.path(), e))).collect()
6630 }
6631
6632 /// Points every clip whose grade names the `.cube` file at `from` to `to`
6633 /// instead (re-reading `to` even if it is the same path, so an edited file is
6634 /// picked up). One undo step; the number of clips changed, 0 (and no history)
6635 /// when none names `from`. The colour table only grows, as every grade edit
6636 /// leaves it: the clips are re-pointed, which is what undo restores.
6637 pub fn relink_lut(&mut self, from: &Path, to: &Path) -> usize {
6638 let named = |p: &ColorParams| p.look.lut.is_some_and(|r| r.path() == from);
6639 let hits: Vec<(usize, usize)> = self
6640 .lanes
6641 .iter()
6642 .enumerate()
6643 .flat_map(|(l, lane)| {
6644 lane.clips.iter().enumerate().filter_map(move |(i, c)| c.color.map(|slot| (l, i, slot)))
6645 })
6646 .filter(|&(_, _, slot)| self.color.get(usize::from(slot)).is_some_and(named))
6647 .map(|(l, i, _)| (l, i))
6648 .collect();
6649 if hits.is_empty() {
6650 return 0;
6651 }
6652 let fresh = crate::cube::LutRef::reload(to);
6653 self.snapshot();
6654 for &(l, i) in &hits {
6655 let slot = usize::from(self.lanes[l].clips[i].color.expect("graded"));
6656 let mut params = self.color[slot];
6657 params.look.lut = Some(fresh);
6658 let at = match self.color.iter().position(|p| *p == params) {
6659 Some(at) => at,
6660 None => {
6661 self.color.push(params);
6662 self.color.len() - 1
6663 }
6664 };
6665 self.lanes[l].clips[i].color = Some(at as u16);
6666 }
6667 hits.len()
6668 }
6669
6670 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
6671 /// policy's own placement (and for an index that is not there) -- what the
6672 /// renderer and the export ask before they place its picture.
6673 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
6674 self.transform
6675 .get(usize::from(self.lane(lane).get(idx)?.transform?))
6676 }
6677
6678 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
6679 /// step, `false` (and no history) for an index that is not there or a
6680 /// value that is not finite, and equal settings share a table entry.
6681 pub fn set_transform(
6682 &mut self,
6683 lane: Lane,
6684 idx: usize,
6685 params: Option<TransformParams>,
6686 ) -> bool {
6687 self.write_transform(lane, idx, params, true)
6688 }
6689
6690 /// [`set_transform`](Self::set_transform) without the undo step, for
6691 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
6692 /// one drag on a position/scale/rotate/crop control are one undo, not one
6693 /// per pixel.
6694 pub fn set_transform_live(
6695 &mut self,
6696 lane: Lane,
6697 idx: usize,
6698 params: Option<TransformParams>,
6699 ) -> bool {
6700 self.flat.clear();
6701 self.write_transform(lane, idx, params, false)
6702 }
6703
6704 fn write_transform(
6705 &mut self,
6706 lane: Lane,
6707 idx: usize,
6708 params: Option<TransformParams>,
6709 snapshot: bool,
6710 ) -> bool {
6711 if idx >= self.lane(lane).len() {
6712 return false;
6713 }
6714 let slot = match params {
6715 None => None,
6716 Some(params) => {
6717 if !transform_finite(&params) {
6718 return false;
6719 }
6720 Some(match self.transform.iter().position(|p| *p == params) {
6721 Some(at) => at as u16,
6722 // corner-cut: the 65535th *distinct* transform of one
6723 // session is refused rather than silently aliased,
6724 // exactly as `write_color` refuses the 65535th grade;
6725 // same upgrade path.
6726 None if self.transform.len() >= usize::from(u16::MAX) => return false,
6727 None => {
6728 self.transform.push(params);
6729 (self.transform.len() - 1) as u16
6730 }
6731 })
6732 }
6733 };
6734 if snapshot {
6735 self.snapshot();
6736 }
6737 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
6738 true
6739 }
6740
6741 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
6742 /// index that is not there, which is what every clip starts at anyway.
6743 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
6744 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
6745 }
6746
6747 /// Sets it, for the clip **and its whole group**: a link is one span on
6748 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
6749 /// from its sound would be a group no save could load. One snapshot, so the
6750 /// group's change is one [`Project::undo`].
6751 ///
6752 /// The source range is untouched -- a speed says how many timeline frames
6753 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
6754 /// split still address the file afterwards.
6755 ///
6756 /// Refused, changing nothing and costing no undo step, when the clip would
6757 /// grow into the one after it on its own lane: slowing a clip down makes it
6758 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
6759 /// the way -- by lane and timeline frame -- because "it did not fit" is not
6760 /// something a user can go and fix. Also for an index that is not there.
6761 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
6762 self.write_speed(lane, idx, speed, true)
6763 }
6764
6765 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
6766 /// one pointer drag, whose first write (a plain `set_speed`) already took the
6767 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
6768 /// not one per rate it passed through -- exactly as
6769 /// [`set_color_live`](Self::set_color_live) is for a slider.
6770 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
6771 self.write_speed(lane, idx, speed, false)
6772 }
6773
6774 /// Gives the clip at `idx` of `lane` (and the clips linked to it) a speed ramp
6775 /// `keys` ([`Clip::speed_keys`]); empty keys clear it, and the clip takes its
6776 /// constant [`Clip::speed`] again. Its source range stays, so its footprint is
6777 /// recomputed from the ramp. Nothing ripples: as a constant rate change, the new
6778 /// length must still fit before the next clip on its lane, or the edit is
6779 /// refused, and the caller is told how far it would have run.
6780 pub fn set_speed_ramp(&mut self, lane: Lane, idx: usize, keys: &[SpeedKey]) -> crate::Result<()> {
6781 if !keys.is_empty() && !valid_speed_keys(keys) {
6782 return Err("a speed ramp takes 1 to 8 keys, in strictly increasing frames".into());
6783 }
6784 let Some(members) = self.group_of(lane, idx) else {
6785 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6786 };
6787 if !members.subs.is_empty() {
6788 return Err("this clip is linked to captions, which a speed ramp cannot retime yet".into());
6789 }
6790 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6791 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6792 }
6793 let labels = handles(&self.lanes);
6794 for &(l, i) in &members.clips {
6795 let clips = &self.lanes[l].clips;
6796 let moved = Clip { speed_keys: keys.to_vec(), ..clips[i].clone() };
6797 if let Some(next) = clips.get(i + 1)
6798 && moved.end() > next.start
6799 {
6800 return Err(format!(
6801 "with that ramp the clip would run to frame {} and the next {} clip starts at {}: \
6802 move it along, or trim this one first",
6803 moved.end(),
6804 labels[l].label(),
6805 next.start
6806 )
6807 .into());
6808 }
6809 }
6810 self.snapshot();
6811 for (l, i) in members.clips {
6812 self.lanes[l].clips[i].speed_keys = keys.to_vec();
6813 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
6814 }
6815 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6816 Ok(())
6817 }
6818
6819 fn write_speed(
6820 &mut self,
6821 lane: Lane,
6822 idx: usize,
6823 speed: Speed,
6824 snapshot: bool,
6825 ) -> crate::Result<()> {
6826 let Some(members) = self.group_of(lane, idx) else {
6827 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6828 };
6829 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6830 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6831 }
6832 if self.lane(lane).get(idx).is_some_and(|c| !c.speed_keys.is_empty()) {
6833 return Err("this clip has a speed ramp: clear the ramp before setting a constant speed".into());
6834 }
6835 let labels = handles(&self.lanes);
6836 // The clip the hand is holding is the group's clock: everything else
6837 // in the group, caption members included, re-times by the ratio its new
6838 // rate gives its own frames. The clips take the rate itself; a caption
6839 // has none, so it takes the *ratio* -- its span on the timeline
6840 // compresses or stretches about the held clip's head, while the words
6841 // it reads keep their own timing ([`write_sub_edge`]'s law: the
6842 // timeline moves, the track does not).
6843 let Some(held) = self.lane(lane).get(idx).cloned() else {
6844 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6845 };
6846 // The same per-member piece `speeded_playhead` builds for this op,
6847 // asked here instead of read there -- a caption's length comes from
6848 // the map's own ends (`end - start`), never `round(len * ratio)`
6849 // separately, which is what let the two answers drift apart by a
6850 // frame.
6851 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
6852 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
6853 let retimed = |s: SubClip| {
6854 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
6855 let start = map.apply(s.start);
6856 let end = map.apply(s.end()).max(start.saturating_add(1));
6857 SubClip {
6858 start,
6859 frames: end - start,
6860 ..s
6861 }
6862 };
6863 for &(l, i) in &members.clips {
6864 let clips = &self.lanes[l].clips;
6865 let mut moved = clips[i].clone();
6866 moved.speed = speed;
6867 if let Some(next) = clips.get(i + 1)
6868 && moved.end() > next.start
6869 {
6870 let name = labels[l].label();
6871 return Err(format!(
6872 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
6873 move it along, or trim this one first",
6874 moved.end(),
6875 next.start
6876 )
6877 .into());
6878 }
6879 }
6880 // ...and the captions, against their own lanes' captions: a stretch
6881 // that runs one into its neighbour is refused for the clip arm's
6882 // reason -- a lane may not overlap itself -- and by name like it.
6883 let subs: Vec<(usize, usize, SubClip)> = members
6884 .subs
6885 .iter()
6886 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
6887 .collect();
6888 for &(l, i, moved) in &subs {
6889 for (j, other) in self.lanes[l].subs.iter().enumerate() {
6890 if j != i && moved.start < other.end() && other.start < moved.end() {
6891 return Err(format!(
6892 "at {speed} the {} caption at frame {} would run to frame {} and the next \
6893 starts at {}: move it along, or trim this one first",
6894 labels[l].label(),
6895 self.lanes[l].subs[i].start,
6896 moved.end(),
6897 other.start
6898 )
6899 .into());
6900 }
6901 }
6902 }
6903 if snapshot {
6904 self.snapshot();
6905 }
6906 for (l, i) in members.clips {
6907 self.lanes[l].clips[i].speed = speed;
6908 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
6909 }
6910 for (l, i, moved) in subs {
6911 self.lanes[l].subs[i] = moved;
6912 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
6913 }
6914 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6915 Ok(())
6916 }
6917
6918 /// Whether the clip at `idx` of `lane` plays backwards ([`Clip::reversed`]);
6919 /// `false` for an index that is not there.
6920 pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool {
6921 self.lane(lane).get(idx).is_some_and(|c| c.reversed)
6922 }
6923
6924 /// Plays the clip at `idx` of `lane` backwards (`on`) or forwards again, for the
6925 /// clip **and its whole group**, as [`set_speed`](Self::set_speed) does: a picture
6926 /// run backwards against its sound would be a take nobody recorded. One snapshot,
6927 /// so the group's change is one [`Project::undo`]. Nothing moves: a clip's
6928 /// footprint and window are the same either way, which is why this can never be
6929 /// refused for room.
6930 ///
6931 /// The keys read from the footage -- placement and volume points are source-keyed
6932 /// -- are mirrored across the window as the direction flips, so every animation
6933 /// still plays on the same timeline frames it did, and only the footage under it
6934 /// runs the other way. Flipping twice puts every key back on the frame it was on.
6935 ///
6936 /// Refused, changing nothing, for a still (it has no direction), and for an index
6937 /// that is not there. A group already in the asked state is `Ok` and costs no undo
6938 /// step.
6939 pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> {
6940 let Some(members) = self.group_of(lane, idx) else {
6941 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6942 };
6943 if members.clips.iter().any(|&(l, i)| self.is_still(&self.lanes[l].clips[i])) {
6944 return Err("a still picture has no direction to reverse".into());
6945 }
6946 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6947 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6948 }
6949 if members.clips.iter().all(|&(l, i)| self.lanes[l].clips[i].reversed == on) {
6950 return Ok(());
6951 }
6952 self.snapshot();
6953 for (l, i) in members.clips {
6954 let c = &mut self.lanes[l].clips[i];
6955 if c.reversed != on {
6956 c.reversed = on;
6957 mirror_keys(c);
6958 }
6959 }
6960 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6961 Ok(())
6962 }
6963
6964 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
6965 /// playhead standing at `at` -- read off the geometry **before** the
6966 /// write, because the old ends are gone after it. The question a card
6967 /// asks as its bar moves: the picture under the cursor has to stay the
6968 /// picture under the cursor, or the scene changes with the rate.
6969 ///
6970 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
6971 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
6972 /// a clip member keeps its own start and re-fits its length at the new
6973 /// rate -- its **old** rate against the new one, which is what the bar's
6974 /// live samples ask about as much as a first press does; a caption
6975 /// member scales about the held clip's start by the held clip's own
6976 /// proportion; and a playhead outside every member's old extent stays
6977 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
6978 /// (or the room a stretch takes) absorbs the difference, not the
6979 /// playhead. `None` for an index that is not there.
6980 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
6981 // A ramped clip has no single rate to re-fit against: no answer, not a wrong one.
6982 if self.lane(lane).get(idx).is_some_and(|c| !c.speed_keys.is_empty()) {
6983 return None;
6984 }
6985 let members = self.group_of(lane, idx)?;
6986 let held = self.lane(lane).get(idx).cloned()?;
6987 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
6988 for &(l, i) in members.clips.iter().chain(&members.subs) {
6989 let (span, map) = match self.lanes[l]
6990 .clips
6991 .get(i)
6992 .filter(|_| members.clips.contains(&(l, i)))
6993 {
6994 // The clip's own span, re-fitted at its own old rate: one
6995 // piece of the map, anchored where the clip itself is. The
6996 // new length is the same *source* frames at the new rate --
6997 // len divided by it, never multiplied.
6998 Some(c) => (
6999 (c.start, c.start + c.frames()),
7000 TimelineMap::piece(
7001 (c.start, c.start + c.frames()),
7002 (c.start, c.start + (c.len() as f64 / new).round() as u32),
7003 ),
7004 ),
7005 // The caption's span, scaled about the held clip's head by
7006 // the held clip's proportion -- the offset the group keeps.
7007 None => {
7008 let s = self.lanes[l].subs.get(i)?;
7009 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
7010 (
7011 (s.start, s.end()),
7012 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
7013 )
7014 }
7015 };
7016 // The piece owns only its own old span: outside it the playhead
7017 // is another member's question, or nobody's.
7018 if (span.0..span.1).contains(&at) {
7019 return Some(map.apply(at));
7020 }
7021 }
7022 Some(at)
7023 }
7024
7025 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
7026 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
7027 /// every clip starts at anyway.
7028 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
7029 self.lane(lane)
7030 .get(idx)
7031 .map_or(FitPolicy::default(), |c| c.fit)
7032 }
7033
7034 /// Sets it. One undo step like every other edit, and `false` (with no
7035 /// history) for an index that is not there. Unlike an eq or a grade there is
7036 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
7037 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
7038 if idx >= self.lane(lane).len() {
7039 return false;
7040 }
7041 self.snapshot();
7042 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
7043 true
7044 }
7045
7046 /// Turns the stabilisation of the clip at `idx` of a video `lane` on (with its
7047 /// settings) or off (`None`). One undo step; `false` (no history) for an index
7048 /// that is not there, a lane that is not video, or no change.
7049 pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool {
7050 if lane.kind != LaneKind::Video || self.lane(lane).get(idx).is_none_or(|c| c.stabilise == st) {
7051 return false;
7052 }
7053 self.snapshot();
7054 self.lane_mut(lane).expect("checked above")[idx].stabilise = st;
7055 true
7056 }
7057
7058 /// Sets how a video clip's interlaced source is deinterlaced
7059 /// ([`Clip::deinterlace`]). One undo step; `false`, and no history, for a
7060 /// lane that is not video, a clip that is not there, or no change.
7061 pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: Deinterlace) -> bool {
7062 if lane.kind != LaneKind::Video || self.lane(lane).get(idx).is_none_or(|c| c.deinterlace == mode) {
7063 return false;
7064 }
7065 self.snapshot();
7066 self.lane_mut(lane).expect("checked above")[idx].deinterlace = mode;
7067 true
7068 }
7069
7070 /// Points the clip at `idx` of a video `lane` at another source -- how a generator's
7071 /// parameter is edited (a new spelling is a new source). The window is kept. One undo step;
7072 /// `false` and no history for a clip that is not there, a source that is not, or no change.
7073 pub fn set_clip_source(&mut self, lane: Lane, idx: usize, source: usize) -> bool {
7074 if lane.kind != LaneKind::Video || source >= self.sources.len() || self.lane(lane).get(idx).is_none_or(|c| c.source == source) {
7075 return false;
7076 }
7077 self.snapshot();
7078 self.lane_mut(lane).expect("checked above")[idx].source = source;
7079 true
7080 }
7081
7082 /// Sets the colour label of the clip at `idx` of `lane` (0 for none). One undo step; `false`
7083 /// and no history for a clip that is not there, a label outside the palette, or no change.
7084 pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool {
7085 if label > LABEL_COUNT || self.lane(lane).get(idx).is_none_or(|c| c.mark.label == label) {
7086 return false;
7087 }
7088 self.snapshot();
7089 self.lane_mut(lane).expect("checked above")[idx].mark.label = label;
7090 true
7091 }
7092
7093 /// Switches the clip at `idx` of `lane` on or off ([`ClipMark::off`]). One undo step; `false`
7094 /// and no history for a clip that is not there or no change.
7095 pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool {
7096 if self.lane(lane).get(idx).is_none_or(|c| c.mark.off != enabled) {
7097 return false;
7098 }
7099 self.snapshot();
7100 self.lane_mut(lane).expect("checked above")[idx].mark.off = !enabled;
7101 true
7102 }
7103
7104 /// The clip's mark, the default for no clip.
7105 pub fn mark_of(&self, lane: Lane, idx: usize) -> ClipMark {
7106 self.lane(lane).get(idx).map_or_else(ClipMark::default, |c| c.mark)
7107 }
7108
7109 /// The clip's deinterlace setting, `Frame` for no clip.
7110 pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> Deinterlace {
7111 self.lane(lane).get(idx).map_or_else(Deinterlace::default, |c| c.deinterlace)
7112 }
7113
7114 /// The clip's stabilisation ([`Clip::stabilise`]), `None` for off or no clip.
7115 pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> {
7116 self.lane(lane).get(idx)?.stabilise
7117 }
7118
7119 /// Waveform style flags on the clip at `idx` of `lane`. Bit 0 marks it
7120 /// a visualizer; the rest are outline/smooth/fast/tint. `false` (no
7121 /// history) for an index that is not there.
7122 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
7123 if idx >= self.lane(lane).len() {
7124 return false;
7125 }
7126 self.snapshot();
7127 self.lane_mut(lane).expect("checked above")[idx].visualizer = flags;
7128 true
7129 }
7130
7131 /// Give the clip at `idx` of `lane` this packed look: one undo step, and
7132 /// `false` (with no history) for an index that is not there, the way every
7133 /// other setter refuses.
7134 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
7135 self.write_viz_paint(lane, idx, paint, true)
7136 }
7137
7138 /// [`set_viz_paint`](Self::set_viz_paint) without the undo step: the
7139 /// samples *inside* one pointer drag across the colour wheel, whose first
7140 /// write (a plain `set_viz_paint`) already took the snapshot the gesture
7141 /// rolls back to. One drag is one undo, not one per sample.
7142 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
7143 self.flat.clear();
7144 self.write_viz_paint(lane, idx, paint, false)
7145 }
7146
7147 fn write_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64, snapshot: bool) -> bool {
7148 if idx >= self.lane(lane).len() {
7149 return false;
7150 }
7151 if snapshot {
7152 self.snapshot();
7153 }
7154 self.lane_mut(lane).expect("checked above")[idx].viz_paint = paint;
7155 true
7156 }
7157
7158 /// Timeline frames of ramp-up from silence at the start of the clip at
7159 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
7160 /// that has none.
7161 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
7162 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
7163 }
7164
7165 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
7166 /// can shrink a clip's audible middle to nothing but never ask for more
7167 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
7168 /// and `false` (no history) for an index that is not there.
7169 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7170 if idx >= self.lane(lane).len() {
7171 return false;
7172 }
7173 self.snapshot();
7174 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
7175 clip.fade_in = frames.min(clip.frames());
7176 true
7177 }
7178
7179 /// Timeline frames of ramp-down to silence at the end of the clip at
7180 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
7181 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
7182 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
7183 }
7184
7185 /// Sets it. Same promises as [`Project::set_fade_in`].
7186 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7187 if idx >= self.lane(lane).len() {
7188 return false;
7189 }
7190 self.snapshot();
7191 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
7192 clip.fade_out = frames.min(clip.frames());
7193 true
7194 }
7195
7196 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
7197 /// into its successor, at its own end. `0` for an index that is not
7198 /// there, same as a clip that has none.
7199 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
7200 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
7201 }
7202
7203 /// Sets it, clamped to the clip's own length and to how many frames its
7204 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
7205 /// visible middle to nothing but never ask for more than the two clips
7206 /// between them have. `false` -- no history -- unless `lane` is video,
7207 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
7208 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
7209 /// them. One undo step like [`Project::set_fade_out`].
7210 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7211 if lane.kind != LaneKind::Video {
7212 return false;
7213 }
7214 let clips = self.lane(lane);
7215 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7216 return false;
7217 };
7218 if a.end() != b.start {
7219 return false;
7220 }
7221 let cap = a.frames().min(b.frames());
7222 self.snapshot();
7223 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
7224 true
7225 }
7226
7227 /// The kind of the transition the clip at `idx` of `lane` plays into its
7228 /// successor; a dissolve for an index that is not there.
7229 pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind {
7230 self.lane(lane).get(idx).map_or_else(Default::default, |c| c.transition_kind)
7231 }
7232
7233 /// [`Project::set_transition_out`] with a kind: sets both in one undo step.
7234 pub fn set_transition(
7235 &mut self,
7236 lane: Lane,
7237 idx: usize,
7238 kind: crate::transitions::TransitionKind,
7239 frames: u32,
7240 ) -> bool {
7241 if lane.kind != LaneKind::Video {
7242 return false;
7243 }
7244 let clips = self.lane(lane);
7245 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7246 return false;
7247 };
7248 if a.end() != b.start {
7249 return false;
7250 }
7251 let cap = a.frames().min(b.frames());
7252 self.snapshot();
7253 let a = &mut self.lane_mut(lane).expect("checked above")[idx];
7254 a.transition_out = frames.min(cap);
7255 a.transition_kind = kind;
7256 true
7257 }
7258
7259 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
7260 /// after it, over `frames` timeline frames: sets `idx`'s
7261 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
7262 /// each clamped to its own clip's length. `false` -- no history -- unless
7263 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
7264 /// adjacent: the second's [`Clip::start`] is exactly the first's
7265 /// [`Clip::end`], no gap between them.
7266 ///
7267 /// This is the whole mechanism, not a stand-in for one: a *real*
7268 /// cross-fade -- both takes heard at once, blending -- is what two clips
7269 /// **overlapping** on separate lanes already get for free from the
7270 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
7271 /// This call only shapes the edges of two clips already sitting
7272 /// end-to-end on *one* lane, so the join between them fades like one did.
7273 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7274 if lane.kind != LaneKind::Audio {
7275 return false;
7276 }
7277 let clips = self.lane(lane);
7278 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7279 return false;
7280 };
7281 if a.end() != b.start {
7282 return false;
7283 }
7284 self.snapshot();
7285 let clips = self.lane_mut(lane).expect("checked above");
7286 clips[idx].fade_out = frames.min(clips[idx].frames());
7287 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
7288 true
7289 }
7290
7291 /// Every frame number on every lane rewritten onto a timeline counted at
7292 /// another rate: `k` is old timeline frames per new one, `counts` is how
7293 /// long each source is on the *new* timeline (indexed as
7294 /// [`Project::sources`] is), and the edit survives as the same seconds of
7295 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
7296 /// the edit list, and the only thing that touches the frame numbers without
7297 /// being an edit anyone made.
7298 ///
7299 /// Every position -- a clip's start and its end alike -- goes through the
7300 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
7301 /// stays a gap, and a take's picture and its sound land on the same frame on
7302 /// their two lanes: no lane can drift against another. A clip is then only
7303 /// ever made to *fit* the room its own start and end mapped to, never to
7304 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
7305 /// below is the backstop for the one case that could: a slow clip so short
7306 /// that no source range fits its new room at all).
7307 ///
7308 /// Rounded to the nearest frame of the new grid, every boundary, length and
7309 /// envelope ([`Rate::timeline_nearest`]), so no round trip drifts: a second
7310 /// trip lands where the first did. Not exact both ways in general: a frame
7311 /// of one grid can fall between two of the other, and a rate change keeps
7312 /// only the frame it rounds to. An edit whose frames sit on both grids (on
7313 /// a whole second at 30, 25 and 24 fps) comes back exactly; any other
7314 /// boundary comes back within one frame. The exact fix is to hold the edit
7315 /// in seconds rather than frames, which every frame number in this module
7316 /// is measured in.
7317 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
7318 for lane in &mut self.lanes {
7319 let mut cursor = 0;
7320 for clip in &mut lane.clips {
7321 let start = k.timeline_nearest(clip.start).max(cursor);
7322 // The room its own end mapped to -- never zero, since a clip is
7323 // never empty even on a grid too coarse to hold it.
7324 let room = k.timeline_nearest(clip.end()).saturating_sub(start).max(1);
7325 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
7326 // Its footage, held inside the file's new length: a clip whose
7327 // out-point was the last frame of its source must not come out
7328 // of this naming a frame past the end -- that is a project that
7329 // would not open again ([`crate::PlaybackSession::open_project`]
7330 // refuses one by name).
7331 let in_frame = k.timeline_nearest(clip.in_frame).min(count - 1);
7332 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
7333 // The envelopes are frame counts measured from the clip's own
7334 // start (fades in), its own end (fades out and a dissolve into
7335 // the next clip). Each is its own length in seconds, rounded to the
7336 // nearest frame of the new grid, not a difference of two rounded
7337 // boundaries, which is what let a dissolve drift a frame per trip.
7338 let fade_in = k.timeline_nearest(clip.fade_in);
7339 let fade_out = k.timeline_nearest(clip.fade_out);
7340 let transition = k.timeline_nearest(clip.transition_out);
7341 clip.start = start;
7342 clip.in_frame = in_frame;
7343 clip.out_frame = in_frame + len;
7344 let frames = clip.frames();
7345 clip.fade_in = fade_in.min(frames);
7346 clip.fade_out = fade_out.min(frames);
7347 clip.transition_out = transition.min(frames);
7348 // A volume point is a source frame, numbered the way `in_frame`
7349 // is, so it moves with the footage. Two points that land on one
7350 // frame keep the first, since the envelope holds one per frame.
7351 let mut last = None;
7352 clip.gain_keys.retain_mut(|key| {
7353 key.at = k.timeline_nearest(key.at);
7354 let keep = last != Some(key.at);
7355 last = Some(key.at);
7356 keep
7357 });
7358 // The placement keys are source frames too, so they follow the
7359 // same grid, one point per frame as the envelope keeps them.
7360 let mut last = None;
7361 clip.transform_keys.retain_mut(|key| {
7362 key.at = k.timeline_nearest(key.at);
7363 let keep = last != Some(key.at);
7364 last = Some(key.at);
7365 keep
7366 });
7367 let mut last = None;
7368 clip.opacity_keys.retain_mut(|key| {
7369 key.at = k.timeline_nearest(key.at);
7370 let keep = last != Some(key.at);
7371 last = Some(key.at);
7372 keep
7373 });
7374 let mut last = None;
7375 clip.color_keys.retain_mut(|key| {
7376 key.at = k.timeline_nearest(key.at);
7377 let keep = last != Some(key.at);
7378 last = Some(key.at);
7379 keep
7380 });
7381 cursor = clip.end();
7382 }
7383 // A dissolve is only as long as the clip it dissolves into allows
7384 // too, which the rescale above cannot see one clip at a time.
7385 for i in 1..lane.clips.len() {
7386 let (before, after) = lane.clips.split_at_mut(i);
7387 let (a, b) = (&mut before[i - 1], &after[0]);
7388 if a.end() == b.start {
7389 a.transition_out = a.transition_out.min(b.frames());
7390 }
7391 }
7392 // A subtitle's *window* is in microseconds and a rate change moves
7393 // no seconds, so only where it sits is remapped -- through the same
7394 // [`Rate::timeline_at`] every clip boundary goes through, so a
7395 // caption still starts on the frame its picture does.
7396 let mut cursor = 0;
7397 for sub in &mut lane.subs {
7398 let start = k.timeline_nearest(sub.start).max(cursor);
7399 sub.frames = k.timeline_nearest(sub.end()).saturating_sub(start).max(1);
7400 sub.start = start;
7401 cursor = sub.end();
7402 }
7403 }
7404 // A title is placed and sized in frames like a clip and its captions,
7405 // so it takes the same grid: its window maps start to end, and its
7406 // fades are re-measured from the boundary each one is counted from.
7407 // Held inside the largest frame a title may end on, which is the check
7408 // a load makes of every title.
7409 for title in &mut self.titles {
7410 let (old_start, old_end) = (title.start, title.end());
7411 let start = k.timeline_nearest(old_start);
7412 let end = k.timeline_nearest(old_end).min(MAX_TITLE_END).max(start + 1);
7413 let frames = end - start;
7414 title.fade_in = k.timeline_nearest(title.fade_in).min(frames);
7415 title.fade_out = k.timeline_nearest(title.fade_out).min(frames);
7416 title.start = start;
7417 title.frames = frames;
7418 }
7419 // A chapter is a single frame, so it takes the grid as a title's start
7420 // does; two that land on one frame keep the first.
7421 for chapter in &mut self.chapters {
7422 chapter.frame = k.timeline_nearest(chapter.frame);
7423 }
7424 self.chapters.dedup_by_key(|c| c.frame);
7425 // A marker's start and end take the grid the same way.
7426 for m in &mut self.markers {
7427 let end = k.timeline_nearest(m.frame + m.length);
7428 m.frame = k.timeline_nearest(m.frame);
7429 m.length = end.saturating_sub(m.frame);
7430 }
7431 self.markers.sort_by_key(|m| m.frame);
7432 }
7433
7434 /// Length of the timeline in frames: where the *last* lane runs out. A lane
7435 /// that ends early is a trailing gap in that lane, not a shorter timeline.
7436 ///
7437 /// A subtitle lane counts like any other: a caption placed past the last
7438 /// picture holds the timeline open under it, exactly as an `A2` running
7439 /// past `V1` does, rather than being silently clipped away by the length
7440 /// ([`crate::export::timeline_cues`] clips cues to this).
7441 pub fn timeline_frames(&self) -> u32 {
7442 self.lanes
7443 .iter()
7444 .filter_map(|l| match l.kind {
7445 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
7446 _ => l.clips.last().map(Clip::end),
7447 })
7448 .max()
7449 .unwrap_or(0)
7450 .max(self.title_end())
7451 }
7452
7453 /// The same, counting the *media* alone: where the last picture or sound
7454 /// runs out, with the captions over them ignored.
7455 ///
7456 /// What an export actually writes ends here -- the picture loop walks the
7457 /// composite spans and the file stops with them -- so this is the length a
7458 /// cue has to be inside of to be written at all (what
7459 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
7460 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
7461 /// thing is a picture or a sound, which is every timeline that has no
7462 /// caption hanging past the end of both.
7463 pub fn media_frames(&self) -> u32 {
7464 self.lanes
7465 .iter()
7466 .filter(|l| l.kind != LaneKind::Subtitle)
7467 .filter_map(|l| l.clips.last().map(Clip::end))
7468 .max()
7469 .unwrap_or(0)
7470 // A title is picture too: one past the last clip runs on over black,
7471 // so the export and the picture cover it.
7472 .max(self.title_end())
7473 }
7474
7475 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
7476 /// to lay clips out. Gaps show up as the holes between consecutive entries.
7477 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
7478 self.lane_spans(Lane::V1)
7479 }
7480
7481 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
7482 // Timeline frames, not source ones: a box on a lane is as wide as the
7483 // clip is long *there*, which a speed halves or quadruples.
7484 self.lane(lane)
7485 .iter()
7486 .map(|c| (c.start, c.frames()))
7487 .collect()
7488 }
7489
7490 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
7491 /// and past the end -- [`Project::span_at`] is the version that tells those
7492 /// two apart.
7493 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
7494 let clips = self.lane(lane);
7495 let idx = at(clips, timeline_frame)?;
7496 Some((idx, source_frame(&clips[idx], timeline_frame)))
7497 }
7498
7499 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
7500 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
7501 self.map(Lane::V1, timeline_frame)
7502 }
7503
7504 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
7505 /// it, or the gap running to the next clip (or to the end of the timeline,
7506 /// which is where a lane shorter than its neighbour keeps showing black).
7507 /// `None` at or past the end of the timeline, which is the only "nothing
7508 /// left" there is.
7509 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
7510 let total = self.timeline_frames();
7511 if timeline_frame >= total {
7512 return None;
7513 }
7514 let clips = self.lane(lane);
7515 Some(match at(clips, timeline_frame) {
7516 Some(idx) => {
7517 let (speed, ramp) = span_speed_of(&clips[idx], timeline_frame);
7518 Span {
7519 start: timeline_frame,
7520 len: clips[idx].end() - timeline_frame,
7521 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
7522 speed,
7523 ramp,
7524 reverse: clips[idx].reversed,
7525 pitch: clips[idx].pitch,
7526 }
7527 }
7528 None => Span {
7529 start: timeline_frame,
7530 speed: Speed::NORMAL,
7531 ramp: None,
7532 reverse: false,
7533 pitch: 0,
7534 // The next placement, or the end of the timeline: a gap is
7535 // bounded by what comes after it, never by its own bookkeeping.
7536 len: clips
7537 .iter()
7538 .find(|c| c.start > timeline_frame)
7539 .map_or(total, |c| c.start)
7540 - timeline_frame,
7541 from: None,
7542 },
7543 })
7544 }
7545
7546 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
7547 /// gaps included -- the whole play list, which is what an export walks.
7548 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
7549 let mut out = Vec::new();
7550 let mut t = timeline_frame;
7551 while let Some(span) = self.span_at(lane, t) {
7552 t = span.end();
7553 out.push(span);
7554 }
7555 out
7556 }
7557
7558 /// What the *composite* shows from `timeline_frame` on -- the answer
7559 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
7560 /// video lane by one rule: **the topmost lane with a clip there wins**, and
7561 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
7562 /// (the usual overlay convention). A frame no video lane covers is a gap,
7563 /// which is black however many lanes are above or below it.
7564 ///
7565 /// No blending, so exactly one lane is visible at a time and the composite
7566 /// is itself a span list -- which is why one decoder plays it, the same one
7567 /// a single-lane timeline uses, rather than N running at once.
7568 ///
7569 /// The span is cut short wherever a *higher* lane's clip starts, because
7570 /// from that frame on a different lane wins; that is what makes walking
7571 /// [`composite_spans_from`](Project::composite_spans_from) correct.
7572 ///
7573 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
7574 /// lanes would then be visible in one frame and the caller needs a decoder
7575 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
7576 /// (this same walk, per lane) feeding N decoders.
7577 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
7578 let total = self.timeline_frames();
7579 if timeline_frame >= total {
7580 return None;
7581 }
7582 let video = self.video_lanes();
7583 // The last covering lane is the winner; only the lanes above it can
7584 // interrupt what it shows.
7585 let winner = video
7586 .iter()
7587 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
7588 let (from, speed, ramp, until, reverse) = match winner {
7589 Some(i) => {
7590 let clips = self.lane(video[i]);
7591 let idx = at(clips, timeline_frame).expect("just found above");
7592 let (speed, ramp) = span_speed_of(&clips[idx], timeline_frame);
7593 (
7594 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
7595 speed,
7596 ramp,
7597 clips[idx].end(),
7598 clips[idx].reversed,
7599 )
7600 }
7601 // Nothing covers it: black until something above the floor starts.
7602 None => (None, Speed::NORMAL, None, total, false),
7603 };
7604 let takeover = video[winner.map_or(0, |i| i + 1)..]
7605 .iter()
7606 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
7607 .map(|c| c.start)
7608 .min();
7609 Some(Span {
7610 start: timeline_frame,
7611 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
7612 from,
7613 speed,
7614 ramp,
7615 reverse,
7616 pitch: 0,
7617 })
7618 }
7619
7620 /// The video lanes in display order, topmost last -- the order the composite
7621 /// rule counts in. A hidden one is not in it: the picture is composed from
7622 /// what is visible, so a hidden lane is black where it is the only one
7623 /// covering and the lane below shows through where it is not.
7624 fn video_lanes(&self) -> Vec<Lane> {
7625 self.lanes()
7626 .into_iter()
7627 .filter(|l| l.kind == LaneKind::Video && !self.lane_hidden(*l))
7628 .collect()
7629 }
7630
7631 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
7632 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
7633 /// index on that lane. `None` over a gap and past the end. What a front-end
7634 /// asks to act on "the clip on screen" without re-deriving the rule.
7635 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
7636 let video = self.video_lanes();
7637 let winner = video
7638 .iter()
7639 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
7640 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
7641 }
7642
7643 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
7644 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
7645 /// answers "the clip on screen"; this answers it per lane, which is what
7646 /// walking the lanes for something to select needs.
7647 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
7648 at(self.lane(lane), timeline_frame)
7649 }
7650
7651 /// How the composite is graded at `timeline_frame`, so the picture playback
7652 /// converts and the one an export encodes are graded from one answer.
7653 /// `None` over a gap (black is black) and for a clip nobody has graded,
7654 /// which is the byte-identical path everywhere.
7655 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
7656 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
7657 self.color_of(lane, idx)
7658 }
7659
7660 /// [`composite_color_at`](Self::composite_color_at)'s twin for
7661 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
7662 /// policy's own placement.
7663 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
7664 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
7665 self.transform_of(lane, idx)
7666 }
7667
7668 /// How the composite meets the project canvas at `timeline_frame`, so the
7669 /// picture playback composes and the one an export encodes are placed from
7670 /// one answer. `Fit` over a gap, where black is already the canvas.
7671 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
7672 self.composite_clip_at(timeline_frame)
7673 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
7674 }
7675
7676 /// Waveform flags of the topmost video clip at `timeline_frame`, or 0
7677 /// over a gap / a picture that is not a visualizer.
7678 pub fn composite_visualizer_at(&self, timeline_frame: u32) -> u8 {
7679 self.composite_clip_at(timeline_frame)
7680 .map(|(lane, idx)| self.lane(lane)[idx].visualizer)
7681 .unwrap_or(0)
7682 }
7683
7684 /// Packed look ([`Clip::viz_paint`]) of the topmost video clip at
7685 /// `timeline_frame`, or zero over a gap / a picture that is not a
7686 /// visualizer.
7687 pub fn composite_viz_paint_at(&self, timeline_frame: u32) -> u64 {
7688 self.composite_clip_at(timeline_frame)
7689 .map(|(lane, idx)| self.lane(lane)[idx].viz_paint)
7690 .unwrap_or(0)
7691 }
7692
7693 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
7694 /// viewer sees from `timeline_frame` to the end, in order. What an export
7695 /// encodes and what playback walks at a clip boundary.
7696 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
7697 let mut out = Vec::new();
7698 let mut t = timeline_frame;
7699 while let Some(span) = self.composite_span_at(t) {
7700 t = span.end();
7701 out.push(span);
7702 }
7703 out
7704 }
7705
7706 /// The frame nearest `frame`, within `reach` frames either side, at which a cut lands
7707 /// cleanly on every lane -- `frame` itself when it does. `None` when no such frame is
7708 /// that near, which is what a cut or a freeze there is refused for.
7709 pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> {
7710 let clean = |f: u32| {
7711 self.lanes.iter().all(|l| {
7712 l.clips
7713 .iter()
7714 .all(|c| !(c.start < f && f < c.end()) || split_source(c, f).is_some())
7715 })
7716 };
7717 (0..=reach)
7718 .flat_map(|d| [frame.checked_add(d), frame.checked_sub(d)])
7719 .flatten()
7720 .find(|&f| clean(f))
7721 }
7722
7723 /// Split every lane at `timeline_frame`, so that frame becomes the first
7724 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
7725 /// (`false`, no change) when no lane has a clip to split there -- at a
7726 /// placement's own start, in a gap, and past the end -- all of which would
7727 /// produce an empty clip or nothing at all.
7728 ///
7729 /// Lanes' halves share an id only where they are the *same* span: the lanes
7730 /// are edited apart, so the clip being cut here may start (or end)
7731 /// somewhere else on another lane, and a group id whose clips disagree
7732 /// about their span is not one take (see [`links_are_consistent`], which
7733 /// refuses to load one).
7734 ///
7735 /// Metadata only: no mapping changes, in any lane.
7736 pub fn split(&mut self, timeline_frame: u32) -> bool {
7737 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
7738 }
7739
7740 /// [`split`](Project::split) on the lanes in `scope` only: the lanes outside
7741 /// it keep their clip across the frame. `false`, no change, as `split`.
7742 pub fn split_on(&mut self, timeline_frame: u32, scope: &[Lane]) -> bool {
7743 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
7744 self.write_split(timeline_frame, true, &on)
7745 }
7746
7747 /// [`split`](Project::split), with the snapshot optional and the lanes
7748 /// named: a batch that has already taken a snapshot
7749 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
7750 /// region and must still be one undo press, and a *scoped* batch must not
7751 /// cut a lane it was told to leave alone.
7752 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
7753 let cut: Vec<Option<Clip>> = self
7754 .lanes
7755 .iter()
7756 .enumerate()
7757 .map(|(i, l)| {
7758 on.contains(&i)
7759 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx].clone()))
7760 .flatten()
7761 })
7762 .collect();
7763 // The same question on the subtitle lanes, in their own arithmetic: a
7764 // razor cuts the captions with the picture, and a frame where only a
7765 // caption can be cut is still a cut.
7766 let cut_subs: Vec<bool> = self
7767 .lanes
7768 .iter()
7769 .enumerate()
7770 .map(|(i, l)| {
7771 on.contains(&i)
7772 && l.subs
7773 .iter()
7774 .any(|s| s.start < timeline_frame && timeline_frame < s.end())
7775 })
7776 .collect();
7777 // The links the captions carry, read before the room is opened below
7778 // -- `sub_open_room` takes the id off both halves, exactly as
7779 // `open_room` does for a clip, and the split hands the halves theirs
7780 // back afterwards.
7781 let sub_orig: Vec<Option<u32>> = self
7782 .lanes
7783 .iter()
7784 .zip(&cut_subs)
7785 .map(|(l, &cut)| {
7786 cut.then(|| {
7787 l.subs
7788 .iter()
7789 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
7790 .and_then(|s| s.link)
7791 })
7792 .flatten()
7793 })
7794 .collect();
7795 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
7796 return false;
7797 }
7798 if snapshot {
7799 self.snapshot();
7800 }
7801 // The captions' words are divided before their windows are cut, so
7802 // the words on the far side of the split stay with the far side.
7803 self.split_cues_across(on, &[timeline_frame], false);
7804 for (data, _) in self
7805 .lanes
7806 .iter_mut()
7807 .zip(&cut_subs)
7808 .filter(|&(_, &cut)| cut)
7809 {
7810 // A split is room of no width: the halves keep their windows by
7811 // proportion and nothing moves.
7812 sub_open_room(&mut data.subs, timeline_frame, 0);
7813 debug_assert!(subs_sorted_disjoint(&data.subs));
7814 }
7815 // Each side is its own question, and the answer is the group the clip
7816 // already carried: the left half *keeps* its take's id -- the take the
7817 // frames before the cut still are -- and the right halves of one take
7818 // share one fresh id of their own, clips and captions alike. A lane
7819 // holding no group (a `place`ment, a caption nobody grouped) comes out
7820 // of the cut holding none, which is what it went in with. The captions'
7821 // own links were drawn above, before the room opened.
7822 let orig: Vec<Option<u32>> = cut
7823 .iter()
7824 .map(|c| c.as_ref().and_then(|c| c.link))
7825 .collect();
7826 let mut distinct: Vec<u32> = Vec::new();
7827 for id in orig.iter().chain(&sub_orig).flatten() {
7828 if !distinct.contains(id) {
7829 distinct.push(*id);
7830 }
7831 }
7832 // A cut on a *subset* of the lanes leaves the take's other members whole
7833 // on lanes that were not cut: the cut halves no longer agree with them
7834 // about their span, so the take is unlinked at the cut -- every member,
7835 // in this same snapshot (one undo puts it back).
7836 let detach = distinct.iter().any(|&id| {
7837 self.lanes.iter().enumerate().any(|(j, d)| {
7838 !on.contains(&j)
7839 && (d.clips.iter().any(|c| c.link == Some(id))
7840 || d.subs.iter().any(|s| s.link == Some(id)))
7841 })
7842 });
7843 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
7844 let right_of = |link: Option<u32>| {
7845 link.and_then(|id| distinct.iter().position(|&d| d == id))
7846 .map(|at| fresh[at])
7847 };
7848 for (l, data) in self.lanes.iter_mut().enumerate() {
7849 if !cut_subs[l] {
7850 continue;
7851 }
7852 // The pair the razor just made: they touch at the frame it cut.
7853 if let Some(idx) = data
7854 .subs
7855 .iter()
7856 .position(|s| s.end() == timeline_frame)
7857 .filter(|&idx| {
7858 data.subs
7859 .get(idx + 1)
7860 .is_some_and(|n| n.start == timeline_frame)
7861 })
7862 {
7863 data.subs[idx].link = sub_orig[l];
7864 data.subs[idx + 1].link = right_of(sub_orig[l]);
7865 }
7866 }
7867 for (data_i, data) in self.lanes.iter_mut().enumerate() {
7868 // The lanes this call was not scoped to are not cut, whatever their
7869 // own clips would allow.
7870 let Some(idx) =
7871 splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some())
7872 else {
7873 continue;
7874 };
7875 let mut tail = data.clips[idx].clone();
7876 // Where the cut lands *in the file*, which is the clip's own rate
7877 // away from where it lands on the timeline. Both halves keep the
7878 // speed, and `splittable` has already refused any frame at which
7879 // the two would not add up to the one being cut.
7880 let cut_at = split_source(&tail, timeline_frame).expect("splittable said so");
7881 let (head_speed, tail_speed) = split_keys(&tail, timeline_frame);
7882 tail.speed_keys = tail_speed;
7883 data.clips[idx].speed_keys = head_speed;
7884 let reversed = tail.reversed;
7885 match reversed {
7886 true => tail.out_frame = cut_at,
7887 false => tail.in_frame = cut_at,
7888 }
7889 tail.start = timeline_frame;
7890 // The placement animation is divided, not copied: each half keeps
7891 // its own keys and a key at the cut (see `split_transform_keys`). The
7892 // lower keys go to the tail of a reversed clip, which plays them last.
7893 let (below, above) = split_transform_keys(&data.clips[idx].transform_keys, cut_at);
7894 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7895 tail.transform_keys = tail_keys;
7896 data.clips[idx].transform_keys = head_keys;
7897 let (head_keys, tail_keys) =
7898 split_transform_keys(&data.clips[idx].opacity_keys, tail.in_frame);
7899 tail.opacity_keys = tail_keys;
7900 data.clips[idx].opacity_keys = head_keys;
7901 let (head_keys, tail_keys) =
7902 split_transform_keys(&data.clips[idx].color_keys, tail.in_frame);
7903 tail.color_keys = tail_keys;
7904 data.clips[idx].color_keys = head_keys;
7905 // Each mask's keys divide the same way as the placement's, per stack position.
7906 let masks: Vec<_> = data.clips[idx]
7907 .effects
7908 .iter()
7909 .map(|e| split_transform_keys(&e.keys, cut_at))
7910 .collect();
7911 for ((tail_e, head_e), (below, above)) in tail.effects.iter_mut().zip(data.clips[idx].effects.iter_mut()).zip(masks) {
7912 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7913 tail_e.keys = tail_keys;
7914 head_e.keys = head_keys;
7915 }
7916 tail.link = right_of(orig[data_i]);
7917 // A split makes a new edge for each half, and a fade is a promise
7918 // about an edge: only the half that *kept* the original edge
7919 // keeps that fade, re-clamped to its own now-shorter length (a
7920 // cut inside the ramp shortens it, never leaves it pointing past
7921 // the clip it is on); the edge the cut itself made starts, or
7922 // ends, flat -- there was no silence there to ramp out of.
7923 tail.fade_in = 0;
7924 tail.fade_out = tail.fade_out.min(tail.frames());
7925 // A dissolve is a promise about the *end* edge, same as
7926 // `fade_out`: only the half that kept the clip's original end
7927 // (the tail) keeps it, re-clamped to its own now-shorter length;
7928 // the head's new end is the cut the razor just made, which starts
7929 // flat -- there was no successor to dissolve into there.
7930 tail.transition_out = tail.transition_out.min(tail.frames());
7931 match reversed {
7932 true => data.clips[idx].in_frame = cut_at,
7933 false => data.clips[idx].out_frame = cut_at,
7934 }
7935 data.clips[idx].link = orig[data_i];
7936 data.clips[idx].fade_out = 0;
7937 data.clips[idx].transition_out = 0;
7938 data.clips[idx].transition_kind = Default::default();
7939 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
7940 data.clips.insert(idx + 1, tail);
7941 }
7942 if detach {
7943 // Every member of the take gets an id of its own, as `ungroup` gives
7944 // them: each half is detached (a lone id), never a whole take.
7945 let gone: Vec<u32> = distinct.iter().chain(&fresh).copied().collect();
7946 let count: usize = self
7947 .lanes
7948 .iter()
7949 .map(|d| {
7950 d.clips.iter().filter(|c| c.link.is_some_and(|id| gone.contains(&id))).count()
7951 + d.subs.iter().filter(|s| s.link.is_some_and(|id| gone.contains(&id))).count()
7952 })
7953 .sum();
7954 let mut own = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
7955 for data in &mut self.lanes {
7956 for c in data.clips.iter_mut().filter(|c| c.link.is_some_and(|id| gone.contains(&id))) {
7957 c.link = own.pop();
7958 }
7959 for s in data.subs.iter_mut().filter(|s| s.link.is_some_and(|id| gone.contains(&id))) {
7960 s.link = own.pop();
7961 }
7962 }
7963 }
7964 true
7965 }
7966
7967 /// The inverse of [`split`](Project::split): rejoin the placements that meet
7968 /// at `timeline_frame` in every lane and put the result back in one group.
7969 /// Only what a split could have produced is rejoined -- the two sides must
7970 /// touch on the timeline *and* be consecutive frames of the same source --
7971 /// so the clip list comes back exactly as it was and traversal with it.
7972 /// `false` when no lane has such a pair. The rejoined placement keeps the
7973 /// **left** half's id, which is the take the split left on it: rejoining a
7974 /// cut take puts the take back, id and all.
7975 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
7976 // What each lane would end up covering, if it joins here at all.
7977 let joined: Vec<Option<(u32, u32)>> = self
7978 .lanes
7979 .iter()
7980 .map(|l| {
7981 joinable(&l.clips, timeline_frame)
7982 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
7983 })
7984 .collect();
7985 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
7986 let join_subs: Vec<Option<usize>> = self
7987 .lanes
7988 .iter()
7989 .map(|l| sub_joinable(&l.subs, timeline_frame))
7990 .collect();
7991 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
7992 return false;
7993 }
7994 self.snapshot();
7995 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
7996 if let Some(idx) = sub {
7997 data.subs[idx].frames += data.subs[idx + 1].frames;
7998 // The left half's `in_us`, the right half's `out_us` -- which
7999 // is the SUM of two legal widths, because `sub_joinable` has
8000 // just established that the two halves are consecutive in the
8001 // *source* (`next.in_us == subs[idx].out_us`). Neither half
8002 // broke the ceiling and the whole does, so this is a composer
8003 // a per-arm check on one writer could never have found:
8004 // `set_window` is what makes the closed set closed.
8005 let (in_us, out_us) = (data.subs[idx].in_us, data.subs[idx + 1].out_us);
8006 set_window(&mut data.subs[idx], in_us, out_us);
8007 data.subs.remove(idx + 1);
8008 debug_assert!(subs_sorted_disjoint(&data.subs));
8009 }
8010 let Some(idx) = joinable(&data.clips, timeline_frame) else {
8011 continue;
8012 };
8013 match data.clips[idx].reversed {
8014 true => data.clips[idx].in_frame = data.clips[idx + 1].in_frame,
8015 false => data.clips[idx].out_frame = data.clips[idx + 1].out_frame,
8016 }
8017 data.clips.remove(idx + 1);
8018 }
8019 true
8020 }
8021
8022 /// Take the placement at `idx` of `lane` out of its group: every clip and
8023 /// every caption carrying its id -- on however many lanes -- is handed an
8024 /// id of its own, so from here on each half moves, trims and is deleted
8025 /// alone. The music video whose sound is to be cut against its picture
8026 /// starts here, and so does the caption that has to come off the picture it
8027 /// was pinned to.
8028 ///
8029 /// A group that holds more than one take gives each take back whole: a
8030 /// [`group`](Project::group_all) with a take member merges that take into
8031 /// the group, and one id cannot say which halves were a take before, so
8032 /// the halves are matched by what a take is -- clips with the same source,
8033 /// start and in/out points -- and each match keeps one id of its own. So
8034 /// ungrouping the picture of a take that was grouped with another clip
8035 /// leaves the take linked and detaches only the other clip. A group of one
8036 /// take, or one with a caption, is taken apart whole, as before.
8037 ///
8038 /// An id of its own rather than none at all: a half no other lane is grouped
8039 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
8040 /// (see [`links_are_consistent`]), and it is what a front-end already draws
8041 /// as detached. `None` would instead say "was never part of a take", which
8042 /// is what a one-lane [`place`](Project::place) means.
8043 ///
8044 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
8045 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
8046 /// the group back. Refused (`false`, nothing changed) for an index that is
8047 /// not there, a placement in no group at all, and one whose group has no
8048 /// other half -- that one is already detached, and a refusal must not cost
8049 /// an undo step.
8050 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
8051 let Some(members) = self.group_of(lane, idx) else {
8052 return false;
8053 };
8054 if members.alone() {
8055 return false;
8056 }
8057 let Some(id) = self
8058 .lane(lane)
8059 .get(idx)
8060 .and_then(|c| c.link)
8061 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
8062 else {
8063 return false;
8064 };
8065 self.snapshot();
8066 // The takes the group holds, by what a take is: its halves share these.
8067 let mut takes: Vec<TakeKey> = Vec::new();
8068 for data in &self.lanes {
8069 for c in data.clips.iter().filter(|c| c.link == Some(id)) {
8070 let k = take_key(c);
8071 if !takes.contains(&k) {
8072 takes.push(k);
8073 }
8074 }
8075 }
8076 let whole = takes.len() == 1 && members.subs.is_empty();
8077 // Drawn before the walk: `new_link` takes the whole project, and the
8078 // walk holds the lanes. One id per take (or per clip, when the group is
8079 // one take that comes apart), then one per caption.
8080 let clip_ids = if whole { members.clips.len() } else { takes.len() };
8081 let mut fresh = (0..clip_ids + members.subs.len()).map(|_| self.new_link()).collect::<Vec<_>>();
8082 let mut sub_fresh = fresh.split_off(clip_ids).into_iter();
8083 let mut next = 0;
8084 for data in &mut self.lanes {
8085 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
8086 c.link = Some(if whole {
8087 next += 1;
8088 fresh[next - 1]
8089 } else {
8090 let k = take_key(c);
8091 fresh[takes.iter().position(|t| *t == k).expect("collected above")]
8092 });
8093 }
8094 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
8095 s.link = sub_fresh.next();
8096 }
8097 }
8098 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8099 true
8100 }
8101
8102 /// Put two clips on two lanes into one group, so what moves one moves the
8103 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
8104 /// how a picture is regrouped with sound it was never opened with. Whatever
8105 /// either of them was grouped with comes along: those clips cover this same
8106 /// span already, so the result is one group and not two overlapping ones.
8107 ///
8108 /// Same frames or nothing: a group id names **one span** on however many
8109 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
8110 /// clips that do not cover the same frames cannot be one take, and the
8111 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
8112 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
8113 /// mean, not the rule.
8114 ///
8115 /// Metadata only, one snapshot. The error says what is wrong, because
8116 /// `false` would not: a bad index, one lane twice (a group is at most one
8117 /// clip per lane), spans that disagree, and a pair that is already one take
8118 /// -- nothing changes, and none of them costs an undo step.
8119 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
8120 if a == b {
8121 return Err(format!(
8122 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
8123 a.label()
8124 )
8125 .into());
8126 }
8127 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
8128 p.lane(lane)
8129 .get(idx)
8130 .cloned()
8131 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
8132 };
8133 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
8134 if (x.start, x.end()) != (y.start, y.end()) {
8135 return Err(format!(
8136 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
8137 a.label(),
8138 x.start,
8139 x.end(),
8140 b.label(),
8141 y.start,
8142 y.end()
8143 )
8144 .into());
8145 }
8146 if x.link.is_some() && x.link == y.link {
8147 return Err("those two are one take already".into());
8148 }
8149 self.snapshot();
8150 let id = self.new_link();
8151 // Every clip either of them was grouped with, by the same rule: all of
8152 // them cover this span, so one id over the lot stays consistent.
8153 let old = [x.link, y.link];
8154 for data in &mut self.lanes {
8155 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
8156 if old.contains(&c.link) {
8157 c.link = Some(id);
8158 }
8159 }
8160 }
8161 // And the two themselves, which a `place` may have left in no group.
8162 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
8163 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
8164 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8165 Ok(())
8166 }
8167
8168 /// Put every placement the picks name into one group -- the group a hand
8169 /// builds with ctrl-click and a menu: the picture, its sound and the
8170 /// caption over it, on as many lanes as the picks name. What any of them
8171 /// was already grouped with rides along (one group, not two sharing a
8172 /// member), and the members keep their own spans: a group is one id over
8173 /// one placement per lane, and the offsets between them are what the group
8174 /// preserves -- a drag, a trim and a delete all move the members *by the
8175 /// same distance*, not to the same frames.
8176 ///
8177 /// No two picks may name one lane -- that is the one clip-per-lane rule,
8178 /// and the refusal says which lane -- and a pick that names nothing is
8179 /// refused with its own words. At least two picks, or there is nothing to
8180 /// group.
8181 ///
8182 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
8183 /// apart again. None of the refusals changes anything or costs an undo
8184 /// step.
8185 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
8186 if picks.len() < 2 {
8187 return Err("a group is two placements or more: pick another one first".into());
8188 }
8189 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
8190 for &(lane, idx) in picks {
8191 if seen.contains(&lane) {
8192 return Err(format!(
8193 "a group is one placement per lane: {} is picked twice -- keep one clip per \
8194 track",
8195 lane.label()
8196 )
8197 .into());
8198 }
8199 seen.push(lane);
8200 let there = if lane.kind == LaneKind::Subtitle {
8201 idx < self.sub_lane(lane).len()
8202 } else {
8203 idx < self.lane(lane).len()
8204 };
8205 if !there {
8206 let what = if lane.kind == LaneKind::Subtitle {
8207 "subtitle"
8208 } else {
8209 "clip"
8210 };
8211 return Err(format!("there is no {what} {idx} on {}", lane.label()).into());
8212 }
8213 }
8214 let links: Vec<Option<u32>> = picks
8215 .iter()
8216 .map(|&(lane, idx)| {
8217 if lane.kind == LaneKind::Subtitle {
8218 self.sub_lane(lane)[idx].link
8219 } else {
8220 self.lane(lane)[idx].link
8221 }
8222 })
8223 .collect();
8224 // The picks are already one per lane (`seen`, above), but a pick's
8225 // *existing* group can carry a second member onto a lane another
8226 // pick (or another existing group in the merge) already occupies --
8227 // two captions on one sub lane, say, each grouped with a different
8228 // clip before this call. Merging both in would leave that lane with
8229 // two members of one id, which `links_are_consistent` may never see:
8230 // refused by name, before anything moves, rather than a group closed
8231 // broken.
8232 let labels = handles(&self.lanes);
8233 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
8234 for (li, data) in self.lanes.iter().enumerate() {
8235 let n = data
8236 .clips
8237 .iter()
8238 .filter(|c| c.link.is_some() && links.contains(&c.link))
8239 .count()
8240 + data
8241 .subs
8242 .iter()
8243 .filter(|s| s.link.is_some() && links.contains(&s.link))
8244 .count();
8245 if n > 0 {
8246 per_lane.insert(li, n as u32);
8247 }
8248 }
8249 // A pick that carries no link of its own is invisible to the scan
8250 // above (there is no `Some` to match): it still claims its lane.
8251 for &(lane, _) in picks {
8252 let li = self.index(lane).expect("checked above");
8253 per_lane.entry(li).or_insert(0);
8254 if !self.lanes[li]
8255 .clips
8256 .iter()
8257 .any(|c| c.link.is_some() && links.contains(&c.link))
8258 && !self.lanes[li]
8259 .subs
8260 .iter()
8261 .any(|s| s.link.is_some() && links.contains(&s.link))
8262 {
8263 *per_lane.get_mut(&li).expect("just inserted") += 1;
8264 }
8265 }
8266 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
8267 return Err(format!(
8268 "a group is one placement per lane: merging these groups would put two on {}",
8269 labels[li].label()
8270 )
8271 .into());
8272 }
8273 self.snapshot();
8274 let id = self.new_link();
8275 // Whatever any pick was grouped with comes along, for [`group`]'s
8276 // reason -- one id over the lot, not two groups sharing a member.
8277 for data in &mut self.lanes {
8278 for c in data.clips.iter_mut() {
8279 if c.link.is_some() && links.contains(&c.link) {
8280 c.link = Some(id);
8281 }
8282 }
8283 for s in data.subs.iter_mut() {
8284 if s.link.is_some() && links.contains(&s.link) {
8285 s.link = Some(id);
8286 }
8287 }
8288 }
8289 // And the picks themselves, which a `place` may have left in no group.
8290 // The lane seats are read before the walk, which holds the lanes.
8291 let seats: Vec<(usize, bool)> = picks
8292 .iter()
8293 .map(|&(lane, _)| {
8294 (
8295 self.index(lane).expect("checked above"),
8296 lane.kind == LaneKind::Subtitle,
8297 )
8298 })
8299 .collect();
8300 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
8301 let _ = lane;
8302 if sub {
8303 self.lanes[at].subs[idx].link = Some(id);
8304 } else {
8305 self.lanes[at].clips[idx].link = Some(id);
8306 }
8307 }
8308 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8309 Ok(())
8310 }
8311
8312 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
8313 /// lands on and leaving every other clip exactly where it is -- the
8314 /// per-lane paste. Anything already there is trimmed away (and split in two
8315 /// if `clip` lands inside it), which is what keeps the lane sorted and
8316 /// disjoint; nothing ripples, so a gap before the placement simply stays a
8317 /// gap. Refused only for an empty `clip`.
8318 ///
8319 /// The placement belongs to no group: a clipboard clip carries the link id
8320 /// of the take it was copied from, and placing it twice -- or placing a copy
8321 /// back over the clip it came from -- would put that id on two clips of one
8322 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
8323 /// `None` rather than a fresh id because a one-lane placement has nothing on
8324 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
8325 /// become a group again.
8326 ///
8327 /// Refused for an empty `clip`, for a lane that is not there, and for a
8328 /// subtitle lane, which carries no picture and no sound
8329 /// ([`Project::place_sub`] is its door).
8330 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
8331 if clip.out_frame <= clip.in_frame
8332 || lane.kind == LaneKind::Subtitle
8333 || self.index(lane).is_none()
8334 || self.cycles(&clip)
8335 {
8336 return false;
8337 }
8338 self.snapshot();
8339 let clip = Clip {
8340 fade_in: 0,
8341 fade_out: 0,
8342 transition_out: 0,
8343 transition_kind: Default::default(),
8344 start: timeline_frame,
8345 link: None,
8346 ..clip
8347 };
8348 self.insert_over(lane, clip, &[]);
8349 true
8350 }
8351
8352 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
8353 /// one grouped take -- what a picture let go over a further video track
8354 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
8355 /// if it is not there yet (the `+ V` button adds a video row alone). Without
8356 /// this half a file with sound landed on a layer silent, and the only way to
8357 /// hear it was to drop it a second time on an audio lane.
8358 ///
8359 /// Both halves overwrite what they land on and neither ripples, exactly as
8360 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
8361 /// nothing under it moves. One history snapshot for the pair, the added lane
8362 /// included, so one [`Project::undo`] takes the whole placement back. The two
8363 /// carry one link, which is what makes them one take to a drag, a trim and a
8364 /// save.
8365 ///
8366 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
8367 /// there or is not a video lane: sound placed alone is
8368 /// [`place`](Project::place)'s door, and a still has no sound to pair.
8369 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
8370 if clip.out_frame <= clip.in_frame
8371 || lane.kind != LaneKind::Video
8372 || self.index(lane).is_none()
8373 || self.cycles(&clip)
8374 {
8375 return false;
8376 }
8377 self.snapshot();
8378 // `A2` for `V2` -- and the rows between it and the last audio lane, since
8379 // an ord names a lane only while every ord below it does.
8380 while self.lane_count(LaneKind::Audio) <= lane.ord {
8381 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
8382 }
8383 let clip = Clip {
8384 fade_in: 0,
8385 fade_out: 0,
8386 transition_out: 0,
8387 transition_kind: Default::default(),
8388 start: timeline_frame,
8389 link: Some(self.new_link()),
8390 ..clip
8391 };
8392 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
8393 self.insert_over(half, clip.clone(), &[]);
8394 }
8395 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8396 true
8397 }
8398
8399 /// A source range onto the timeline at `at`, the way an editor's
8400 /// three-point edit puts it: `items` are the `(lane, clip)` halves of one
8401 /// take (a picture on a video lane, its sound on an audio lane, or either
8402 /// alone), each landing with its head on `at` whatever `clip.start` says.
8403 ///
8404 /// * [`SourceEdit::Overwrite`] replaces what is there for the take's length:
8405 /// a clip it covers is trimmed or split around it, and nothing moves.
8406 /// * [`SourceEdit::Insert`] opens room first: on the lanes the items land
8407 /// on, a clip `at` falls inside is cut there and everything from `at` on
8408 /// moves later by the take's length. Lanes that are not item lanes do not
8409 /// move and are never cut -- so, as in a scoped ripple
8410 /// ([`Project::scope_holds_takes_whole`]), a take that would be pulled
8411 /// apart by it (one half on an item lane, the other not) refuses the
8412 /// insert by name. Captions keep their own clock, as a paste leaves them.
8413 ///
8414 /// The halves share one fresh link when there are several and run the same
8415 /// length; a lone half belongs to no group. Exactly one history snapshot,
8416 /// so one [`Project::undo`] takes the whole edit back. Changes the
8417 /// timeline->source mapping: the caller must reseek.
8418 ///
8419 /// Refused, changing nothing and costing no undo step, for no items, a lane
8420 /// that is not there, is locked or is a caption lane, a lane twice, a source
8421 /// that is not there or cannot play on the lane (a song on a video lane, a
8422 /// still on an audio one), an empty range, a start or ripple that would pass
8423 /// the last frame there is, and an insert inside a speeded clip at a frame
8424 /// its rate cannot cut.
8425 pub fn edit_from_source(&mut self, kind: SourceEdit, at: u32, items: &[(Lane, Clip)]) -> crate::Result<()> {
8426 if items.is_empty() {
8427 return Err("nothing to place".into());
8428 }
8429 let labels = handles(&self.lanes);
8430 let mut on: Vec<usize> = Vec::with_capacity(items.len());
8431 for (lane, clip) in items {
8432 let Some(i) = self.index(*lane) else {
8433 return Err(format!("no {} track on this timeline", lane.label()).into());
8434 };
8435 if lane.kind == LaneKind::Subtitle {
8436 return Err(format!("{} is a caption track: a source cannot go on it", labels[i].label()).into());
8437 }
8438 if on.contains(&i) {
8439 return Err(format!("{} is named twice", labels[i].label()).into());
8440 }
8441 if self.lanes[i].locked {
8442 return Err(format!("{} is locked: unlock it to edit it", labels[i].label()).into());
8443 }
8444 if is_sequence_source(clip.source) {
8445 return Err("a sequence is placed with the sequence ops, not as a source".into());
8446 }
8447 let Some(source) = self.sources.get(clip.source) else {
8448 return Err("that source is not in the project".into());
8449 };
8450 if clip.out_frame <= clip.in_frame {
8451 return Err("the range to place is empty".into());
8452 }
8453 if lane.kind == LaneKind::Video && crate::is_audio(&source.path) {
8454 return Err(format!("that source has no picture: it cannot go on {}", labels[i].label()).into());
8455 }
8456 if lane.kind == LaneKind::Audio && crate::is_image(&source.path) {
8457 return Err(format!("a still has no sound: it cannot go on {}", labels[i].label()).into());
8458 }
8459 on.push(i);
8460 }
8461 let len = items.iter().map(|(_, c)| c.frames()).max().unwrap_or(0);
8462 if len == 0 || at.checked_add(len).is_none() {
8463 return Err("the range to place is empty or runs past the last frame there is".into());
8464 }
8465 if kind == SourceEdit::Insert {
8466 for &i in &on {
8467 let clips = &self.lanes[i].clips;
8468 if clips.iter().any(|c| c.end() > at && c.end().checked_add(len).is_none()) {
8469 return Err("the insert would push a clip past the last frame there is".into());
8470 }
8471 if clips.iter().any(|c| c.start < at && at < c.end()) && splittable(clips, at).is_none() {
8472 return Err(format!(
8473 "{} cannot be cut at frame {at}: the clip there plays at a rate that has no source frame at it; pick a neighbouring frame",
8474 labels[i].label()
8475 )
8476 .into());
8477 }
8478 }
8479 self.scope_holds_takes_whole(&on, at)?;
8480 }
8481 self.snapshot();
8482 if kind == SourceEdit::Insert {
8483 self.write_split(at, false, &on);
8484 for &i in &on {
8485 for c in self.lanes[i].clips.iter_mut().filter(|c| c.start >= at) {
8486 c.start += len;
8487 }
8488 }
8489 }
8490 let link = (items.len() > 1 && items.iter().all(|(_, c)| c.frames() == len)).then(|| self.new_link());
8491 // A take the overwrite cuts through keeps its take, when every member of it sits on a lane
8492 // this edit writes: each member is then cut at the same frames, so the head keeps the id and
8493 // the tail takes one fresh id shared by them all. A take with a member on a lane left alone
8494 // would be cut out of step with it, so it is detached as a delete detaches it.
8495 let end = at + len;
8496 let mut straddled: Vec<u32> = Vec::new();
8497 for &i in &on {
8498 for c in &self.lanes[i].clips {
8499 if let Some(id) = c.link.filter(|_| c.start < end && c.end() > at)
8500 && !straddled.contains(&id)
8501 {
8502 straddled.push(id);
8503 }
8504 }
8505 }
8506 let mut keep: Vec<(u32, u32)> = Vec::new();
8507 for id in straddled {
8508 let whole = self
8509 .lanes
8510 .iter()
8511 .enumerate()
8512 .all(|(j, d)| on.contains(&j) || !d.clips.iter().any(|c| c.link == Some(id)));
8513 if whole {
8514 keep.push((id, self.new_link()));
8515 }
8516 }
8517 for (lane, clip) in items {
8518 let clip = Clip {
8519 fade_in: 0,
8520 fade_out: 0,
8521 transition_out: 0,
8522 transition_kind: Default::default(),
8523 start: at,
8524 link,
8525 ..clip.clone()
8526 };
8527 self.insert_over(*lane, clip, &keep);
8528 }
8529 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8530 Ok(())
8531 }
8532
8533 /// `clip` into `lane` at its own start, over whatever it lands on: the
8534 /// insert both placement doors make, which is what keeps a lane sorted and
8535 /// disjoint. The caller has checked that the lane is there.
8536 fn insert_over(&mut self, lane: Lane, clip: Clip, keep: &[(u32, u32)]) {
8537 let clips = self.lane_mut(lane).expect("the caller checked the lane");
8538 // The pieces a cut leaves keep their take where `keep` says so (see `edit_from_source`);
8539 // everywhere else a straddled clip's pieces are detached.
8540 clear_with(clips, clip.start, clip.end(), &mut |link| match link.and_then(|id| keep.iter().find(|k| k.0 == id)) {
8541 Some(&(head, tail)) => (Some(head), Some(tail)),
8542 None => (None, None),
8543 });
8544 let idx = clips.partition_point(|c| c.start < clip.start);
8545 clips.insert(idx, clip);
8546 debug_assert!(sorted_disjoint(clips));
8547 }
8548
8549 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
8550 /// frame `start`: the drag that rearranges takes, along a track and across
8551 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
8552 /// was. `start` at the clip's own is the pure lane change.
8553 ///
8554 /// The whole group travels the same distance, each half on the lane it
8555 /// already sits on -- a link means "these cover one span on however many
8556 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
8557 /// sound would be a group no save could load. Only the dragged half changes
8558 /// lane, and that is not a desync: a link names no lane at all.
8559 ///
8560 /// `start` is **clamped**, never refused, to the room the group has: no
8561 /// member crosses a neighbour on the lane it lands on, exactly as
8562 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
8563 /// dragging past a neighbour means "as far as it goes", and butting up
8564 /// against the take next door is how clips are laid end to end. The
8565 /// tightest member's wall wins, so a sound half boxed in between two others
8566 /// holds its picture still.
8567 ///
8568 /// Refused, changing nothing and costing no undo step, for a lane that is
8569 /// not there, an index that is not there, a move across *kinds* (a picture
8570 /// cannot play on an audio lane, and the save it wrote would not open
8571 /// again), a head let go *inside* another clip or into a gap too narrow to
8572 /// hold this one -- a move that overwrote what it landed on would destroy a
8573 /// take the pointer never named, which is what [`place`](Project::place)
8574 /// may do and a drag may not -- a half let go onto the lane its own partner
8575 /// is on, and a drop that changes neither lane nor frame, which is a clip
8576 /// picked up and put back down, i.e. a click.
8577 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
8578 self.move_selection(&[(from, idx)], from, idx, to, start)
8579 }
8580
8581 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
8582 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
8583 /// reads it) travels the same distance as the clip at `idx` of `from`,
8584 /// which alone changes lane, onto `to`. One clamp across the whole set
8585 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
8586 /// neighbour that boxes in *any* member narrows the delta every member
8587 /// moves by, and a member with no room at all (`lo > hi`) refuses the
8588 /// whole set rather than moving the rest and leaving that one behind.
8589 /// `move_clip` is this with a selection of one -- the dragged clip's own
8590 /// group and nothing else -- so a drag on a clip outside the selection is
8591 /// byte-identical to before this existed.
8592 pub fn move_selection(
8593 &mut self,
8594 picks: &[(Lane, usize)],
8595 from: Lane,
8596 idx: usize,
8597 to: Lane,
8598 start: u32,
8599 ) -> bool {
8600 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).cloned()) else {
8601 return false;
8602 };
8603 if from.kind != to.kind {
8604 return false;
8605 }
8606 let held = self.index(from).expect("the clip was found on it");
8607 // Every pick's own group, unioned: the whole selection moves as one,
8608 // and a pick's link partners (not themselves picked) come along with
8609 // it exactly as a lone drag's do.
8610 let mut members = Members::default();
8611 for &(lane, i) in picks {
8612 let Some(group) = self.group_of(lane, i) else {
8613 continue;
8614 };
8615 for m in group.clips {
8616 if !members.clips.contains(&m) {
8617 members.clips.push(m);
8618 }
8619 }
8620 for m in group.subs {
8621 if !members.subs.contains(&m) {
8622 members.subs.push(m);
8623 }
8624 }
8625 }
8626 if !members.clips.contains(&(held, idx)) {
8627 members.clips.push((held, idx));
8628 }
8629 // The two halves of *the dragged clip's own* group would land on one
8630 // span of one lane, which is the one thing a link may never mean --
8631 // checked against that group alone, not the whole moving set: an
8632 // unlinked fellow pick already sitting on `dest` is no conflict at
8633 // all, since it travels by the same delta and `move_room` below
8634 // leaves it the room to. Refused rather than clamped: the partner
8635 // moves the same distance, so there is no room for it anywhere on
8636 // that lane.
8637 let own_group = self.group_of(from, idx).expect("the clip was found");
8638 if dest != held
8639 && own_group
8640 .clips
8641 .iter()
8642 .chain(&own_group.subs)
8643 .any(|&(l, _)| l == dest)
8644 {
8645 return false;
8646 }
8647 let want = i64::from(start) - i64::from(clip.start);
8648 // First the placement as asked: every member's span shifted by the one
8649 // delta the pointer named, each read against the gap it would land in.
8650 // A drop on empty frames lands exactly there -- jumping over whatever
8651 // clips lie between, on its lane and its linked partners' -- and only
8652 // a member whose new span would meet another clip refuses it.
8653 let as_asked = self
8654 .move_room(&members, Some((held, idx, dest, start)), Some(want))
8655 .filter(|&(lo, hi)| lo <= want && want <= hi);
8656 // Otherwise the drag as it always was: how far the group may travel,
8657 // in timeline frames and signed, with every member narrowing it to the
8658 // gap it stands in (its own lane, or the lane the pointer let it go
8659 // over), and what is left is what the pointer is clamped to.
8660 let Some((lo, hi)) = as_asked.or_else(|| {
8661 self.move_room(&members, Some((held, idx, dest, start)), None)
8662 }) else {
8663 return false;
8664 };
8665 if lo > hi {
8666 return false;
8667 }
8668 let delta = want.clamp(lo, hi);
8669 if delta == 0 && dest == held {
8670 return false;
8671 }
8672 self.snapshot();
8673 for &(l, i) in &members.clips {
8674 let c = &mut self.lanes[l].clips[i];
8675 // In range by the walls above, which are `u32` frames throughout.
8676 c.start = (i64::from(c.start) + delta) as u32;
8677 }
8678 for &(l, i) in &members.subs {
8679 let s = &mut self.lanes[l].subs[i];
8680 s.start = (i64::from(s.start) + delta) as u32;
8681 }
8682 if dest != held {
8683 let clip = self.lanes[held].clips.remove(idx);
8684 let clips = &mut self.lanes[dest].clips;
8685 let at = clips.partition_point(|c| c.start < clip.start);
8686 clips.insert(at, clip);
8687 }
8688 // A jump can carry a member past clips it did not pass before, on its
8689 // own lane as much as onto another, so every lane the set touched is
8690 // put back in order. The members keep their spacing among themselves
8691 // (one delta), so the order is all that can have changed.
8692 let mut touched: Vec<usize> = members
8693 .clips
8694 .iter()
8695 .chain(&members.subs)
8696 .map(|&(l, _)| l)
8697 .chain([dest])
8698 .collect();
8699 touched.sort_unstable();
8700 touched.dedup();
8701 for l in touched {
8702 self.lanes[l].clips.sort_by_key(|c| c.start);
8703 self.lanes[l].subs.sort_by_key(|s| s.start);
8704 }
8705 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
8706 debug_assert!(members.clips.iter().chain(&members.subs).all(|&(l, _)| {
8707 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
8708 }));
8709 true
8710 }
8711
8712 /// How far a group drag may travel, `(least, most)` in timeline frames and
8713 /// signed: every member narrows the range to the gap it is landing in --
8714 /// the clips against their lanes' clips and the captions against their
8715 /// lanes' captions -- and what is left is what the pointer is clamped to.
8716 /// `travelling` names the one member that changes lane, if any: the clip a
8717 /// hand is carrying onto another track, whose walls are read on the lane it
8718 /// is let go over at the frame the pointer named. `None` when a member has
8719 /// no gap to land in at all.
8720 ///
8721 /// `requested`, when given, reads every member's walls where it would sit
8722 /// with the whole group shifted by that many frames, rather than where it
8723 /// stands; a member whose requested spot is inside another placement, or
8724 /// has no gap wide enough, is `None`.
8725 fn move_room(
8726 &self,
8727 members: &Members,
8728 travelling: Option<(usize, usize, usize, u32)>,
8729 requested: Option<i64>,
8730 ) -> Option<(i64, i64)> {
8731 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
8732 for &(l, i) in members.clips.iter().chain(&members.subs) {
8733 let sub = members.subs.contains(&(l, i));
8734 let (start, frames) = match self.lanes[l]
8735 .clips
8736 .get(i)
8737 .filter(|_| !sub)
8738 .map(|c| (c.start, c.frames()))
8739 {
8740 Some(pair) => pair,
8741 None => {
8742 let s = self.lanes[l].subs.get(i)?;
8743 (s.start, s.frames)
8744 }
8745 };
8746 let land = travelling
8747 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
8748 .map_or(l, |(_, _, dest, _)| dest);
8749 // Which gap this member's walls are read off: its own place on the
8750 // lane it stays on, and the frame the pointer named on the lane it
8751 // is let go over. A clip's neighbours are the clips of the lane it
8752 // lands on and a caption's are its captions -- the two lists of one
8753 // lane never meet.
8754 let at = match (requested, travelling) {
8755 (Some(shift), _) => match u32::try_from(i64::from(start) + shift) {
8756 Ok(at) => at,
8757 Err(_) => return None,
8758 },
8759 (None, Some((fl, fi, _, asked))) if (fl, fi) == (l, i) && land != l => asked,
8760 (None, _) => start,
8761 };
8762 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
8763 let neighbours: Vec<(u32, u32)> = if sub {
8764 self.lanes[land]
8765 .subs
8766 .iter()
8767 .map(|s| (s.start, s.end()))
8768 .collect()
8769 } else {
8770 self.lanes[land]
8771 .clips
8772 .iter()
8773 .map(|c| (c.start, c.end()))
8774 .collect()
8775 };
8776 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
8777 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
8778 continue;
8779 }
8780 if *other_start <= at && at < *other_end {
8781 // A head let go inside another placement, which a clamp
8782 // has no answer for: the drop is refused.
8783 return None;
8784 }
8785 match other_end <= &at {
8786 true => wall_lo = wall_lo.max(*other_end),
8787 false => wall_hi = wall_hi.min(*other_start),
8788 }
8789 }
8790 if wall_hi - wall_lo < frames {
8791 return None;
8792 }
8793 lo = lo.max(i64::from(wall_lo) - i64::from(start));
8794 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
8795 }
8796 Some((lo, hi))
8797 }
8798
8799 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
8800 /// the drag on a clip's end that makes it play more or less of its source.
8801 /// The rest of the lane stays exactly where it is (nothing ripples), so what
8802 /// a shortened clip leaves behind is a gap and what a lengthened one takes
8803 /// is room that was already empty. One snapshot, so a whole drag is one
8804 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
8805 /// sample. Changes the timeline->source mapping: the caller must reseek.
8806 ///
8807 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
8808 /// exactly what they played before, which is what makes this a trim and not
8809 /// a slip.
8810 ///
8811 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
8812 /// legal means "as far as it goes", and stopping the box there is the
8813 /// affordance. The walls are: one frame of clip always survives, an edge
8814 /// never crosses the neighbouring clip on its own lane, an in-point never
8815 /// walks back past the source's first frame, and an out-point never runs
8816 /// past `source_frames[clip.source]` -- the caller's table of how long each
8817 /// source actually is ([`Project`] does not know, and a clip ending past its
8818 /// file's last frame is a save that will not open again; see
8819 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
8820 /// there may not grow at all.
8821 ///
8822 /// Linked placements trim *together*, by one delta: every member's same
8823 /// edge moves the distance the dragged one did, clamped to the room its
8824 /// own walls leave -- offsets between the members of a hand-built group
8825 /// survive the trim, exactly as they survive a drag.
8826 ///
8827 /// `false`, changing nothing and costing no undo step, for an index that is
8828 /// not there and for an edge that is already where it was asked to go.
8829 pub fn trim(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, source_frames: &[u32]) -> bool {
8830 self.trim_with_walls(lane, idx, edge, to, SourceWalls::same(source_frames))
8831 }
8832
8833 /// [`trim`](Project::trim) measured against each lane's own table
8834 /// ([`SourceWalls`]): what a linked take needs, since its audio and picture
8835 /// members end on different frames.
8836 pub fn trim_with_walls(
8837 &mut self,
8838 lane: Lane,
8839 idx: usize,
8840 edge: Edge,
8841 to: u32,
8842 walls: SourceWalls<'_>,
8843 ) -> bool {
8844 let (Some((lo, hi)), Some(clip)) = (
8845 self.trim_room_with_walls(lane, idx, edge, walls),
8846 self.lane(lane).get(idx).cloned(),
8847 ) else {
8848 return false;
8849 };
8850 let to = to.clamp(lo, hi);
8851 let at = match edge {
8852 Edge::Start => clip.start,
8853 Edge::End => clip.end(),
8854 };
8855 if to == at {
8856 return false;
8857 }
8858 // Worked out before anything moves: at a slow rate a room can be too
8859 // narrow to hold even one source frame ([`Speed::fit`]), and the
8860 // dragged clip refusing to fit must refuse the whole gesture rather
8861 // than be given a range wider than its room -- which is the overlap
8862 // the lane invariant exists to forbid. The walls below leave that room,
8863 // so this is the backstop for a project that came in through another
8864 // door.
8865 // A ramp's head is not moved yet: its keys are measured from the clip's own
8866 // start, so a head trim would have to rebase them. Refused, as a split is.
8867 if matches!(edge, Edge::Start) && !clip.speed_keys.is_empty() {
8868 return false;
8869 }
8870 let room = match edge {
8871 // The frames that stay play what they played, so what survives is
8872 // measured from the *end*.
8873 Edge::Start => clip.end() - to,
8874 Edge::End => to - clip.start,
8875 };
8876 let Some(keep) = clip.fit_source(room) else {
8877 return false;
8878 };
8879 // An end edge never keeps more source than the source has past the
8880 // in-point: [`Speed::fit`] rounds by the same footprint the wall does, so
8881 // at a fast rate it can name one frame past the source's end, one the wall
8882 // (`clip_walls`) never offers. Held to the wall, the edit it commits is
8883 // the edit a save will accept.
8884 let keep = keep.min(keep_cap(&clip, edge, walls.for_kind(lane.kind)));
8885 let members = self.group_of(lane, idx).expect("checked above");
8886 self.snapshot();
8887 let still = self.is_still(&clip);
8888 let held = self.index(lane).expect("checked above");
8889 write_trim(&mut self.lanes[held].clips[idx], edge, to, keep, still);
8890 rekey_trimmed(&mut self.lanes[held].clips[idx], &clip, edge, still);
8891 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
8892 self.follow_group(
8893 &members,
8894 &(held, idx),
8895 edge,
8896 i64::from(to) - i64::from(at),
8897 walls,
8898 );
8899 true
8900 }
8901
8902 /// **Ripple trim**: [`trim`](Project::trim), except that the hole the trim leaves is closed
8903 /// (or opened) and what comes after moves with the edge, as Premiere's ripple trim does. A
8904 /// start edge keeps the clip where it began and cuts its head out, so the clips behind it
8905 /// move up by as much; an end edge moves what follows by the length it gained or lost. A
8906 /// linked member moves the same way on its own lane. The room an end edge may grow into is
8907 /// still the room its neighbour leaves, as a plain trim's is. One undo step.
8908 pub fn ripple_trim(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, source_frames: &[u32]) -> bool {
8909 self.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls::same(source_frames))
8910 }
8911
8912 /// [`ripple_trim`](Project::ripple_trim) measured against each lane's own table
8913 /// ([`SourceWalls`]), as [`trim_with_walls`](Project::trim_with_walls) is.
8914 pub fn ripple_trim_with_walls(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, walls: SourceWalls<'_>) -> bool {
8915 let Some(members) = self.group_of(lane, idx) else {
8916 return false;
8917 };
8918 let before: Vec<(usize, usize, u32, u32)> = members
8919 .clips
8920 .iter()
8921 .filter_map(|&(l, i)| self.lanes[l].clips.get(i).map(|c| (l, i, c.start, c.end())))
8922 .collect();
8923 if !self.trim_with_walls(lane, idx, edge, to, walls) {
8924 return false;
8925 }
8926 for (l, i, old_start, old_end) in before {
8927 let clip = &self.lanes[l].clips[i];
8928 let (new_start, new_end) = (clip.start, clip.end());
8929 match edge {
8930 Edge::Start => {
8931 // The head went (or came back): the clip starts where it did, and the
8932 // hole between it and what it was cut from closes behind it.
8933 let g = i64::from(new_start) - i64::from(old_start);
8934 if g != 0 {
8935 // Back in place first: `shift_behind` checks the whole lane, and the clip
8936 // still starting at the trimmed head would overlap what moves up.
8937 self.lanes[l].clips[i].start = old_start;
8938 shift_behind(&mut self.lanes[l], old_end, -g);
8939 }
8940 }
8941 Edge::End => {
8942 let g = i64::from(new_end) - i64::from(old_end);
8943 if g != 0 {
8944 shift_behind(&mut self.lanes[l], old_end, g);
8945 }
8946 }
8947 }
8948 }
8949 true
8950 }
8951
8952 /// The rest of a group after one member's `edge` has moved by `delta`:
8953 /// every other member's same edge moves the same distance, clamped to the
8954 /// room its own walls leave -- a clip's against its lane and its source,
8955 /// a caption's against its own lane, its window following by the
8956 /// placement's own proportion. The undo step is the caller's: this is the
8957 // second half of one edit, not an edit of its own.
8958 fn follow_group(
8959 &mut self,
8960 members: &Members,
8961 dragged: &(usize, usize),
8962 edge: Edge,
8963 delta: i64,
8964 walls: SourceWalls<'_>,
8965 ) {
8966 for &(l, i) in &members.clips {
8967 if (l, i) == *dragged {
8968 continue;
8969 }
8970 let old = self.lanes[l].clips[i].clone();
8971 let c = &old;
8972 let at = match edge {
8973 Edge::Start => c.start,
8974 Edge::End => c.end(),
8975 };
8976 let (lo, hi) = self.clip_room(l, i, edge, walls);
8977 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
8978 if to == at {
8979 continue;
8980 }
8981 let room = match edge {
8982 Edge::Start => c.end() - to,
8983 Edge::End => to - c.start,
8984 };
8985 if matches!(edge, Edge::Start) && !c.speed_keys.is_empty() {
8986 continue;
8987 }
8988 let Some(keep) = c.fit_source(room) else {
8989 continue;
8990 };
8991 // Held to the member's own source, as the dragged clip is.
8992 let keep = keep.min(keep_cap(c, edge, walls.for_kind(self.lanes[l].kind)));
8993 let still = self.is_still(&self.lanes[l].clips[i]);
8994 write_trim(&mut self.lanes[l].clips[i], edge, to, keep, still);
8995 rekey_trimmed(&mut self.lanes[l].clips[i], &old, edge, still);
8996 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
8997 }
8998 for &(l, i) in &members.subs {
8999 if (l, i) == *dragged {
9000 continue;
9001 }
9002 let s = self.lanes[l].subs[i];
9003 let at = match edge {
9004 Edge::Start => s.start,
9005 Edge::End => s.end(),
9006 };
9007 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
9008 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
9009 if to == at {
9010 continue;
9011 }
9012 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
9013 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
9014 }
9015 }
9016
9017 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
9018 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
9019 /// What a front-end drawing the box *during* a drag asks, so the live width
9020 /// is the width the release will commit and an edge stops under the pointer
9021 /// rather than snapping back. The **clip's own** walls: the rest of its
9022 /// group follows by the same delta within their own ([`follow_group`]), so
9023 /// what is drawn for the dragged edge is what its own clip will commit.
9024 /// `None` for an index that is not there.
9025 pub fn trim_room(
9026 &self,
9027 lane: Lane,
9028 idx: usize,
9029 edge: Edge,
9030 source_frames: &[u32],
9031 ) -> Option<(u32, u32)> {
9032 self.trim_room_with_walls(lane, idx, edge, SourceWalls::same(source_frames))
9033 }
9034
9035 /// [`trim_room`](Project::trim_room) against each lane's own table.
9036 pub fn trim_room_with_walls(
9037 &self,
9038 lane: Lane,
9039 idx: usize,
9040 edge: Edge,
9041 walls: SourceWalls<'_>,
9042 ) -> Option<(u32, u32)> {
9043 let l = self.index(lane)?;
9044 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, walls))
9045 }
9046
9047 /// [`trim_room`](Project::trim_room) with the same two walls, and for each
9048 /// one whether it is the source's media limit (head for a start edge, tail
9049 /// for an end edge) rather than a neighbouring clip. Stills never report
9050 /// media. `None` for an index that is not there.
9051 pub fn trim_walls(
9052 &self,
9053 lane: Lane,
9054 idx: usize,
9055 edge: Edge,
9056 source_frames: &[u32],
9057 ) -> Option<TrimWalls> {
9058 self.trim_walls_with_walls(lane, idx, edge, SourceWalls::same(source_frames))
9059 }
9060
9061 /// [`trim_walls`](Project::trim_walls) against each lane's own table.
9062 pub fn trim_walls_with_walls(
9063 &self,
9064 lane: Lane,
9065 idx: usize,
9066 edge: Edge,
9067 walls: SourceWalls<'_>,
9068 ) -> Option<TrimWalls> {
9069 let l = self.index(lane)?;
9070 (idx < self.lanes[l].clips.len()).then(|| self.clip_walls(l, idx, edge, walls).0)
9071 }
9072
9073 /// [`trim_walls`](Project::trim_walls) with each wall's bound named: what
9074 /// sets the low wall and what the high one, as a [`WallBound`]. The same
9075 /// walls, so a trim to one of them lands on the bound named for it. Asked
9076 /// before the trim: a clip committed at a wall sits on it, and the name is
9077 /// the one for the place it was asked to go. `None` for a bad index.
9078 pub fn trim_bounds(
9079 &self,
9080 lane: Lane,
9081 idx: usize,
9082 edge: Edge,
9083 walls: SourceWalls<'_>,
9084 ) -> Option<(WallBound, WallBound)> {
9085 let l = self.index(lane)?;
9086 (idx < self.lanes[l].clips.len()).then(|| {
9087 let (_, lo, hi) = self.clip_walls(l, idx, edge, walls);
9088 (lo, hi)
9089 })
9090 }
9091
9092 // ---- roll, slip, slide ------------------------------------------------
9093 //
9094 // The three trims that move *two* things at once, so no single-edge
9095 // [`trim`](Project::trim) can do them: the pair of edges at a cut, the
9096 // window a clip reads, the clip between its neighbours. Each is one undo
9097 // step, carries the clip's linked take along by the same delta, and is
9098 // measured against the same source tables a trim is. The engine ignores
9099 // locks, as everywhere: the front-end refuses first.
9100 //
9101 // Each plans the whole edit on clones and commits only a plan every member
9102 // can take *exactly*: at a rate that does not divide the frame grid a
9103 // timeline length can be unreachable for a source range ([`Speed::fit`]),
9104 // and an edit that lands one frame off would open a gap or an overlap and
9105 // move the timeline's length. The delta therefore backs off toward zero
9106 // until the plan is exact; a delta of zero is "no change" and costs no step.
9107
9108 /// `c` with its `edge` at timeline frame `to`, as [`trim`](Project::trim)
9109 /// would leave it, ignoring the neighbours (the caller owns them). `None`
9110 /// where a trim would refuse: a ramped head, no room for a source frame.
9111 fn edge_moved(&self, c: &Clip, edge: Edge, to: u32, table: &[u32]) -> Option<Clip> {
9112 if matches!(edge, Edge::Start) && !c.speed_keys.is_empty() {
9113 return None;
9114 }
9115 let still = self.is_still(c);
9116 let room = match edge {
9117 Edge::Start => c.end().checked_sub(to)?,
9118 Edge::End => to.checked_sub(c.start)?,
9119 };
9120 let keep = c.fit_source(room)?;
9121 let mut n = c.clone();
9122 match edge {
9123 Edge::End => n.out_frame = c.in_frame + keep.min(source_left(c, table)),
9124 Edge::Start if still => {
9125 n.in_frame = 0;
9126 n.out_frame = keep.min(table.get(c.source).copied().unwrap_or(c.len())).max(1);
9127 n.start = to;
9128 }
9129 Edge::Start => {
9130 n.in_frame = c.out_frame - keep.min(c.out_frame);
9131 n.start = to;
9132 }
9133 }
9134 rekey_trimmed(&mut n, c, edge, still);
9135 Some(n)
9136 }
9137
9138 /// The lane slot and index of every cut a roll at `(lane, idx)` moves: the
9139 /// clip before the cut first, then the same cut of each other member of its
9140 /// take that has a clip abutting behind it. `None` when `idx` has no clip
9141 /// abutting behind it.
9142 fn roll_pairs(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
9143 let l = self.index(lane)?;
9144 let abuts = |l: usize, i: usize| {
9145 let clips = &self.lanes[l].clips;
9146 matches!((clips.get(i), clips.get(i + 1)), (Some(a), Some(b)) if a.end() == b.start)
9147 };
9148 if lane.kind == LaneKind::Subtitle || !abuts(l, idx) {
9149 return None;
9150 }
9151 let members = self.group_of(lane, idx)?;
9152 let mut out = vec![(l, idx)];
9153 out.extend(members.clips.into_iter().filter(|&(ml, mi)| (ml, mi) != (l, idx) && abuts(ml, mi)));
9154 Some(out)
9155 }
9156
9157 /// How far the cut after `(l, i)` may travel on its media alone, as the
9158 /// delta range `(back, forward)` around where it is: the clip before it can
9159 /// play on to the end of its source, the one behind it back to the start of
9160 /// its own, and each keeps a frame.
9161 fn roll_span(&self, l: usize, i: usize, walls: SourceWalls<'_>) -> (i64, i64) {
9162 let (a, b) = (&self.lanes[l].clips[i], &self.lanes[l].clips[i + 1]);
9163 let t = walls.for_kind(self.lanes[l].kind);
9164 let cut = i64::from(a.end());
9165 if !b.speed_keys.is_empty() {
9166 return (0, 0);
9167 }
9168 let tail = i64::from(a.start)
9169 + i64::from(footprint(a, t.get(a.source).copied().unwrap_or(a.out_frame).saturating_sub(a.in_frame)));
9170 let head = if self.is_still(b) {
9171 i64::from(b.end()) - i64::from(b.speed.room(t.get(b.source).copied().unwrap_or(b.len())))
9172 } else {
9173 i64::from(b.start) - i64::from(footprint(b, b.in_frame))
9174 };
9175 let lo = head.max(0).max(i64::from(a.start) + i64::from(footprint(a, 1)));
9176 let hi = tail.min(i64::from(b.end()) - i64::from(footprint(b, 1)));
9177 ((lo - cut).min(0), (hi - cut).max(0))
9178 }
9179
9180 /// The two clips of the cut after `(l, i)` once it sits at `to`, or `None`
9181 /// when either cannot take it *exactly* (see the section note).
9182 fn rolled(&self, l: usize, i: usize, to: u32, walls: SourceWalls<'_>) -> Option<(Clip, Clip)> {
9183 let (a, b) = (&self.lanes[l].clips[i], &self.lanes[l].clips[i + 1]);
9184 let t = walls.for_kind(self.lanes[l].kind);
9185 let na = self.edge_moved(a, Edge::End, to, t)?;
9186 let nb = self.edge_moved(b, Edge::Start, to, t)?;
9187 (na.end() == to && nb.start == to && nb.end() == b.end()).then_some((na, nb))
9188 }
9189
9190 /// Where the cut at the end of the clip at `idx` of `lane` may travel,
9191 /// `(first, last)` timeline frame inclusive: the walls [`roll`](Project::roll)
9192 /// clamps to -- the media of both clips of every member of the take, and a
9193 /// frame of each. `None` for a clip with nothing abutting behind it.
9194 pub fn roll_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(u32, u32)> {
9195 let pairs = self.roll_pairs(lane, idx)?;
9196 let (back, fwd) = self.roll_delta_span(&pairs, walls);
9197 let cut = i64::from(self.lanes[pairs[0].0].clips[pairs[0].1].end());
9198 Some(((cut + back) as u32, (cut + fwd) as u32))
9199 }
9200
9201 fn roll_delta_span(&self, pairs: &[(usize, usize)], walls: SourceWalls<'_>) -> (i64, i64) {
9202 pairs.iter().fold((i64::MIN, i64::MAX), |(back, fwd), &(l, i)| {
9203 let (b, f) = self.roll_span(l, i, walls);
9204 (back.max(b), fwd.min(f))
9205 })
9206 }
9207
9208 /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to
9209 /// timeline frame `to`. The out-point of that clip and the in-point of the
9210 /// clip abutting behind it move together, so the pair keeps its joint span
9211 /// and nothing else on the lane moves: the timeline's length does not
9212 /// change. The frames that stay play what they played.
9213 ///
9214 /// Like [`trim`](Project::trim), `to` is clamped to the walls
9215 /// ([`roll_room`](Project::roll_room)), never refused. The rest of the take
9216 /// rolls its own cut by the same delta -- the ones that have a cut there --
9217 /// and the whole take is held to the tightest member. At a rate where the
9218 /// exact frame is unreachable the cut stops on the nearest one that is.
9219 ///
9220 /// `Some(cut)`: where the cut is now (the old place when nothing moved, at
9221 /// no cost in undo steps; one step otherwise). `None`, changing nothing:
9222 /// no clip there, or none abutting behind it -- a roll needs a cut. A
9223 /// speed-ramped clip behind the cut cannot take a new in-point (as a trim
9224 /// refuses a ramped head), which pins the cut.
9225 pub fn roll(&mut self, lane: Lane, idx: usize, to: u32, walls: SourceWalls<'_>) -> Option<u32> {
9226 let pairs = self.roll_pairs(lane, idx)?;
9227 let cut = i64::from(self.lanes[pairs[0].0].clips[pairs[0].1].end());
9228 let (back, fwd) = self.roll_delta_span(&pairs, walls);
9229 let mut d = (i64::from(to) - cut).clamp(back, fwd);
9230 let plan = loop {
9231 if d == 0 {
9232 return Some(cut as u32);
9233 }
9234 let plan: Option<Vec<_>> = pairs
9235 .iter()
9236 .map(|&(l, i)| {
9237 let at = i64::from(self.lanes[l].clips[i].end()) + d;
9238 let at = u32::try_from(at).ok()?;
9239 self.rolled(l, i, at, walls).map(|p| (l, i, p))
9240 })
9241 .collect();
9242 if let Some(plan) = plan {
9243 break plan;
9244 }
9245 d -= d.signum();
9246 };
9247 self.snapshot();
9248 for (l, i, (a, b)) in plan {
9249 self.lanes[l].clips[i] = a;
9250 self.lanes[l].clips[i + 1] = b;
9251 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9252 }
9253 Some((cut + d) as u32)
9254 }
9255
9256 /// The clips a slide at `(lane, idx)` moves, as lane slot and index: the
9257 /// clip itself first, then the rest of its take. `None` unless every one of
9258 /// them has a clip on both sides -- sliding needs neighbours to give to.
9259 fn slide_members(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
9260 let l = self.index(lane)?;
9261 if lane.kind == LaneKind::Subtitle || self.lanes[l].clips.get(idx).is_none() {
9262 return None;
9263 }
9264 let members = self.group_of(lane, idx)?;
9265 let mut out = vec![(l, idx)];
9266 out.extend(members.clips.into_iter().filter(|&m| m != (l, idx)));
9267 out.iter()
9268 .all(|&(ml, mi)| mi > 0 && mi + 1 < self.lanes[ml].clips.len())
9269 .then_some(out)
9270 }
9271
9272 /// How far the clip at `(l, i)` may slide on its neighbours' media alone, as
9273 /// the delta range `(back, forward)`. A neighbour it abuts gives or takes
9274 /// frames at its cut, up to its own media and a frame of itself; a
9275 /// neighbour across a gap only bounds the move where it begins.
9276 fn slide_span(&self, l: usize, i: usize, walls: SourceWalls<'_>) -> (i64, i64) {
9277 let clips = &self.lanes[l].clips;
9278 let (p, c, n) = (&clips[i - 1], &clips[i], &clips[i + 1]);
9279 let t = walls.for_kind(self.lanes[l].kind);
9280 let (start, end) = (i64::from(c.start), i64::from(c.end()));
9281 let (mut back, mut fwd) = (i64::MIN, i64::MAX);
9282 if p.end() == c.start {
9283 let tail = i64::from(p.start)
9284 + i64::from(footprint(p, t.get(p.source).copied().unwrap_or(p.out_frame).saturating_sub(p.in_frame)));
9285 back = back.max(i64::from(p.start) + i64::from(footprint(p, 1)) - start);
9286 fwd = fwd.min(tail - start);
9287 } else {
9288 back = back.max(i64::from(p.end()) - start);
9289 }
9290 if n.start == c.end() {
9291 if n.speed_keys.is_empty() {
9292 let head = if self.is_still(n) {
9293 i64::from(n.end()) - i64::from(n.speed.room(t.get(n.source).copied().unwrap_or(n.len())))
9294 } else {
9295 i64::from(n.start) - i64::from(footprint(n, n.in_frame))
9296 };
9297 back = back.max(head - end);
9298 fwd = fwd.min(i64::from(n.end()) - i64::from(footprint(n, 1)) - end);
9299 } else {
9300 back = back.max(0);
9301 fwd = fwd.min(0);
9302 }
9303 } else {
9304 fwd = fwd.min(i64::from(n.start) - end);
9305 }
9306 (back.min(0), fwd.max(0))
9307 }
9308
9309 /// The three clips of the slide at `(l, i)` once the middle one starts
9310 /// `d` frames later: the previous clip and the next one `None` when a gap
9311 /// (not a cut) lies on that side and so nothing there changes.
9312 fn slid(&self, l: usize, i: usize, d: i64, walls: SourceWalls<'_>) -> Option<(Option<Clip>, Clip, Option<Clip>)> {
9313 let clips = &self.lanes[l].clips;
9314 let (p, c, n) = (&clips[i - 1], &clips[i], &clips[i + 1]);
9315 let t = walls.for_kind(self.lanes[l].kind);
9316 let start = u32::try_from(i64::from(c.start) + d).ok()?;
9317 let end = start.checked_add(c.frames())?;
9318 let np = if p.end() == c.start {
9319 let np = self.edge_moved(p, Edge::End, start, t)?;
9320 (np.end() == start).then_some(())?;
9321 Some(np)
9322 } else {
9323 (start >= p.end()).then_some(())?;
9324 None
9325 };
9326 let nn = if n.start == c.end() {
9327 let nn = self.edge_moved(n, Edge::Start, end, t)?;
9328 (nn.start == end && nn.end() == n.end()).then_some(())?;
9329 Some(nn)
9330 } else {
9331 (end <= n.start).then_some(())?;
9332 None
9333 };
9334 Some((np, Clip { start, ..c.clone() }, nn))
9335 }
9336
9337 /// Where the clip at `idx` of `lane` may start when slid, `(first, last)`
9338 /// timeline frame inclusive: the walls [`slide`](Project::slide) clamps to.
9339 /// `None` for a clip that lacks a neighbour on either side (or any member
9340 /// of its take does).
9341 pub fn slide_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(u32, u32)> {
9342 let members = self.slide_members(lane, idx)?;
9343 let (back, fwd) = self.slide_delta_span(&members, walls);
9344 let start = i64::from(self.lanes[members[0].0].clips[members[0].1].start);
9345 Some(((start + back).max(0) as u32, (start + fwd).min(i64::from(u32::MAX)) as u32))
9346 }
9347
9348 fn slide_delta_span(&self, members: &[(usize, usize)], walls: SourceWalls<'_>) -> (i64, i64) {
9349 members.iter().fold((i64::MIN, i64::MAX), |(back, fwd), &(l, i)| {
9350 let (b, f) = self.slide_span(l, i, walls);
9351 (back.max(b), fwd.min(f))
9352 })
9353 }
9354
9355 /// **Slide**: starts the clip at `idx` of `lane` at timeline frame `to`,
9356 /// between its neighbours. Its content and length stay; the out-point of the
9357 /// clip before it and the in-point of the clip after it absorb the move
9358 /// (each gives or takes the frames at its cut), so the timeline's length
9359 /// does not change. A neighbour across a gap is not edited: the clip just
9360 /// may not run into it.
9361 ///
9362 /// Clamped like [`trim`](Project::trim) to [`slide_room`](Project::slide_room);
9363 /// the take slides by the same delta, held to its tightest member, and at a
9364 /// rate where the exact frame is unreachable stops on the nearest one that
9365 /// is. `Some(start)`: where the clip starts now (the old place when nothing
9366 /// moved, costing no undo step; one step otherwise). `None`, changing
9367 /// nothing: no clip, or no neighbour on a side -- the first and last clip
9368 /// of a lane have nothing to give or take. A speed-ramped clip *after* the
9369 /// slid one cannot take a new in-point, which pins the slide.
9370 pub fn slide(&mut self, lane: Lane, idx: usize, to: u32, walls: SourceWalls<'_>) -> Option<u32> {
9371 let members = self.slide_members(lane, idx)?;
9372 let start = i64::from(self.lanes[members[0].0].clips[members[0].1].start);
9373 let (back, fwd) = self.slide_delta_span(&members, walls);
9374 let mut d = (i64::from(to) - start).clamp(back, fwd);
9375 let plan = loop {
9376 if d == 0 {
9377 return Some(start as u32);
9378 }
9379 let plan: Option<Vec<_>> = members
9380 .iter()
9381 .map(|&(l, i)| self.slid(l, i, d, walls).map(|p| (l, i, p)))
9382 .collect();
9383 if let Some(plan) = plan {
9384 break plan;
9385 }
9386 d -= d.signum();
9387 };
9388 self.snapshot();
9389 for (l, i, (p, c, n)) in plan {
9390 if let Some(p) = p {
9391 self.lanes[l].clips[i - 1] = p;
9392 }
9393 self.lanes[l].clips[i] = c;
9394 if let Some(n) = n {
9395 self.lanes[l].clips[i + 1] = n;
9396 }
9397 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9398 }
9399 Some((start + d) as u32)
9400 }
9401
9402 /// The source frames that `by` timeline frames are worth for the clip at
9403 /// `idx` of `lane`: `by` itself at real time, `by * speed` at a constant
9404 /// rate and at the ramp's average rate for a ramped clip. Rounded to the
9405 /// nearest frame, so a tiny `by` on a slow clip can be zero. What a
9406 /// front-end turns a pointer or a typed timeline distance into before
9407 /// [`slip`](Project::slip), which works in the media's own frames.
9408 pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
9409 let c = self.lane(lane).get(idx)?;
9410 let (len, frames) = (i128::from(c.len()), i128::from(c.frames()));
9411 let n = i128::from(by) * len;
9412 // Round half away from zero.
9413 let r = (n.abs() * 2 + frames) / (frames * 2) * n.signum();
9414 Some(r as i64)
9415 }
9416
9417 /// How far the clip at `idx` of `lane` may slip, `(back, forward)` in
9418 /// source frames (`back <= 0 <= forward`): back to the first frame of the
9419 /// source and forward to its last, which is where the clip's own window
9420 /// stops. `None` for a bad index and for a still, which has no frames to
9421 /// slip through.
9422 pub fn slip_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(i64, i64)> {
9423 let l = self.index(lane)?;
9424 let c = self.lanes[l].clips.get(idx)?;
9425 if self.is_still(c) {
9426 return None;
9427 }
9428 let t = walls.for_kind(self.lanes[l].kind);
9429 let limit = i64::from(t.get(c.source).copied().unwrap_or(c.out_frame));
9430 Some((-i64::from(c.in_frame), (limit - i64::from(c.out_frame)).max(0)))
9431 }
9432
9433 /// **Slip**: shifts the source window of the clip at `idx` of `lane` by
9434 /// `by` source frames (see [`slip_source_delta`](Project::slip_source_delta)
9435 /// for timeline frames), later in the file for positive. Its place on the
9436 /// timeline and its length -- at its speed or ramp -- are unchanged: the
9437 /// same slot shows different content. Gain and placement keys stay on the
9438 /// footage they were set on.
9439 ///
9440 /// Clamped to [`slip_room`](Project::slip_room), never refused; the rest of
9441 /// the take slips by the same source frames, each within its own media. A
9442 /// source with no known length may not slip forward, as it may not grow in
9443 /// a trim. `Some(shift)`: the source frames the clip actually moved (`0`
9444 /// when pinned at a limit or asked for nothing, costing no undo step; one
9445 /// step otherwise). `None`, changing nothing: no clip, or a still.
9446 pub fn slip(&mut self, lane: Lane, idx: usize, by: i64, walls: SourceWalls<'_>) -> Option<i64> {
9447 let (lo, hi) = self.slip_room(lane, idx, walls)?;
9448 let d = by.clamp(lo, hi);
9449 if d == 0 {
9450 return Some(0);
9451 }
9452 let l = self.index(lane)?;
9453 let members = self.group_of(lane, idx)?;
9454 let mut plan: Vec<(usize, usize, Clip)> = Vec::new();
9455 for &(ml, mi) in &members.clips {
9456 let c = &self.lanes[ml].clips[mi];
9457 let t = walls.for_kind(self.lanes[ml].kind);
9458 let limit = i64::from(t.get(c.source).copied().unwrap_or(c.out_frame));
9459 let own = if (ml, mi) == (l, idx) {
9460 d
9461 } else if self.is_still(c) {
9462 continue;
9463 } else {
9464 d.clamp(-i64::from(c.in_frame), (limit - i64::from(c.out_frame)).max(0))
9465 };
9466 if own == 0 {
9467 continue;
9468 }
9469 let mut n = c.clone();
9470 n.in_frame = (i64::from(c.in_frame) + own) as u32;
9471 n.out_frame = (i64::from(c.out_frame) + own) as u32;
9472 if !c.transform_keys.is_empty() {
9473 n.transform_keys = keys_within(&c.transform_keys, n.in_frame, n.out_frame);
9474 }
9475 for (ne, ce) in n.effects.iter_mut().zip(&c.effects) {
9476 if !ce.keys.is_empty() {
9477 ne.keys = keys_within(&ce.keys, n.in_frame, n.out_frame);
9478 }
9479 }
9480 plan.push((ml, mi, n));
9481 }
9482 self.snapshot();
9483 for (ml, mi, n) in plan {
9484 self.lanes[ml].clips[mi] = n;
9485 }
9486 Some(d)
9487 }
9488
9489 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
9490 /// its lane's storage index: the one wall computation, asked for the clip
9491 /// itself and for each member a group trim carries.
9492 fn clip_room(&self, l: usize, i: usize, edge: Edge, walls: SourceWalls<'_>) -> (u32, u32) {
9493 let (w, _, _) = self.clip_walls(l, i, edge, walls);
9494 (w.lo, w.hi)
9495 }
9496
9497 /// The walls [`clip_room`](Self::clip_room) measures, with the media flags
9498 /// [`trim_walls`](Project::trim_walls) reports. Every wall is computed here
9499 /// once; the flags are read off the same comparisons that pick the wall.
9500 fn clip_walls(
9501 &self,
9502 l: usize,
9503 i: usize,
9504 edge: Edge,
9505 walls: SourceWalls<'_>,
9506 ) -> (TrimWalls, WallBound, WallBound) {
9507 // The lane's own table: a sound's length on an audio lane, the picture's
9508 // everywhere else.
9509 let source_frames = walls.for_kind(self.lanes[l].kind);
9510 let clips = &self.lanes[l].clips;
9511 let c = clips[i].clone();
9512 // A still has no media limit to report: its head and tail reach as far
9513 // as the caller's table says, which is a cap, not a source's end.
9514 let still = self.is_still(&c);
9515 let prev_end = i.checked_sub(1).map_or(0, |p| clips[p].end());
9516 let (lo, hi, lo_media, hi_media, lo_bound, hi_bound) = match edge {
9517 Edge::Start => {
9518 // Back to the source's own first frame -- as many *timeline*
9519 // frames as that head is worth at the clip's rate, which at
9520 // real time is the head itself -- and never over the clip in
9521 // front of it. Saturating because a clip may hold *more*
9522 // head than the timeline has room for -- a ripple delete
9523 // slides a clip back to frame 0 with its in-point wherever
9524 // the cut left it -- and frame 0 is the other wall.
9525 //
9526 // A still is measured from its *tail* instead: it has no
9527 // in-point worth the name (every frame the same picture), so
9528 // its head reaches exactly as far as its tail does -- out to
9529 // the length the caller's table gives it, whole. Measured
9530 // from the in-point it would have no head room at all, which
9531 // is a placed picture whose left edge cannot be dragged out.
9532 // No entry in the table means no growth, as it does at the
9533 // other end.
9534 let head = if still {
9535 c.end().saturating_sub(
9536 c.speed
9537 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
9538 )
9539 } else if c.reversed {
9540 // The head is the window's far end: what it can still grow into
9541 // is what the file has past the out-point.
9542 c.start.saturating_sub(c.speed.room(
9543 source_frames
9544 .get(c.source)
9545 .copied()
9546 .unwrap_or(c.out_frame)
9547 .saturating_sub(c.out_frame),
9548 ))
9549 } else {
9550 c.start.saturating_sub(c.speed.room(c.in_frame))
9551 };
9552 (
9553 head.max(prev_end),
9554 // One *frame of clip* always survives, and at a rate below
9555 // real time one frame of clip is several frames of timeline
9556 // ([`Speed::room`]): an edge dragged closer than that would
9557 // ask for a range no source frame fits in. At real time this
9558 // is `end - 1`, unchanged.
9559 c.end() - c.speed.room(1),
9560 // The head is the binding wall when it is not behind the
9561 // neighbour; equal walls count as media. With no neighbour
9562 // the wall is frame 0, which the head always meets or beats.
9563 !still && head >= prev_end,
9564 // The clip's own minimum length, not a neighbour or media.
9565 false,
9566 // A neighbour that sits on the same frame as the source's
9567 // head is named: the two walls coincide, and the neighbour is
9568 // the one a caller can move, so a tie is worded as it.
9569 if i > 0 && head <= prev_end {
9570 WallBound::Neighbour(prev_end)
9571 } else if still {
9572 WallBound::Cap
9573 } else {
9574 WallBound::Source
9575 },
9576 WallBound::MinLength,
9577 )
9578 }
9579 Edge::End => {
9580 // Out to whatever is left of the source -- again in timeline
9581 // frames, at this clip's rate -- and never over the clip
9582 // behind it.
9583 let tail = c.start.saturating_add(c.speed.room(match c.reversed {
9584 // The tail is the window's near end, which grows down to the
9585 // file's first frame.
9586 true => c.out_frame,
9587 false => source_frames
9588 .get(c.source)
9589 .copied()
9590 .unwrap_or(c.out_frame)
9591 .saturating_sub(c.in_frame),
9592 }));
9593 let next = clips.get(i + 1).map_or(u32::MAX, |n| n.start);
9594 (
9595 // ...and the same wall from the other end: the shortest this
9596 // clip can be is the room one source frame of it takes.
9597 c.start + c.speed.room(1),
9598 tail.min(next),
9599 false,
9600 // The tail is the binding wall when it is not past the
9601 // neighbour; equal walls count as media.
9602 !still && tail <= next,
9603 WallBound::MinLength,
9604 // A tie with the neighbour's start is named as the neighbour
9605 // too, for the same reason as the start edge's.
9606 if clips.get(i + 1).is_some() && tail >= next {
9607 WallBound::Neighbour(next)
9608 } else if still {
9609 WallBound::Cap
9610 } else {
9611 WallBound::Source
9612 },
9613 )
9614 }
9615 };
9616 // `hi.max(lo)`: for a clip the invariants hold for, the range always
9617 // contains the edge's own place, and a caller's wrong `source_frames`
9618 // must not become an empty range (or a panicking `clamp`) here.
9619 (
9620 TrimWalls {
9621 lo,
9622 hi: hi.max(lo),
9623 lo_media,
9624 hi_media,
9625 },
9626 lo_bound,
9627 hi_bound,
9628 )
9629 }
9630
9631 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
9632 /// every frame is the same picture, so which frame of it a clip's in-point
9633 /// names is not a question -- what [`Project::trim`] lets grow at either
9634 /// end. `false` for a source that is not there.
9635 fn is_still(&self, clip: &Clip) -> bool {
9636 self.sources
9637 .get(clip.source)
9638 .is_some_and(|s| crate::is_image(&s.path))
9639 }
9640
9641 /// The placements that move as one with the one at `idx` of `lane` --
9642 /// itself and whatever carries its link, on the media lanes and the
9643 /// subtitle ones alike. `None` for an index that is not there.
9644 /// Whether the clip at `idx` is in a take: its link is shared with another clip. A lone link
9645 /// (what [`ungroup`](Self::ungroup) leaves) is not a take, so the clip moves on its own.
9646 fn in_take(&self, lane: Lane, idx: usize) -> bool {
9647 self.group_of(lane, idx).is_some_and(|m| !m.alone())
9648 }
9649
9650 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
9651 let sub = lane.kind == LaneKind::Subtitle;
9652 let link = if sub {
9653 self.sub_lane(lane).get(idx)?.link
9654 } else {
9655 self.lane(lane).get(idx)?.link
9656 };
9657 let mut members = Members::default();
9658 match link {
9659 Some(link) => {
9660 for (l, data) in self.lanes.iter().enumerate() {
9661 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
9662 members.clips.push((l, i));
9663 }
9664 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
9665 members.subs.push((l, i));
9666 }
9667 }
9668 }
9669 None => {
9670 let l = self.index(lane).expect("the placement was found on it");
9671 if sub {
9672 members.subs.push((l, idx));
9673 } else {
9674 members.clips.push((l, idx));
9675 }
9676 }
9677 }
9678 Some(members)
9679 }
9680
9681 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
9682 /// new group, pushing everything from there on later by its length in
9683 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
9684 /// the clip it lands in is split around it; past the end of the timeline it
9685 /// goes down where it was asked for, with black in front of it -- which is
9686 /// what a library row let go on the open bed means, and what the ghost under
9687 /// the pointer promised. A clipboard means "put it here", not "here and
9688 /// black in front", and clamps to the end at its own door
9689 /// ([`crate::PlaybackSession::paste_at`]).
9690 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
9691 ///
9692 /// `V1` and `A1` and no other lane, because a take is one picture and one
9693 /// sound: copying it onto every lane there is would play the same audio
9694 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
9695 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
9696 /// video lane it is a clip that decodes to nothing, and a save carrying one
9697 /// does not open again -- and a still image ([`crate::is_image`]) reaches
9698 /// `V1` only, for the mirror of that reason. The room is still opened on
9699 /// every media lane, or the lanes it was not inserted into would slide out
9700 /// of step with the ones it was -- and the subtitle lanes are left alone:
9701 /// the words keep their own clock, and a caption that should travel with a
9702 /// clip is what a group is for.
9703 ///
9704 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
9705 /// Changes the timeline->source mapping: the caller must reseek. Refused for
9706 /// an empty `clip` and for one naming a source that is not there (both of
9707 /// which the public fields let a caller build), and for a paste whose ripple
9708 /// would push a clip past the last frame there is -- nothing is changed by
9709 /// any of them.
9710 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
9711 let source = self.sources.get(clip.source);
9712 let compound = is_sequence_source(clip.source);
9713 if source.is_none() && (!compound || self.compound_refusal(&clip).is_some()) {
9714 return false;
9715 }
9716 if clip.out_frame <= clip.in_frame {
9717 return false;
9718 }
9719 let audio_only = source.is_some_and(|s| crate::is_audio(&s.path));
9720 // ...and its mirror: a still is a picture and no sound, so a copy of one
9721 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
9722 // worker tries to demux -- which silences the *whole session*, not just
9723 // that clip -- and a save the engine's own `open_project` then refuses.
9724 let picture_only = source.is_some_and(|s| crate::is_image(&s.path));
9725 // The frame it was asked for and no other: a row let go on the empty
9726 // bed past the last clip lands *there*, under the ghost that promised
9727 // it, with black in front. Clamping to the end here made every drop on
9728 // open bed an append -- the clipboard's rule, applied to a hand that
9729 // had named a place.
9730 let at = timeline_frame;
9731 // The room it takes on the timeline, which its speed decides -- not the
9732 // source range it reads.
9733 let len = clip.frames();
9734 // Room for it: `open_room` adds `len` to every start from `at` on, and a
9735 // hand-written file may hold a clip that ends at the very last frame
9736 // (`edith::check` permits `start + len == u32::MAX`). Refused here
9737 // rather than wrapped there -- a wrapped start lands *behind* the clip
9738 // it belongs after, which is an overlap no save will read back.
9739 if at.checked_add(len).is_none()
9740 || self
9741 .lanes
9742 .iter()
9743 .flat_map(|l| &l.clips)
9744 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
9745 {
9746 return false;
9747 }
9748 // ...and room *to open*: the paste splits whatever it lands inside of,
9749 // and a speeded clip can only be cut where its own rate has a source
9750 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
9751 // of one, which is the overlap a lane may never hold. At real time every
9752 // frame answers, so this cannot refuse an unspeeded paste.
9753 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
9754 if self
9755 .lanes
9756 .iter()
9757 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
9758 {
9759 return false;
9760 }
9761 self.snapshot();
9762 let clip = Clip {
9763 fade_in: 0,
9764 fade_out: 0,
9765 transition_out: 0,
9766 transition_kind: Default::default(),
9767 start: at,
9768 link: Some(self.new_link()),
9769 ..clip
9770 };
9771 // Only lanes that can play the source: a file with no picture belongs on
9772 // an audio lane and nowhere else, exactly as `place_stream_at` decides
9773 // it for an import. On a video lane it would decode to nothing, and the
9774 // save it wrote would not open again.
9775 let kinds: &[LaneKind] = match (audio_only, picture_only) {
9776 (true, _) => &[LaneKind::Audio],
9777 (_, true) => &[LaneKind::Video],
9778 _ => &[LaneKind::Video, LaneKind::Audio],
9779 };
9780 let takes: Vec<usize> = kinds
9781 .iter()
9782 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
9783 .collect();
9784 for (i, data) in self.lanes.iter_mut().enumerate() {
9785 open_room(&mut data.clips, at, len);
9786 // The subtitle lanes are NOT touched: a paste inserts media, and
9787 // the words keep their own clock. Opening room here used to split
9788 // a caption the paste landed inside and slide the rest behind it
9789 // -- "a caption that stayed put while the picture moved on no
9790 // longer says the same thing" -- but a caption pinned to nothing
9791 // (and a video arriving on a timeline of words alone) has no
9792 // picture to follow, and the split did to the words what no hand
9793 // asked for. A caption that should travel with a clip is what a
9794 // group is for, and a group moves as one.
9795 if takes.contains(&i) {
9796 let idx = data.clips.partition_point(|c| c.start < at);
9797 data.clips.insert(idx, clip.clone());
9798 }
9799 debug_assert!(sorted_disjoint(&data.clips));
9800 debug_assert!(subs_sorted_disjoint(&data.subs));
9801 }
9802 true
9803 }
9804
9805 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
9806 /// `items` lands on the lane it names, its head moved by the offset every
9807 /// other item moves by too -- `at` less the earliest `start` among them,
9808 /// so the set's own gaps and lane assignment survive the trip from
9809 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
9810 /// way a lone clip's copy does.
9811 ///
9812 /// All-or-nothing, and **refused** rather than opening room or splitting
9813 /// a neighbour the way [`paste`](Project::paste) does for one clip:
9814 /// a set-paste never ripples the bed, so a landing that overlaps so much
9815 /// as one existing clip on its own lane refuses the whole set, changing
9816 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
9817 /// clamps instead of refusing, but a paste has no drag to clamp against,
9818 /// and a landing moved off the frame asked for is not what a paste means.
9819 /// `items` empty, naming a lane or a source that is not there, or a clip
9820 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
9821 ///
9822 /// Exactly one history snapshot for the whole set, so one
9823 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
9824 /// on every lane an item lands on: the caller must reseek.
9825 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
9826 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
9827 return false;
9828 };
9829 // Resolved once, up front, off the lanes as they stand now: a lane or
9830 // source that is not there, or a landing that would overlap a
9831 // neighbour, refuses the whole set before any of it is written.
9832 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
9833 for (lane, clip) in items.iter().cloned() {
9834 let Some(li) = self.index(lane) else {
9835 return false;
9836 };
9837 let known = self.sources.get(clip.source).is_some()
9838 || (is_sequence_source(clip.source) && self.compound_refusal(&clip).is_none());
9839 if !known || clip.out_frame <= clip.in_frame {
9840 return false;
9841 }
9842 let delta = i64::from(clip.start) - i64::from(anchor);
9843 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
9844 return false;
9845 };
9846 let Some(end) = start.checked_add(clip.frames()) else {
9847 return false;
9848 };
9849 if self.lanes[li]
9850 .clips
9851 .iter()
9852 .any(|c| c.start < end && start < c.end())
9853 {
9854 return false;
9855 }
9856 landings.push((li, Clip { start, ..clip }));
9857 }
9858 self.snapshot();
9859 for (li, mut clip) in landings {
9860 clip.link = Some(self.new_link());
9861 clip.fade_in = 0;
9862 clip.fade_out = 0;
9863 clip.transition_out = 0;
9864 let clips = &mut self.lanes[li].clips;
9865 let idx = clips.partition_point(|c| c.start < clip.start);
9866 clips.insert(idx, clip);
9867 }
9868 true
9869 }
9870
9871 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
9872 /// silence, and nothing else moves. Refused only for an out-of-range index
9873 /// (which a lane that is not there always is) -- lifting the last placement
9874 /// there is leaves an *empty* timeline, which is a state the project holds
9875 /// like any other and an undo brings back.
9876 /// Swaps the placements at `a` and `b` of `lane`: `b` takes `a`'s start, the
9877 /// placements between them move by the difference in their lengths (the
9878 /// ripple within this one lane), and `a` lands where `b` was, moved by the
9879 /// same difference. The span the two cover keeps its length, so nothing
9880 /// after `b` moves. One snapshot.
9881 ///
9882 /// `false`, nothing changed, for an index that is not there, `a == b`, and a
9883 /// placement in a group: a take is moved as a take, never swapped apart.
9884 pub fn swap(&mut self, lane: Lane, a: usize, b: usize) -> bool {
9885 let (a, b) = if a < b { (a, b) } else { (b, a) };
9886 let Some(new) = (|| {
9887 let clips = self.lane(lane);
9888 if a == b || b >= clips.len() || self.in_take(lane, a) || self.in_take(lane, b) {
9889 return None;
9890 }
9891 let span = &clips[a..=b];
9892 let (sa, sb) = (span[0].start, span[span.len() - 1].start);
9893 let d = i64::from(span[span.len() - 1].frames()) - i64::from(span[0].frames());
9894 let shift = |x: u32, by: i64| (i64::from(x) + by) as u32;
9895 let last = span.len() - 1;
9896 let mut out = Vec::with_capacity(span.len());
9897 let mut first_in = span[last].clone();
9898 first_in.start = sa;
9899 out.push(first_in);
9900 for c in &span[1..last] {
9901 let mut m = c.clone();
9902 m.start = shift(m.start, d);
9903 out.push(m);
9904 }
9905 let mut back = span[0].clone();
9906 back.start = shift(sb, d);
9907 out.push(back);
9908 Some(out)
9909 })() else {
9910 return false;
9911 };
9912 self.snapshot();
9913 self.lane_mut(lane).expect("checked above").splice(a..=b, new);
9914 true
9915 }
9916
9917 /// Exchanges the positions of two unlinked clips on `lane` without rippling
9918 /// anything: each takes the other's head, and whatever lies between them stays
9919 /// where it is. When the two differ in length the shorter leaves a gap where it
9920 /// was and the longer must fit its new place -- the one that does not fit is
9921 /// refused, naming the clip it would overlap, and nothing changes.
9922 ///
9923 /// Both new footprints are checked against every clip that stays put, at once,
9924 /// so a clip moving into the slot the other one vacates is not refused for
9925 /// overlapping a slot that is about to be free (which is what sequencing three
9926 /// single moves did). One undo step.
9927 pub fn swap_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> {
9928 let label = lane.label();
9929 let clips = self.lane(lane);
9930 if a == b {
9931 return Err("the same clip twice: name two different clips".into());
9932 }
9933 let (Some(ca), Some(cb)) = (clips.get(a).cloned(), clips.get(b).cloned()) else {
9934 return Err(format!("there is no clip {} or {} on {label}", a.max(b), a.min(b)).into());
9935 };
9936 if self.in_take(lane, a) || self.in_take(lane, b) {
9937 return Err(format!(
9938 "clip {a} and clip {b} on {label} are grouped with other lanes: a take moves as a take, not swapped apart"
9939 )
9940 .into());
9941 }
9942 let mut moved_a = ca.clone();
9943 moved_a.start = cb.start;
9944 let mut moved_b = cb.clone();
9945 moved_b.start = ca.start;
9946 let placed = [(a, &moved_a), (b, &moved_b)];
9947 for (idx, moved) in placed {
9948 for (i, other) in clips.iter().enumerate() {
9949 if i == a || i == b {
9950 continue;
9951 }
9952 if moved.start < other.end() && other.start < moved.end() {
9953 return Err(format!(
9954 "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",
9955 moved.start,
9956 moved.end(),
9957 other.start,
9958 other.end()
9959 )
9960 .into());
9961 }
9962 }
9963 }
9964 if moved_a.start < moved_b.end() && moved_b.start < moved_a.end() {
9965 return Err(format!(
9966 "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",
9967 moved_b.start,
9968 moved_b.end(),
9969 moved_a.start,
9970 moved_a.end()
9971 )
9972 .into());
9973 }
9974 self.snapshot();
9975 let list = self.lane_mut(lane).expect("checked above");
9976 list[a] = moved_a;
9977 list[b] = moved_b;
9978 list.sort_by_key(|c| c.start);
9979 debug_assert!(sorted_disjoint(list));
9980 Ok(())
9981 }
9982
9983 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
9984 if idx >= self.lane(lane).len() {
9985 return false;
9986 }
9987 self.snapshot();
9988 self.lane_mut(lane).expect("checked above").remove(idx);
9989 true
9990 }
9991
9992 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
9993 /// the hole: everything after slides back by `len`. The rippling delete --
9994 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
9995 /// empty range; a delete that leaves nothing behind empties the timeline,
9996 /// which is a state like any other and one undo away.
9997 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
9998 if len == 0 {
9999 return false;
10000 }
10001 // Nothing reaches past `at`: there is nothing to cut and nothing to
10002 // slide back, and a delete that changes nothing must not cost an undo
10003 // step (see [`snapshot`](Project::snapshot)).
10004 if !self
10005 .lanes
10006 .iter()
10007 .flat_map(|l| &l.clips)
10008 .any(|c| c.end() > at)
10009 {
10010 return false;
10011 }
10012 self.snapshot();
10013 let on = all_lanes(&self.lanes);
10014 let tracks = self.caption_tracks_on(&on);
10015 let placed = self.placed_cues(&tracks);
10016 let pieces = self.split_cues_across(&on, &[at, at.saturating_add(len)], true);
10017 ripple(&mut self.lanes, &on, at, len);
10018 self.drop_unplaced(&tracks, &placed, &pieces);
10019 true
10020 }
10021
10022 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
10023 /// a right-click on empty bench space names before offering to close it.
10024 /// `None` when `frame` sits inside a placement, or past the last one: the
10025 /// open end of a lane is not a gap, since there is nothing after it to slide
10026 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
10027 /// the media [`Clip`] list they deliberately never hold.
10028 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
10029 let data = self.index(lane).map(|i| &self.lanes[i])?;
10030 match data.kind {
10031 LaneKind::Subtitle => gap(&data.subs, frame),
10032 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
10033 }
10034 }
10035
10036 /// How many bounded holes `lane` holds. The open end after the last
10037 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
10038 /// it would move nothing.
10039 pub fn gap_count(&self, lane: Lane) -> usize {
10040 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
10041 return 0;
10042 };
10043 match data.kind {
10044 LaneKind::Subtitle => gaps(&data.subs).len(),
10045 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
10046 }
10047 }
10048
10049 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
10050 /// together to keep sync -- what a right-click on empty bench space asks
10051 /// before the menu offers to close it, and what widens
10052 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
10053 /// named to the whole take the gap might be half of.
10054 ///
10055 /// A clip bordering the gap on `lane` -- the one ending where it starts,
10056 /// the one starting where it ends -- carries a link when it is one take
10057 /// with a clip on another lane. That lane joins the scope only when the
10058 /// *exact same* stretch is empty there too (same start, same length): the
10059 /// ripple then removes nothing but silence, on every lane it touches, and
10060 /// both halves stay the length they always were. A link whose partner
10061 /// lane is not empty there -- a gap of a different length, or none at all
10062 /// -- is named back to the caller rather than silently widened past
10063 /// (which would cut real media out of a lane nothing asked to touch) or
10064 /// silently left out (which is the defect this closes: a per-lane ripple
10065 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
10066 /// to refuse it after the fact, on the very half this could have carried
10067 /// along).
10068 ///
10069 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
10070 /// partner clip sits on another lane -- the unlinked case, untouched.
10071 ///
10072 /// Subtitle lanes have no media take halves to inspect. A caption can be
10073 /// hand-grouped with clips, but it is not the imported A/V take this method
10074 /// widens for, so a subtitle gap stays scoped to its own lane; the later
10075 /// scoped cut still refuses an explicit group split.
10076 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
10077 let Some(li) = self.index(lane) else {
10078 return Err("no track to work on".into());
10079 };
10080 let labels = handles(&self.lanes);
10081 let end = start + frames;
10082 let mut scope = vec![lane];
10083 for c in self.lanes[li]
10084 .clips
10085 .iter()
10086 .filter(|c| c.end() == start || c.start == end)
10087 {
10088 let Some(id) = c.link else { continue };
10089 for (j, data) in self.lanes.iter().enumerate() {
10090 if j == li {
10091 continue;
10092 }
10093 if !data.clips.iter().any(|o| o.link == Some(id)) {
10094 continue;
10095 }
10096 match gap(&data.clips, start) {
10097 Some((s, f)) if s == start && f == frames => {
10098 let other = labels[j];
10099 if !scope.contains(&other) {
10100 scope.push(other);
10101 }
10102 }
10103 _ => {
10104 // One plain line: the partner by name, and the reason in a word.
10105 return Err(format!("Can't close this gap: it would put {} out of sync.", labels[j].label()).into());
10106 }
10107 }
10108 }
10109 }
10110 Ok(scope)
10111 }
10112
10113 /// Close every bounded gap on `lane`, as one undo step, without making the
10114 /// lane's scope global. Media lanes use the same take-safety widening
10115 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
10116 /// halves ride along only when their matching lane is empty over that exact
10117 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
10118 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
10119 /// halves of an imported A/V take, so the media take-widening rule has
10120 /// nothing to add there.
10121 ///
10122 /// The walk is back-to-front. Closing a gap shifts everything after it, so
10123 /// later holes must be consumed while their measured starts are still true;
10124 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
10125 /// only before the first successful close, so an all-skipped sweep is not an
10126 /// undo step.
10127 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
10128 let Some(i) = self.index(lane) else {
10129 return Err("no track to work on".into());
10130 };
10131 if self.lanes[i].kind == LaneKind::Subtitle {
10132 return Ok(self.close_all_subtitle_gaps_on_lane(i));
10133 }
10134 let mut report = GapSweep::default();
10135 let mut snapshot = false;
10136 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
10137 match self.gap_take_scope(lane, start, frames).and_then(|scope| {
10138 let on = self.scoped(&scope)?;
10139 self.scope_holds_takes_whole(&on, start)?;
10140 Ok(on)
10141 }) {
10142 Ok(on) => {
10143 if !snapshot {
10144 self.snapshot();
10145 snapshot = true;
10146 }
10147 ripple(&mut self.lanes, &on, start, frames);
10148 report.closed += 1;
10149 }
10150 Err(e) => report.skipped.push(GapSkip {
10151 start,
10152 reason: e.to_string(),
10153 }),
10154 }
10155 }
10156 report.skipped.reverse();
10157 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10158 Ok(report)
10159 }
10160
10161 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
10162 /// take-scope widening: a caption is not one half of an A/V take. Explicit
10163 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
10164 /// so a grouped caption is refused rather than pulled away from its group.
10165 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
10166 let mut report = GapSweep::default();
10167 let mut snapshot = false;
10168 let on = [i];
10169 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
10170 match self.scope_holds_takes_whole(&on, start) {
10171 Ok(()) => {
10172 if !snapshot {
10173 self.snapshot();
10174 snapshot = true;
10175 }
10176 ripple(&mut self.lanes, &on, start, frames);
10177 report.closed += 1;
10178 }
10179 Err(e) => report.skipped.push(GapSkip {
10180 start,
10181 reason: e.to_string(),
10182 }),
10183 }
10184 }
10185 report.skipped.reverse();
10186 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10187 report
10188 }
10189
10190 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
10191 /// out of the lanes in `scope` and close each hole, as one edit: the
10192 /// jumpcut a silence scan asks for ([`crate::silence`]).
10193 ///
10194 /// A lane that is not in `scope` **does not move**, which is the whole
10195 /// point of the parameter: the silences of a podcast track come out
10196 /// without the music track under it sliding. `scope` is an arbitrary set of
10197 /// lanes and not a kind or a range, so a caller with its own idea of what
10198 /// is selected (a take, a track, everything) says it in lanes and nothing
10199 /// here has to learn about selection.
10200 ///
10201 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
10202 /// reason this exists rather than a caller's loop over
10203 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
10204 /// undo press, not forty. Cut back to front, so a region's frames still
10205 /// mean what the caller measured while the ones before it are cut.
10206 ///
10207 /// The list is sorted and overlapping entries are merged before anything is
10208 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
10209 /// other's frames. Refused, with no undo step, for an empty list, for a
10210 /// scope naming no lane that is there, and -- by name -- when the scope
10211 /// would take one half of a take with it
10212 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
10213 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
10214 let regions = tidy(regions);
10215 let on = self.scoped(scope)?;
10216 let Some(&(first, _)) = regions.first() else {
10217 return Err("nothing to cut".into());
10218 };
10219 self.scope_holds_takes_whole(&on, first)?;
10220 self.snapshot();
10221 for &(at, len) in regions.iter().rev() {
10222 let tracks = self.caption_tracks_on(&on);
10223 let placed = self.placed_cues(&tracks);
10224 let pieces = self.split_cues_across(&on, &[at, at.saturating_add(len)], true);
10225 ripple_keeping_takes(&mut self.lanes, &on, at, len, &mut self.next_link);
10226 self.drop_unplaced(&tracks, &placed, &pieces);
10227 }
10228 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10229 self.settle();
10230 Ok(())
10231 }
10232
10233 /// The storage indices of `scope`, which is what every batch below walks.
10234 /// `Err` for a scope that names nothing there rather than a silent no-op:
10235 /// an edit asked for on a lane that is not there did not happen, and the
10236 /// caller has to hear so.
10237 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
10238 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
10239 match on.is_empty() {
10240 true => Err("no track to work on".into()),
10241 false => Ok(on),
10242 }
10243 }
10244
10245 /// The law a scoped ripple lives under: **a group travels as one**, so a
10246 /// batch that moves one half of a take and not the other would leave the
10247 /// halves disagreeing about where they stand -- an offset no hand asked
10248 /// for, and the reason the take's lanes have to be scoped together.
10249 ///
10250 /// Refused by name rather than widened silently. Widening would edit a
10251 /// track the user did not scope, which is exactly the surprise scoping
10252 /// exists to end; a front-end that wants the take is free to *say* the
10253 /// take's lanes, and to name them in what it tells the user afterwards.
10254 ///
10255 /// Only from `from` on: a take sitting entirely before the first cut does
10256 /// not move, so it is not this rule's business.
10257 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
10258 let labels = handles(&self.lanes);
10259 // The halves of a group are on either of a lane's lists, and the
10260 // refusal names whichever sits outside the scope -- a clip like it
10261 // always has, and a caption now that a group may hold one.
10262 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
10263 let Some(id) = link else {
10264 return Ok(());
10265 };
10266 for (j, data) in self.lanes.iter().enumerate() {
10267 if on.contains(&j) {
10268 continue;
10269 }
10270 let clip = data.clips.iter().find(|o| o.link == Some(id));
10271 let sub = data.subs.iter().find(|s| s.link == Some(id));
10272 if let Some(half) = clip {
10273 return Err(format!(
10274 "the {what} at frame {start} is one take with the {} clip at frame {}: \
10275 moving one track of a take would pull it apart -- take the whole take, \
10276 or detach them first",
10277 labels[j].label(),
10278 half.start
10279 )
10280 .into());
10281 }
10282 if let Some(half) = sub {
10283 return Err(format!(
10284 "the {what} at frame {start} is one take with the {} caption at frame {}: \
10285 moving one track of a take would pull it apart -- take the whole take, \
10286 or detach them first",
10287 labels[j].label(),
10288 half.start
10289 )
10290 .into());
10291 }
10292 }
10293 Ok(())
10294 };
10295 for &i in on {
10296 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
10297 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
10298 }
10299 // A caption before the first cut does not move, so it is not this
10300 // rule's business -- exactly the clip test's own line.
10301 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
10302 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
10303 }
10304 }
10305 Ok(())
10306 }
10307
10308 /// Play every one of `regions` at `speed` instead of cutting it: each is
10309 /// split out of whatever covers it, re-rated, and the room it no longer
10310 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
10311 /// does not ripple, and a hole where a silence shrank is the one thing this
10312 /// must not leave. One snapshot for the lot, like
10313 /// [`cut_regions`](Project::cut_regions).
10314 ///
10315 /// The rate is **absolute**, not a multiplier on what is there: running it
10316 /// twice over the same stretch leaves it at `speed`, not at `speed`
10317 /// squared, so a second pass over an already-cut timeline changes nothing.
10318 ///
10319 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
10320 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
10321 ///
10322 /// Refused by name, with nothing changed and no undo step, when:
10323 ///
10324 /// * the scope would take one half of a take with it
10325 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
10326 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
10327 /// shrink by different amounts and the ripple would pull them apart,
10328 /// which is what cutting does not suffer and why delete mode has no such
10329 /// refusal;
10330 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
10331 /// piece could not be split out exactly;
10332 /// * two lanes' pieces would end up different lengths, which is a group
10333 /// whose halves disagree about their span (the refusal
10334 /// [`write_speed`](Project::write_speed) already makes, in its words);
10335 /// * the region would grow rather than shrink, i.e. it already plays faster
10336 /// than `speed`.
10337 pub fn speed_regions(
10338 &mut self,
10339 regions: &[(u32, u32)],
10340 speed: Speed,
10341 scope: &[Lane],
10342 ) -> crate::Result<()> {
10343 let regions = tidy(regions);
10344 let on = self.scoped(scope)?;
10345 let Some(&(first, _)) = regions.first() else {
10346 return Err("nothing to speed up".into());
10347 };
10348 self.scope_holds_takes_whole(&on, first)?;
10349 if self.lanes.iter().any(|l| {
10350 l.clips.iter().any(|c| {
10351 is_sequence_source(c.source) && regions.iter().any(|&(a, b)| c.start < b && a < c.end())
10352 })
10353 }) {
10354 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
10355 }
10356 if self.lanes.iter().any(|l| {
10357 l.clips.iter().any(|c| {
10358 !c.speed_keys.is_empty()
10359 && regions.iter().any(|&(a, b)| c.start < b && a < c.end())
10360 })
10361 }) {
10362 return Err("a clip under the region has a speed ramp: clear the ramp first".into());
10363 }
10364 let labels = handles(&self.lanes);
10365 // Before anything is touched, because this is the refusal a person can
10366 // act on: a clip that laps over the edge of a silence has to be trimmed
10367 // (or the silences cut instead), and saying so after a rollback would
10368 // be saying it about a timeline that already looks different.
10369 for &(at, len) in &regions {
10370 for &l in &on {
10371 for c in &self.lanes[l].clips {
10372 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
10373 {
10374 return Err(format!(
10375 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
10376 speeding it up would pull the lanes apart -- trim it first, or cut the \
10377 silences out instead",
10378 labels[l].label(),
10379 c.start,
10380 at + len
10381 )
10382 .into());
10383 }
10384 }
10385 }
10386 }
10387 // The rest is checked as it is built: a split's own arithmetic is what
10388 // says whether a rate can address an edge. So the snapshot is taken
10389 // first and *rolled back* on a refusal -- one undo either way, and a
10390 // refusal still costs no step (`roll_back_snapshot` takes back the one just pushed).
10391 self.snapshot();
10392 for &(at, len) in regions.iter().rev() {
10393 self.write_split(at, false, &on);
10394 self.write_split(at + len, false, &on);
10395 let mut room: Option<(Lane, u32)> = None;
10396 let mut refused = None;
10397 for &l in &on {
10398 let clips = &self.lanes[l].clips;
10399 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
10400 if (c.start, c.end()) != (at, at + len) {
10401 // *Which* edge did not come off: a rate that cannot
10402 // address the end of the silence is not a rate that
10403 // cannot address its start, and naming the wrong frame
10404 // sends the user looking in the wrong place.
10405 let edge = match c.start == at {
10406 true => at + len,
10407 false => at,
10408 };
10409 refused = Some(format!(
10410 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
10411 detach it, or put it back to 1.00x first",
10412 labels[l].label(),
10413 c.start,
10414 c.speed
10415 ));
10416 continue;
10417 }
10418 let after = speed.frames(c.len());
10419 match room {
10420 None => room = Some((labels[l], after)),
10421 Some((first, n)) if n != after => {
10422 refused = Some(format!(
10423 "at {speed} the {} half of the silence at frame {at} would cover \
10424 {after} frames and the {} half {n}: they are one take and a take \
10425 is one span -- detach them first",
10426 labels[l].label(),
10427 first.label()
10428 ));
10429 }
10430 Some(_) => {}
10431 }
10432 }
10433 }
10434 let shrunk = match (refused, room) {
10435 (Some(e), _) => {
10436 self.roll_back_snapshot();
10437 return Err(e.into());
10438 }
10439 // A gap on every lane: nothing to re-rate, and nothing to close.
10440 (None, None) => continue,
10441 (None, Some((_, after))) => after,
10442 };
10443 // The region's new length, on every scoped lane alike.
10444 let after = shrunk;
10445 let Some(delta) = len.checked_sub(shrunk) else {
10446 self.roll_back_snapshot();
10447 return Err(format!(
10448 "the silence at frame {at} already plays faster than {speed}: \
10449 at that rate it would be {shrunk} frames instead of {len}"
10450 )
10451 .into());
10452 };
10453 for &l in &on {
10454 for c in &mut self.lanes[l].clips {
10455 if c.start == at && c.end() == at + len {
10456 c.speed = speed;
10457 } else if c.start >= at + len {
10458 c.start -= delta;
10459 }
10460 }
10461 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
10462 // The captions on a scoped lane travel with the region's time:
10463 // a piece inside it plays in `after` frames instead of `len`
10464 // -- same words on less timeline, its window untouched, for
10465 // [`write_speed`]'s reason -- and everything behind the region
10466 // slides up by what the region gave back.
10467 //
10468 // The pieces inside re-time by their *boundaries*, not each
10469 // on its own: rounding one piece's start and its neighbour's
10470 // start apart can land both on the same frame (two one-frame
10471 // cues of a thirty-frame region at 2x both want frame 15), so
10472 // the mapped boundaries are walked in order and forced apart
10473 // -- each piece at least one frame, none past the region's own
10474 // new end, where the first follower lands exactly. A rounding
10475 // artifact is clamped, not refused: nothing about the words
10476 // asked for an overlap.
10477 let share = f64::from(after) / f64::from(len).max(1.);
10478 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
10479 let mut prev = at;
10480 let subs = &mut self.lanes[l].subs;
10481 for sub in subs.iter_mut() {
10482 let s = *sub;
10483 if s.start >= at + len {
10484 sub.start = s.start - delta;
10485 } else if s.start >= at && s.end() <= at + len {
10486 let mut start = map(s.start).max(prev);
10487 let end = map(s.end()).max(start + 1).min(at + after);
10488 start = start.min(end - 1);
10489 sub.start = start;
10490 sub.frames = end - start;
10491 prev = end;
10492 }
10493 }
10494 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
10495 }
10496 }
10497 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10498 self.settle();
10499 Ok(())
10500 }
10501
10502 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
10503 /// -- the whole-group delete a single-lane front-end means. `false` for a
10504 /// bad index. Changes the mapping: the caller must reseek.
10505 pub fn delete(&mut self, idx: usize) -> bool {
10506 self.delete_in(Lane::V1, idx)
10507 }
10508
10509 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
10510 /// in no group (or a group of one, which is the same thing to a delete) is
10511 /// what it always was: its own span cut out of *every* lane, so the
10512 /// timeline closes up under it. A clip in a group takes the group with it,
10513 /// each member by its **own** span and on its **own** lane -- the members
10514 /// keep their offsets, so their spans may disagree, and the lanes may end
10515 /// up out of step with each other, which is inherent to a hand-built group
10516 /// and one undo away. Every member -- clips and captions alike -- goes by
10517 /// the same law: its own span out of its own lane, hole closed; a caption
10518 /// in no group keeps the lift that leaves a gap, which is its own door's
10519 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
10520 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
10521 /// index, and for a lane that is not there. Changes the mapping: the
10522 /// caller must reseek.
10523 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
10524 let Some(members) = self.group_of(lane, idx) else {
10525 return false;
10526 };
10527 if !members.alone() {
10528 return self.delete_members(&members);
10529 }
10530 let Some(clip) = self.lane(lane).get(idx).cloned() else {
10531 return false;
10532 };
10533 self.ripple_delete(clip.start, clip.frames())
10534 }
10535
10536 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
10537 /// caption in no group lifts, exactly as its own key always made it
10538 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
10539 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
10540 /// span out of its own lane, hole closed, captions and clips alike.
10541 /// `false` for a bad index.
10542 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
10543 let Some(members) = self.group_of(lane, idx) else {
10544 return false;
10545 };
10546 if !members.alone() {
10547 return self.delete_members(&members);
10548 }
10549 self.lift_sub(lane, idx)
10550 }
10551
10552 /// The one whole-group delete both doors land in: every member's own span
10553 /// cut out of its own lane and the hole closed there -- clips and
10554 /// captions by the same law -- and nothing else on another lane moves,
10555 /// which is what keeps one member's ripple from dragging another
10556 /// member's lane out from under it. One snapshot, one undo step.
10557 fn delete_members(&mut self, members: &Members) -> bool {
10558 self.snapshot();
10559 for &(l, i) in &members.clips {
10560 let c = self.lanes[l].clips[i].clone();
10561 ripple(&mut self.lanes, &[l], c.start, c.frames());
10562 }
10563 // The captions go by the same law their clip siblings do -- the span
10564 // out of its own lane, the hole closed -- and not by the lift a
10565 // *lone* caption's delete is: deleted with its group, the words after
10566 // it slide up with everything else, or the lane the group emptied is
10567 // the one lane the delete left a hole in. `ripple` is the one
10568 // mechanism (it clears the span and shifts the rest, clips and
10569 // captions alike); a sub lane holds no clips, so its other list is
10570 // untouched.
10571 for &(l, i) in &members.subs {
10572 let s = self.lanes[l].subs[i];
10573 ripple(&mut self.lanes, &[l], s.start, s.frames);
10574 }
10575 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10576 true
10577 }
10578
10579 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
10580 #[cfg(test)]
10581 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
10582 self.lane(lane)
10583 }
10584
10585 /// The mark an action takes before it runs, for [`Project::name_step`]: the count
10586 /// of every step pushed so far. Settles a no-op first, so the mark is exact.
10587 pub(crate) fn step_mark(&mut self) -> u64 {
10588 self.settle();
10589 self.pushes
10590 }
10591
10592 /// Names the newest undo step, but only when the action that took `mark` pushed one:
10593 /// an action that changed nothing, or only undid, names nothing. The name is what
10594 /// Undo and Redo say about this step ([`Project::undo_label`]) and it leaves with
10595 /// the step, so a settled no-op or a capped-out step takes its name with it.
10596 pub(crate) fn name_step(&mut self, mark: u64, label: &str) {
10597 self.settle();
10598 if self.pushes > mark
10599 && let Some(top) = self.history.last_mut()
10600 {
10601 top.label = Some(label.to_string());
10602 }
10603 }
10604
10605 /// The name of the step [`Project::undo`] would take back; `None` when that step
10606 /// was never named, or when there is nothing to undo.
10607 pub fn undo_label(&self) -> Option<&str> {
10608 let top = match self.settling_no_op() {
10609 // The no-op is the newest step; settling it leaves the one under it on top.
10610 Some(_) => self.history.len().checked_sub(2).and_then(|i| self.history.get(i)),
10611 None => self.history.last(),
10612 };
10613 top.and_then(|s| s.label.as_deref())
10614 }
10615
10616 /// The name of the step [`Project::redo`] would walk forward to; `None` when that
10617 /// step was never named, or when there is nothing to redo.
10618 pub fn redo_label(&self) -> Option<&str> {
10619 let stack = match self.settling_no_op() {
10620 Some(pending) => &pending.redo,
10621 None => &self.redo,
10622 };
10623 stack.last().and_then(|s| s.label.as_deref())
10624 }
10625
10626 /// How many undo steps are stacked: what the sweep asks so "one op, one
10627 /// snapshot" is a count and not a guess.
10628 /// The name of every step [`Project::undo`] can take back, oldest first; `None` for a step
10629 /// nobody named. The last one is the step the project is on.
10630 pub fn undo_labels(&self) -> Vec<Option<String>> {
10631 let n = self.history_len();
10632 self.history.iter().take(n).map(|s| s.label.clone()).collect()
10633 }
10634
10635 /// The name of every step [`Project::redo`] can walk forward to, the next one last (the
10636 /// mirror of [`undo_labels`](Project::undo_labels)).
10637 pub fn redo_labels(&self) -> Vec<Option<String>> {
10638 let stack = match self.settling_no_op() {
10639 Some(pending) => &pending.redo,
10640 None => &self.redo,
10641 };
10642 stack.iter().map(|s| s.label.clone()).collect()
10643 }
10644
10645 pub(crate) fn history_len(&self) -> usize {
10646 match self.settling_no_op() {
10647 // The no-op's step goes, and the one it evicted comes back.
10648 Some(pending) => self.history.len() - 1 + usize::from(pending.evicted.is_some()),
10649 None => self.history.len(),
10650 }
10651 }
10652
10653 /// Every snapshot pushed so far, including those the cap has since dropped.
10654 pub(crate) fn history_pushes(&self) -> u64 {
10655 match self.settling_no_op() {
10656 Some(_) => self.pushes.saturating_sub(1),
10657 None => self.pushes,
10658 }
10659 }
10660
10661 /// Which state the project is in: a fresh id after every edit, and the id the
10662 /// state had before it after an undo, so equal revisions mean the same
10663 /// timeline. Never reused, so a revision names one state for good.
10664 pub fn revision(&self) -> u64 {
10665 match (self.settling_no_op(), self.history.last()) {
10666 (Some(_), Some(top)) => top.revision,
10667 _ => self.revision,
10668 }
10669 }
10670
10671 /// Drops the redo stack without a step: for a caller whose own trial edits
10672 /// were rolled back, which left their undone states here to redo.
10673 pub(crate) fn clear_redo(&mut self) {
10674 self.settle();
10675 self.redo.clear();
10676 }
10677
10678 /// Moves the redo stack out, leaving it empty, for a caller whose trial edits
10679 /// are about to run and may be rolled back. [`Project::restore_redo`] puts it
10680 /// back exactly, replacing whatever the trial's own undo steps left on it.
10681 pub(crate) fn take_redo(&mut self) -> RedoCheckpoint {
10682 self.settle();
10683 RedoCheckpoint(std::mem::take(&mut self.redo))
10684 }
10685
10686 /// Puts back a stack [`Project::take_redo`] took out.
10687 pub(crate) fn restore_redo(&mut self, cp: RedoCheckpoint) {
10688 self.settle();
10689 self.redo = cp.0;
10690 }
10691
10692 /// Lets the undo history run past [`HISTORY_CAP`] while a trial batch is open,
10693 /// so the trial's pushes evict nothing; closing it (`false`) trims the history
10694 /// back to the cap, dropping the oldest steps as an edit would.
10695 pub(crate) fn hold_history(&mut self, hold: bool) {
10696 self.settle();
10697 self.hold_cap = hold;
10698 if !hold {
10699 let over = self.history.len().saturating_sub(HISTORY_CAP);
10700 self.history.drain(..over);
10701 }
10702 }
10703
10704 /// How many redo steps are stacked: what the sweep asks to check `undo`
10705 /// left a branch behind, and that a fresh edit clears it.
10706 pub(crate) fn redo_len(&self) -> usize {
10707 match self.settling_no_op() {
10708 Some(pending) => pending.redo.len(),
10709 None => self.redo.len(),
10710 }
10711 }
10712
10713 /// The project's own settings as they stand ([`ProjectSettings`]) -- what an
10714 /// undo entry holds beside the lanes, and what the session reads back after
10715 /// one is restored ([`crate::PlaybackSession::undo`]).
10716 pub(crate) fn settings_now(&self) -> ProjectSettings {
10717 self.settings.clone()
10718 }
10719
10720 /// One undo step for a change to the project's own settings: `from` is the
10721 /// state the change is from and `now` the one it leaves behind. The entry
10722 /// pushed holds `from`, while the copy kept here is `now` -- so the next
10723 /// lane edit's own entry carries the canvas and the rate really in force
10724 /// rather than the ones before the pick. The lanes the entry holds are the
10725 /// ones in place at the call: a settings door leaves them alone and may
10726 /// take this step after its change, and one that moves them
10727 /// ([`Project::retime`] on a rate change) takes it before, with `now` equal
10728 /// to `from`, mirroring the new state afterwards
10729 /// ([`Project::mirror_settings`]).
10730 pub(crate) fn push_settings_step(&mut self, from: ProjectSettings, now: ProjectSettings) {
10731 self.settle();
10732 self.settings = from;
10733 self.snapshot();
10734 self.settings = now;
10735 }
10736
10737 /// Keeps `now` as this project's copy of its own settings, without a step:
10738 /// the second half of a settings door that had to take its step before the
10739 /// change.
10740 pub(crate) fn mirror_settings(&mut self, now: ProjectSettings) {
10741 self.settle();
10742 self.settings = now;
10743 }
10744
10745 /// Every part of the project that an edit can change, as comparable
10746 /// values: what the sweep's undo round-trip asks "byte identical?" of.
10747 #[cfg(test)]
10748 pub(crate) fn parts(&self) -> SweepParts {
10749 SweepParts(
10750 self.sources.len(),
10751 self.lanes
10752 .iter()
10753 .map(|l| (l.kind, l.clips.clone()))
10754 .collect(),
10755 self.lanes.iter().map(|l| l.subs.clone()).collect(),
10756 self.subtitles.clone(),
10757 self.settings.clone(),
10758 )
10759 }
10760
10761 /// Restore everything from before the last successful edit -- the lanes,
10762 /// the subtitle palette, the project's own settings and the sources (a
10763 /// relink is undone by the old path coming back). `false` when there
10764 /// is nothing left to undo. Pushes what was just left onto the redo stack,
10765 /// so [`Project::redo`] can walk forward again.
10766 pub fn undo(&mut self) -> bool {
10767 self.settle();
10768 match self.history.pop() {
10769 Some(prev) => {
10770 self.batch_snapped = false;
10771 self.pending = None;
10772 let displaced = self.swap_state(prev);
10773 self.redo.push(displaced);
10774 true
10775 }
10776 None => false,
10777 }
10778 }
10779
10780 /// Restore everything from before the last [`Project::undo`] -- the
10781 /// mirror of `undo`, walking the redo stack it fills. `false` when there
10782 /// is nothing left to redo, which is also true after any fresh edit: a
10783 /// new [`Project::snapshot`] clears the branch `undo` left behind.
10784 pub fn redo(&mut self) -> bool {
10785 self.settle();
10786 match self.redo.pop() {
10787 Some(next) => {
10788 self.batch_snapped = false;
10789 self.pending = None;
10790 let displaced = self.swap_state(next);
10791 self.history.push(displaced);
10792 true
10793 }
10794 None => false,
10795 }
10796 }
10797
10798 /// Puts `to` back as the project's state and returns the state it replaced,
10799 /// as the snapshot an undo or redo of that replacement restores.
10800 fn swap_state(&mut self, to: Snapshot) -> Snapshot {
10801 let sources = restored_sources(to.sources, &self.sources);
10802 let displaced = Snapshot {
10803 revision: std::mem::replace(&mut self.revision, to.revision),
10804 label: to.label.clone(),
10805 lanes: std::mem::replace(&mut self.lanes, to.lanes),
10806 subtitles: self.subtitles.clone(),
10807 cue_edits: self.cue_edits.clone(),
10808 cue_adds: self.cue_adds.clone(),
10809 titles: self.titles.clone(),
10810 chapters: self.chapters.clone(),
10811 markers: self.markers.clone(),
10812 settings: self.settings.clone(),
10813 sources: std::mem::replace(&mut self.sources, sources),
10814 bins: std::mem::replace(&mut self.bins, to.bins),
10815 seq: std::mem::replace(&mut self.seq, to.seq),
10816 };
10817 self.flat.clear();
10818 self.subtitles = to.subtitles;
10819 self.cue_edits = to.cue_edits;
10820 self.cue_adds = to.cue_adds;
10821 self.titles = to.titles;
10822 self.chapters = to.chapters;
10823 self.markers = to.markers;
10824 self.settings = to.settings;
10825 displaced
10826 }
10827
10828 /// Half-open `(source, start, end)` segments in *source* seconds, from
10829 /// `timeline_frame` to the end of the timeline -- the play list for the
10830 /// audio worker, read off **`A1`**. A `None` source is a gap: the
10831 /// worker synthesises that many seconds of silence, which is what keeps the
10832 /// audio master clock counting across a hole instead of stalling on it.
10833 /// The first entry is partial when the position is mid-clip. Empty when the
10834 /// position is past the end or `fps` is not usable.
10835 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
10836 self.lane_segments_from(Lane::A1, timeline_frame, fps)
10837 }
10838
10839 /// [`segments_from`](Project::segments_from) for a named lane.
10840 pub fn lane_segments_from(
10841 &self,
10842 lane: Lane,
10843 timeline_frame: u32,
10844 fps: f64,
10845 ) -> Vec<(Option<usize>, f64, f64)> {
10846 if !(fps.is_finite() && fps > 0.0) {
10847 return Vec::new();
10848 }
10849 self.spans_from(lane, timeline_frame)
10850 .iter()
10851 .map(|span| match span.from {
10852 // A clip's window is in *source* seconds: where in the file it
10853 // reads from, which a delete before it never shifts. How many
10854 // source frames that is, is the span's own arithmetic -- at a
10855 // speed it is not the timeline length ([`Span::source_len`]).
10856 Some(_) => {
10857 let (source, lo, hi) = span.source_window().expect("a clip's span");
10858 (Some(source), f64::from(lo) / fps, f64::from(hi) / fps)
10859 }
10860 // A gap has no file, so all it can say is how long it is.
10861 None => (None, 0.0, f64::from(span.len) / fps),
10862 })
10863 .collect()
10864 }
10865
10866 /// One play list per audio lane that *holds* something, in display order --
10867 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
10868 /// what an export asks how many lanes it would have to mix.
10869 ///
10870 /// Never empty: a timeline whose audio lanes are all empty (or which has no
10871 /// audio lane at all) still yields one all-gap list, so it plays silence
10872 /// against a master clock exactly as it did before there were lanes to
10873 /// count. Lanes with nothing on them are left out rather than mixed in as
10874 /// silence: they would cost a decode thread each and add zero.
10875 pub fn audio_segments_from(
10876 &self,
10877 timeline_frame: u32,
10878 fps: f64,
10879 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
10880 self.audio_lanes()
10881 .into_iter()
10882 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
10883 .collect()
10884 }
10885
10886 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
10887 /// builds a play list for, in the same order. Public because everything
10888 /// asked per audio lane -- which clip a segment's equalizer belongs to,
10889 /// which lane an mp4 export would copy -- has to read the very list the
10890 /// sound comes off, or the two answers drift apart (which is exactly how an
10891 /// `A2`-only project once exported silently, ledger).
10892 pub fn audio_lanes(&self) -> Vec<Lane> {
10893 let lanes: Vec<Lane> = self
10894 .lanes()
10895 .into_iter()
10896 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
10897 .collect();
10898 match lanes.is_empty() {
10899 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
10900 // no sound still plays silence against the master clock.
10901 true => vec![Lane::A1],
10902 false => lanes,
10903 }
10904 }
10905
10906 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
10907 /// segments plays at, and how long the timeline gives it: the same lanes in
10908 /// the same order, one entry per segment, `None` for a segment at real time
10909 /// -- which is every segment of a project nobody has speeded, and the path
10910 /// the audio worker leaves bit-identical.
10911 ///
10912 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
10913 /// the segment tuple is what every opener and a dozen tests speak, and a
10914 /// rate is not part of *which samples* a segment names.
10915 ///
10916 /// The seconds are what makes a resample exact: a segment's own window
10917 /// resolves to whole source frames, and dividing that by the rate would
10918 /// leave each clip a fraction of a frame short or long -- a drift that grows
10919 /// clip by clip. Told how much timeline it owes, the worker pads or trims
10920 /// the last few samples of each segment instead, so the sound stays locked
10921 /// to the picture however many speeded cuts it walks through.
10922 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
10923 self.audio_lanes()
10924 .into_iter()
10925 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
10926 .collect()
10927 }
10928
10929 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
10930 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
10931 /// same walk, same `fps` refusal.
10932 pub fn lane_speeds_from(
10933 &self,
10934 lane: Lane,
10935 timeline_frame: u32,
10936 fps: f64,
10937 ) -> Vec<Option<Stretch>> {
10938 if !(fps.is_finite() && fps > 0.0) {
10939 return Vec::new();
10940 }
10941 self.spans_from(lane, timeline_frame)
10942 .iter()
10943 .map(|span| {
10944 // A ramp's `step` is its mean rate over the span (the source it reads
10945 // over the timeline it fills), the fallback; the stretch follows the
10946 // ramp itself through `ramp`.
10947 let ramped = span.ramp.is_some();
10948 let step = match span.ramp {
10949 Some(_) => f64::from(span.source_len()) / f64::from(span.len),
10950 None => span.speed.as_f64(),
10951 };
10952 (ramped || !span.speed.is_normal() || span.reverse || span.pitch != 0).then(|| Stretch {
10953 step,
10954 timeline_secs: f64::from(span.len) / fps,
10955 reverse: span.reverse,
10956 ramp: span.ramp,
10957 fps,
10958 pitch: span.pitch,
10959 })
10960 })
10961 .collect()
10962 }
10963
10964 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
10965 /// segments plays through: the same lanes in the same order, one entry per
10966 /// segment, `None` where the segment is a gap or its clip plays flat.
10967 ///
10968 /// A parallel list rather than a fourth element of the segment tuple: that
10969 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
10970 /// and an effect is not part of *which samples* a segment names. A short
10971 /// list therefore means "flat from here on" rather than a length mismatch --
10972 /// see [`crate::AudioSession::open_mixed_streams_eq`].
10973 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
10974 self.audio_lanes()
10975 .into_iter()
10976 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
10977 .collect()
10978 }
10979
10980 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
10981 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
10982 /// same walk, same `fps` refusal, so the two lists cannot come out different
10983 /// lengths.
10984 pub fn lane_eqs_from(
10985 &self,
10986 lane: Lane,
10987 timeline_frame: u32,
10988 fps: f64,
10989 ) -> Vec<Option<EqParams>> {
10990 if !(fps.is_finite() && fps > 0.0) {
10991 return Vec::new();
10992 }
10993 self.spans_from(lane, timeline_frame)
10994 .iter()
10995 // A span off a clip covers that clip's frames and no others, so its
10996 // own start names the clip -- the index a [`Span`] does not carry.
10997 .map(|span| {
10998 self.map(lane, span.start)
10999 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
11000 })
11001 .collect()
11002 }
11003
11004 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
11005 /// segments plays through: the same lanes in the same order, one entry per
11006 /// segment, `None` where the segment is a gap or its clip has neither a
11007 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
11008 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
11009 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
11010 self.audio_lanes()
11011 .into_iter()
11012 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
11013 .collect()
11014 }
11015
11016 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
11017 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
11018 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
11019 if !(fps.is_finite() && fps > 0.0) {
11020 return Vec::new();
11021 }
11022 let lane_pan = self.lane_pan(lane);
11023 self.spans_from(lane, timeline_frame)
11024 .iter()
11025 .map(|span| {
11026 let (idx, _) = self.map(lane, span.start)?;
11027 let clip = self.lane(lane).get(idx)?;
11028 (clip.fade_in > 0
11029 || clip.fade_out > 0
11030 || clip.gain_db != 0.0
11031 || clip.pan != 0
11032 || lane_pan != 0.0
11033 || !clip.gain_keys.is_empty())
11034 .then(|| Fade {
11035 // `span.len` is the clip's own remaining frames from
11036 // `span.start` on -- shorter than `clip.frames()` only
11037 // when this is the first span of a seek mid-clip.
11038 elapsed: clip.frames().saturating_sub(span.len),
11039 fade_in: clip.fade_in,
11040 fade_out: clip.fade_out,
11041 total: clip.frames(),
11042 gain: db_to_linear(clip.gain_db),
11043 pan: pan_gains(clip.pan_value(), lane_pan),
11044 curve: clip_curve(clip),
11045 })
11046 })
11047 .collect()
11048 }
11049
11050 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
11051 /// it has decided it will succeed -- a refusal must not cost an undo step.
11052 /// Clears the redo stack: a fresh edit branches off from here, so whatever
11053 /// `undo` had left to redo is no longer where this edit leads back to.
11054 fn snapshot(&mut self) {
11055 self.flat.clear();
11056 if self.batching && self.batch_snapped {
11057 // The open batch already holds its one step, taken before its first edit.
11058 self.redo.clear();
11059 self.revision = next_revision();
11060 return;
11061 }
11062 // A no-op left on top is dropped first, so it never stacks as a step of its own,
11063 // evicts one, or clears a redo branch it did not displace.
11064 self.settle();
11065 let evicted = match !self.hold_cap && self.history.len() == HISTORY_CAP {
11066 true => Some(self.history.remove(0)),
11067 false => None,
11068 };
11069 let redo = std::mem::take(&mut self.redo);
11070 self.pending = Some(PendingStep { redo, evicted });
11071 self.pushes += 1;
11072 self.history.push(Snapshot {
11073 revision: self.revision,
11074 label: None,
11075 lanes: self.lanes.clone(),
11076 subtitles: self.subtitles.clone(),
11077 cue_edits: self.cue_edits.clone(),
11078 cue_adds: self.cue_adds.clone(),
11079 titles: self.titles.clone(),
11080 chapters: self.chapters.clone(),
11081 markers: self.markers.clone(),
11082 settings: self.settings.clone(),
11083 sources: self.sources.clone(),
11084 bins: self.bins.clone(),
11085 seq: self.seq.clone(),
11086 });
11087 self.batch_snapped = self.batching;
11088 self.revision = next_revision();
11089 }
11090
11091 /// Whether the project is exactly the state the newest undo step restores.
11092 /// Every field a step holds is compared, the sources in full (their own `==`
11093 /// ignores the library's star and bin, which an edit may change).
11094 fn matches_newest_step(&self) -> bool {
11095 let Some(top) = self.history.last() else {
11096 return false;
11097 };
11098 let same_sources = top.sources.len() == self.sources.len()
11099 && top.sources.iter().zip(&self.sources).all(|(a, b)| {
11100 a == b && a.fav == b.fav && a.bin == b.bin
11101 });
11102 top.lanes == self.lanes
11103 && top.subtitles == self.subtitles
11104 && top.cue_edits == self.cue_edits
11105 && top.cue_adds == self.cue_adds
11106 && top.titles == self.titles
11107 && top.chapters == self.chapters
11108 && top.markers == self.markers
11109 && top.settings == self.settings
11110 && same_sources
11111 && top.bins == self.bins
11112 && top.seq == self.seq
11113 }
11114
11115 /// Takes back the step this method's own [`Project::snapshot`] pushed, when
11116 /// the method refuses after it has already changed things. Unlike
11117 /// [`Project::undo`] it does not settle first: a refused edit that changed
11118 /// nothing must still take back its own step, not an earlier real one. The
11119 /// redo branch the snapshot displaced comes back exactly as it was.
11120 fn roll_back_snapshot(&mut self) {
11121 let Some(pending) = self.pending.take() else {
11122 self.undo();
11123 return;
11124 };
11125 let Some(prev) = self.history.pop() else {
11126 return;
11127 };
11128 self.swap_state(prev);
11129 self.redo = pending.redo;
11130 if let Some(old) = pending.evicted {
11131 self.history.insert(0, old);
11132 }
11133 self.pushes = self.pushes.saturating_sub(1);
11134 self.batch_snapped = false;
11135 }
11136
11137 /// The pending step, when it is a no-op that [`Project::settle`] would drop.
11138 /// Every reader looks through it, so a no-op never shows as a step, a new
11139 /// revision or a cleared redo branch, whether or not anything has settled it yet.
11140 fn settling_no_op(&self) -> Option<&PendingStep> {
11141 self.pending.as_ref().filter(|_| self.matches_newest_step())
11142 }
11143
11144 /// Takes back the step the last edit pushed when that edit left the project
11145 /// as it was: no undo step, the revision it started from, and the redo branch
11146 /// it displaced put back. Nothing is dropped unless the step is the newest
11147 /// one this project pushed and the state matches it exactly. Outside a batch
11148 /// the step is then settled, so a later edit cannot pick it up. Every snapshot,
11149 /// undo and redo settles first, so a no-op is gone before anything builds on it.
11150 pub(crate) fn settle(&mut self) {
11151 if self.pending.is_some() && self.matches_newest_step() {
11152 let (Some(prev), Some(pending)) = (self.history.pop(), self.pending.take()) else {
11153 return;
11154 };
11155 self.revision = prev.revision;
11156 self.redo = pending.redo;
11157 if let Some(old) = pending.evicted {
11158 self.history.insert(0, old);
11159 }
11160 self.pushes = self.pushes.saturating_sub(1);
11161 self.batch_snapped = false;
11162 self.flat.clear();
11163 }
11164 if !self.batching {
11165 self.pending = None;
11166 }
11167 }
11168
11169 /// Starts a batch: until [`Project::end_batch`], every edit shares one undo
11170 /// step, the snapshot taken before the batch's first edit. Idempotent while open.
11171 pub fn begin_batch(&mut self) {
11172 if !self.batching {
11173 self.batching = true;
11174 self.batch_snapped = false;
11175 }
11176 }
11177
11178 /// Ends the batch [`Project::begin_batch`] opened. The next edit takes its own step.
11179 pub fn end_batch(&mut self) {
11180 if self.batching {
11181 self.settle();
11182 }
11183 self.batching = false;
11184 self.batch_snapped = false;
11185 self.pending = None;
11186 }
11187
11188 fn new_link(&mut self) -> u32 {
11189 let id = self.next_link;
11190 self.next_link = self.next_link.saturating_add(1);
11191 id
11192 }
11193}
11194
11195/// The handle of every lane, in storage order -- the one definition of what
11196/// [`Lane::ord`] counts.
11197fn handles(lanes: &[LaneData]) -> Vec<Lane> {
11198 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
11199 lanes
11200 .iter()
11201 .map(|l| match l.kind {
11202 LaneKind::Video => {
11203 video += 1;
11204 Lane::new(LaneKind::Video, video - 1)
11205 }
11206 LaneKind::Audio => {
11207 audio += 1;
11208 Lane::new(LaneKind::Audio, audio - 1)
11209 }
11210 LaneKind::Subtitle => {
11211 subtitle += 1;
11212 Lane::new(LaneKind::Subtitle, subtitle - 1)
11213 }
11214 })
11215 .collect()
11216}
11217
11218/// The one law a caption re-time scales by: frame `f` moves about the held
11219/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
11220/// commits it, [`Project::speeded_playhead`] previews it -- both build their
11221/// [`TimelineMap`] piece from this single answer so the two cannot drift
11222/// apart by a frame the way they once did.
11223fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
11224 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
11225 .round()
11226 .clamp(0., f64::from(u32::MAX)) as u32
11227}
11228
11229/// Where in the source a clip's `clip_frame`th timeline frame plays, fractional:
11230/// its in-point plus the speed's integral up to that frame. The one place the two
11231/// frame spaces meet, so a speed cannot be applied twice or forgotten in one of
11232/// them. At a constant speed the position is whole (the floored
11233/// [`Speed::source_at`]), so `floor` of it is that path's frame exactly; with a
11234/// ramp ([`Clip::speed_keys`]) it is the continuous integral and the frame is its
11235/// floor.
11236pub fn source_pos(clip: &Clip, clip_frame: u32) -> f64 {
11237 let offset = if clip.speed_keys.is_empty() {
11238 f64::from(clip.speed.source_at(clip_frame))
11239 } else {
11240 ramp_source_at(&clip.speed_keys, f64::from(clip_frame))
11241 };
11242 match clip.reversed {
11243 // Walked from the window's last frame down. The whole frames travelled are
11244 // what is mirrored (`out - 1 - floor`), so a ramp's fraction cannot lift the
11245 // floor of the frame shown, and the first frame is the last one of the window.
11246 true => f64::from(clip.out_frame - 1) - offset.floor() + offset.fract(),
11247 false => f64::from(clip.in_frame) + offset,
11248 }
11249}
11250
11251/// Where the source-keyed things of a clip (its placement and volume keys) are read
11252/// at `timeline_frame`: the playing source position, fractional. At a constant
11253/// speed this is its own expression, so an unramped, unreversed clip is bit-identical
11254/// to what it was before there were ramps.
11255/// The source position a key is sampled at: [`key_pos`] rounded to a whole frame,
11256/// the frame [`Project::key_source_frame`] writes a key at. A key is read back
11257/// exactly where it was written; sampling the fraction would blend it with its
11258/// neighbour (a typed 40% on a 1.5x clip reads 41%).
11259pub(crate) fn key_sample_pos(clip: &Clip, timeline_frame: u32) -> f64 {
11260 key_pos(clip, timeline_frame).round()
11261}
11262
11263fn key_pos(clip: &Clip, timeline_frame: u32) -> f64 {
11264 let offset = timeline_frame.saturating_sub(clip.start);
11265 match (clip.speed_keys.is_empty(), clip.reversed) {
11266 (true, false) => f64::from(clip.in_frame) + f64::from(offset) * clip.speed.as_f64(),
11267 (true, true) => f64::from(clip.out_frame - 1) - f64::from(offset) * clip.speed.as_f64(),
11268 (false, false) => source_pos(clip, offset),
11269 // Continuous, unlike [`source_pos`]'s floor-exact walk: a key is interpolated,
11270 // and a saw-toothed position would make it jump.
11271 (false, true) => {
11272 f64::from(clip.out_frame - 1) - ramp_source_at(&clip.speed_keys, f64::from(offset))
11273 }
11274 }
11275}
11276
11277/// Which source frame a clip plays at `timeline_frame` -- [`source_pos`] floored.
11278/// Clamped inside the clip's own range: rounding at a slow rate can put the last
11279/// timeline frame of a clip a frame past its out-point, and a source frame outside
11280/// the range is one the next clip owns.
11281fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
11282 (source_pos(c, timeline_frame - c.start).floor() as u32).clamp(c.in_frame, c.out_frame - 1)
11283}
11284
11285/// The span a clip contributes from `timeline_frame` on: its speed field, and its ramp
11286/// when it has one, based at the span's own start.
11287pub(crate) fn span_speed_of(c: &Clip, timeline_frame: u32) -> (Speed, Option<SpeedRamp>) {
11288 if c.speed_keys.is_empty() {
11289 (c.speed, None)
11290 } else {
11291 let base = timeline_frame - c.start;
11292 (Speed::NORMAL, Some(SpeedRamp::new(&c.speed_keys, base)))
11293 }
11294}
11295
11296/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
11297/// finder generic makes the subtitle path use the same bounded-hole rules as
11298/// media lanes without teaching the media-specific take logic about captions.
11299trait GapPlacement {
11300 fn start_frame(&self) -> u32;
11301 fn end_frame(&self) -> u32;
11302}
11303
11304impl GapPlacement for Clip {
11305 fn start_frame(&self) -> u32 {
11306 self.start
11307 }
11308
11309 fn end_frame(&self) -> u32 {
11310 self.end()
11311 }
11312}
11313
11314impl GapPlacement for SubClip {
11315 fn start_frame(&self) -> u32 {
11316 self.start
11317 }
11318
11319 fn end_frame(&self) -> u32 {
11320 self.end()
11321 }
11322}
11323
11324/// Index of the placement covering `frame`, or `None` for a gap or past the
11325/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
11326fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
11327 let idx = items
11328 .partition_point(|item| item.start_frame() <= frame)
11329 .checked_sub(1)?;
11330 (frame < items[idx].end_frame()).then_some(idx)
11331}
11332
11333/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
11334/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
11335/// invariant like [`at`]: the first placement whose start is past `frame` is
11336/// the far wall, and the last one that ends at or before `frame` (or the
11337/// timeline's own head, `0`, when there is none) is the near one.
11338fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
11339 if at(items, frame).is_some() {
11340 return None;
11341 }
11342 let idx = items.partition_point(|item| item.start_frame() <= frame);
11343 let next = items.get(idx)?;
11344 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
11345 Some((start, next.start_frame() - start))
11346}
11347
11348/// Every bounded hole in `items`, left to right. The tail after the last
11349/// placement is deliberately absent: there is no later placement for a ripple
11350/// to bring back.
11351fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
11352 let mut out = Vec::new();
11353 let mut next = 0;
11354 for item in items {
11355 if item.start_frame() > next {
11356 out.push((next, item.start_frame() - next));
11357 }
11358 next = item.end_frame();
11359 }
11360 out
11361}
11362
11363/// The clip's gain envelope in clip-relative timeline frames, or `None` when it
11364/// has no points. Source frame `s` is reached `(s - in_frame) / speed` timeline
11365/// frames in, which is exact because a speed is one linear rate.
11366fn clip_curve(clip: &Clip) -> Option<std::sync::Arc<[(f64, f32, KeyEase)]>> {
11367 if clip.gain_keys.is_empty() {
11368 return None;
11369 }
11370 let step = clip.speed.as_f64();
11371 let base = f64::from(clip.in_frame);
11372 let mut curve: Vec<(f64, f32, KeyEase)> = match clip.reversed {
11373 // The far end of the window is the clip's head, so the points are walked from
11374 // there and come out in time order the other way about.
11375 true => {
11376 let top = f64::from(clip.out_frame - 1);
11377 clip.gain_keys
11378 .iter()
11379 .enumerate()
11380 .rev()
11381 .map(|(n, k)| {
11382 // The segment that arrived at a point is the one that now leaves it.
11383 let ease = if n > 0 { clip.gain_keys[n - 1].ease } else { k.ease };
11384 ((top - f64::from(k.at)) / step, k.db, ease)
11385 })
11386 .collect()
11387 }
11388 false => clip
11389 .gain_keys
11390 .iter()
11391 .map(|k| ((f64::from(k.at) - base) / step, k.db, k.ease))
11392 .collect(),
11393 };
11394 curve.shrink_to_fit();
11395 Some(curve.into())
11396}
11397
11398/// `keys` walked from the far end of a window whose last frame is `top`, in the
11399/// order a reversed clip plays them: each point at source frame `p` moves to
11400/// `top - p`, and each segment keeps the easing it had, now leaving the point at
11401/// its other end. A point the mirror would put before frame 0 is dropped -- it lay
11402/// far outside the window, where nothing reads it.
11403fn mirrored<K: Clone>(
11404 keys: &[K],
11405 top: i64,
11406 at: impl Fn(&K) -> u32,
11407 ease: impl Fn(&K) -> KeyEase,
11408 with: impl Fn(&K, u32, KeyEase) -> K,
11409) -> Vec<K> {
11410 keys.iter()
11411 .enumerate()
11412 .rev()
11413 .filter_map(|(n, k)| {
11414 // The segment that arrived at this point is the one that now leaves it.
11415 let e = if n > 0 { ease(&keys[n - 1]) } else { ease(k) };
11416 Some(with(k, u32::try_from(top - i64::from(at(k))).ok()?, e))
11417 })
11418 .collect()
11419}
11420
11421/// Re-keys `c`'s source-keyed animation after its direction flipped: each point at
11422/// source frame `p` moves to `in + out - 1 - p`, the same footage frame seen from the
11423/// other end of the window, so the point stays on the timeline frame it was on.
11424fn mirror_keys(c: &mut Clip) {
11425 let top = i64::from(c.in_frame) + i64::from(c.out_frame) - 1;
11426 c.gain_keys = mirrored(&c.gain_keys, top, |k| k.at, |k| k.ease, |k, at, ease| GainKey { at, ease, ..*k });
11427 c.transform_keys =
11428 mirrored(&c.transform_keys, top, |k| k.at, |k| k.ease, |k, at, ease| TransformKey { at, ease, ..*k });
11429 c.opacity_keys = mirrored(&c.opacity_keys, top, |k| k.at, |k| k.ease, |k, at, ease| OpacityKey { at, ease, ..*k });
11430 c.color_keys = mirrored(&c.color_keys, top, |k| k.at, |k| k.ease, |k, at, ease| ColorKey { at, ease, ..*k });
11431 for e in &mut c.effects {
11432 e.keys = mirrored(&e.keys, top, |k| k.at, |k| k.ease, |k, at, ease| crate::effects::EffectKey { at, ease, ..*k });
11433 }
11434}
11435
11436/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
11437/// there would cut in two. A placement's own first frame is not inside it.
11438fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
11439 let idx = at(clips, frame)?;
11440 // ...and, on a speeded clip, one its rate can actually address
11441 // ([`Speed::split_at`]): a cut between two showings of one source frame
11442 // would leave halves that no longer add up to the clip that was cut.
11443 (frame > clips[idx].start)
11444 .then_some(idx)
11445 .filter(|&idx| split_source(&clips[idx], frame).is_some())
11446}
11447
11448/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
11449/// rate cannot address that frame.
11450fn split_source(c: &Clip, frame: u32) -> Option<u32> {
11451 if !c.speed_keys.is_empty() {
11452 // A reversed ramp is not cut yet: its far end would need the ramp mirrored.
11453 if c.reversed {
11454 return None;
11455 }
11456 return ramp_split(&c.speed_keys, c.len(), frame - c.start).map(|(src, _, _)| c.in_frame + src);
11457 }
11458 c.speed.split_at(c.len(), frame - c.start).map(|src| match c.reversed {
11459 // The head of a reversed clip is the window's far end, so the cut is that
11460 // far down from the out-point.
11461 true => c.out_frame - src,
11462 false => c.in_frame + src,
11463 })
11464}
11465
11466/// The speed keys each half of `c` keeps when it is cut at `frame`. Both empty for a
11467/// constant rate, which keeps its own [`Speed`] on both halves.
11468fn split_keys(c: &Clip, frame: u32) -> (Vec<SpeedKey>, Vec<SpeedKey>) {
11469 if c.speed_keys.is_empty() {
11470 return (Vec::new(), Vec::new());
11471 }
11472 match ramp_split(&c.speed_keys, c.len(), frame - c.start) {
11473 Some((_, head, tail)) => (head, tail),
11474 None => (Vec::new(), Vec::new()),
11475 }
11476}
11477
11478/// Where a ramped clip of `src_len` source frames can be cut at its clip-relative timeline
11479/// frame `off`, and the keys each half keeps. The source frame the tail starts at is
11480/// relative to the clip's in-point. `None` where the cut would not add up in whole frames
11481/// on both halves -- the ramp's own version of what [`Speed::split_at`] asks of a constant
11482/// rate. Reads at which the ramp lands near a frame boundary answer; the others do not.
11483pub fn ramp_split(keys: &[SpeedKey], src_len: u32, off: u32) -> Option<(u32, Vec<SpeedKey>, Vec<SpeedKey>)> {
11484 let len = ramp_frames(keys, src_len);
11485 if off == 0 || off >= len {
11486 return None;
11487 }
11488 let src = ramp_source_at(keys, f64::from(off)).round();
11489 if src < 1. || src >= f64::from(src_len) {
11490 return None;
11491 }
11492 let src = src as u32;
11493 let head = ramp_keys_until(keys, off);
11494 let tail = ramp_keys_from(keys, off);
11495 let whole = valid_speed_keys(&head)
11496 && valid_speed_keys(&tail)
11497 && ramp_frames(&head, src) == off
11498 && ramp_frames(&tail, src_len - src) == len - off;
11499 whole.then_some((src, head, tail))
11500}
11501
11502/// The keys of the part of a ramped clip up to clip-relative frame `cut`: the keys before
11503/// it, and the speed there as the last one when the ramp goes on past it. The ramp is held
11504/// to `cut` exactly as the whole ramp plays there, so the head's length comes back as `cut`.
11505pub fn ramp_keys_until(keys: &[SpeedKey], cut: u32) -> Vec<SpeedKey> {
11506 let mut out: Vec<SpeedKey> = keys.iter().copied().filter(|k| k.at < cut).collect();
11507 if keys.iter().any(|k| k.at > cut) {
11508 out.push(SpeedKey { at: cut, speed: ramp_speed_at(keys, cut) });
11509 }
11510 out
11511}
11512
11513/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
11514/// rejoin: they must touch there, and be consecutive frames of one source.
11515fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
11516 let idx = clips.iter().position(|c| c.end() == frame)?;
11517 let next = clips.get(idx + 1)?;
11518 let joined = clips[idx].len() + next.len();
11519 (next.start == frame
11520 && next.source == clips[idx].source
11521 && next.reversed == clips[idx].reversed
11522 && match clips[idx].reversed {
11523 // The halves of a reversed cut swap sides: the head holds the window's
11524 // upper part.
11525 true => clips[idx].in_frame == next.out_frame,
11526 false => next.in_frame == clips[idx].out_frame,
11527 }
11528 // ...at one rate, and one that puts the rejoined clip back in exactly
11529 // the room the two took up: what a split could have produced, which is
11530 // all this undoes.
11531 && next.speed == clips[idx].speed
11532 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
11533 .then_some(idx)
11534}
11535
11536/// The lane invariant: sorted by `start`, no two placements overlapping, no
11537/// empty placement. Checked at every constructor and asserted after every
11538/// mutation -- the offset model is only tractable while it holds.
11539/// The one thing an equalizer setting may not be: a value the text format
11540/// cannot write and read back as itself. Checked wherever params come in, so
11541/// what an edit produces is always what a save writes and a load reads.
11542fn finite(params: &EqParams) -> bool {
11543 params
11544 .bands
11545 .iter()
11546 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
11547}
11548
11549/// The same for a colour grade: [`crate::color`] itself falls back to identity
11550/// on a non-finite value, but a value that cannot be written and read back as
11551/// itself has no business reaching the model.
11552fn color_finite(p: &ColorParams) -> bool {
11553 let w = &p.look.wheels;
11554 w.lift.iter().chain(&w.gamma).chain(&w.gain).all(|v| v.is_finite())
11555 && p.look.lut_mix.is_finite()
11556 && p.brightness.is_finite()
11557 && p.contrast.is_finite()
11558 && p.saturation.is_finite()
11559 && p.tint.is_finite()
11560}
11561
11562/// The same for a transform: [`crate::scale`] clamps a non-finite value to
11563/// identity at read time, but a value that cannot round-trip has no business
11564/// reaching the model.
11565fn transform_finite(p: &TransformParams) -> bool {
11566 p.pos_x.is_finite()
11567 && p.pos_y.is_finite()
11568 && p.scale.is_finite()
11569 && p.rotate.is_finite()
11570 && p.crop_l.is_finite()
11571 && p.crop_r.is_finite()
11572 && p.crop_t.is_finite()
11573 && p.crop_b.is_finite()
11574 && (0.0..=1.0).contains(&p.opacity)
11575}
11576
11577fn sorted_disjoint(clips: &[Clip]) -> bool {
11578 clips.iter().all(|c| c.out_frame > c.in_frame)
11579 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
11580}
11581
11582/// The very same invariant on a subtitle lane, in that lane's own two units:
11583/// sorted by `start`, no two placements overlapping, no empty placement at
11584/// either end. Asserted after every mutation, exactly as its twin is.
11585fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
11586 subs.iter()
11587 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
11588 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
11589}
11590
11591/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
11592/// the one conversion between a lane's clock and a cue's, and `0` for a rate
11593/// that is not one (every caller of this has already refused such a rate).
11594fn us_of(frames: i64, fps: f64) -> i64 {
11595 match fps.is_finite() && fps > 0.0 {
11596 true => ((frames as f64) / fps * 1e6).round() as i64,
11597 false => 0,
11598 }
11599}
11600
11601/// **The one function in this file that writes a caption's window.** Every
11602/// composer -- a trim, a split, a ripple, a group follow, a rejoin -- routes
11603/// through it, and the invariant it holds is total:
11604///
11605/// ```text
11606/// 0 <= in_us and in_us < out_us and out_us - in_us <= MAX_WINDOW_US
11607/// ```
11608///
11609/// which is the never-empty invariant plus the width ceiling, restated as one
11610/// shape both ends of it come from. Note that the ceiling bounds a
11611/// **difference**, which is why a per-arm check is not enough and this is:
11612///
11613/// - Growing `out_us` (a tail trim) makes the width larger, so the *upper*
11614/// wall bites.
11615/// - Falling `in_us` (a head trim) makes the width larger too, from the other
11616/// side -- so bounding `in_us` alone, which is what a head trim's own clamp
11617/// (`in_us <= out_us - 1`) does, says nothing at all about the ceiling.
11618/// - A rejoin takes the left half's `in_us` and the right half's `out_us`, and
11619/// the two halves are consecutive in the *source* (that is what
11620/// [`sub_joinable`] requires), so the joined width is the **sum** of two
11621/// legal widths. Each half passes its own door; the whole does not.
11622///
11623/// Three rounds of review each found one more composer this way, so the
11624/// function is the fix rather than any single call site: clamping a new
11625/// caller into shape is a two-line change, and forgetting one is silent.
11626/// `every_window_write_goes_through_set_window` (in the tests below) is the
11627/// other half of that promise -- it scans the file and fails if a write
11628/// appears anywhere else.
11629///
11630/// **Why it clamps where the doors refuse.** The doors -- the parser,
11631/// [`Project::with_subs`], [`Project::place_sub`] -- see a value on the way
11632/// IN, from a file or a foreign caller, where nobody was mid-gesture, so a
11633/// value that wide is named and refused rather than quietly changed. Every
11634/// composer below is an edit a person is watching happen, so the same value is
11635/// clamped to the end of the window: a drag that stops, exactly like the frame
11636/// walls these trims already apply.
11637fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {
11638 let in_us = in_us.max(0);
11639 // The `+ 1` is the never-empty invariant: the window is open, always, so a
11640 // composer that would otherwise clamp it shut lands on one microsecond.
11641 let out_us = out_us.clamp(in_us + 1, in_us.saturating_add(MAX_WINDOW_US));
11642 s.in_us = in_us;
11643 s.out_us = out_us;
11644 debug_assert!(
11645 s.in_us >= 0 && s.out_us > s.in_us && s.out_us - s.in_us <= MAX_WINDOW_US,
11646 "set_window left an illegal window: {:?}",
11647 (s.in_us, s.out_us)
11648 );
11649}
11650
11651/// The two pieces a cue becomes when a window edge at `t_us` falls inside it:
11652/// `(start, end, text)` for the piece before the edge and the one after, the
11653/// words shared between them at the word boundary nearest the point that is the
11654/// same fraction of the words as `t_us` is of the time. A piece with no words is
11655/// left out. A cue with one word has no boundary to divide at, so that word
11656/// stays on the longer side of the edge (ties: the piece before it) and the
11657/// other side is left out too. `None` for a cue with no words at all.
11658fn split_words(c: &crate::subtitle::Cue, t_us: i64) -> Option<Vec<(i64, i64, String)>> {
11659 let text = c.text.as_str();
11660 let mut starts: Vec<usize> = Vec::new();
11661 let mut prev_space = true;
11662 for (i, ch) in text.char_indices() {
11663 let space = ch.is_whitespace();
11664 if !space && prev_space {
11665 starts.push(i);
11666 }
11667 prev_space = space;
11668 }
11669 let n = starts.len();
11670 if n == 0 {
11671 return None;
11672 }
11673 if n == 1 {
11674 let word = text.trim().to_string();
11675 let before = t_us - c.start_us;
11676 let after = c.end_us - t_us;
11677 return Some(if before >= after {
11678 vec![(c.start_us, t_us, word)]
11679 } else {
11680 vec![(t_us, c.end_us, word)]
11681 });
11682 }
11683 let p = (t_us - c.start_us) as f64 / (c.end_us - c.start_us) as f64;
11684 let k = ((p * n as f64).round() as usize).min(n);
11685 let mut out = Vec::with_capacity(2);
11686 if k >= 1 {
11687 let end = if k < n { starts[k] } else { text.len() };
11688 out.push((c.start_us, t_us, text[..end].trim_end().to_string()));
11689 }
11690 if k < n {
11691 out.push((t_us, c.end_us, text[starts[k]..].to_string()));
11692 }
11693 Some(out)
11694}
11695
11696/// [`split_words`] for one edge of a cut. With `both_sides` a one-word cue is
11697/// kept whole on both sides of the point, so the side the cut leaves in its
11698/// window survives: which side that is, only the ripple knows, and
11699/// [`Project::drop_unplaced`] drops the other. Every other cue is
11700/// [`split_words`]' division.
11701fn cut_pieces(c: &crate::subtitle::Cue, t_us: i64, both_sides: bool) -> Option<Vec<(i64, i64, String)>> {
11702 if both_sides && c.text.split_whitespace().count() == 1 {
11703 let word = c.text.trim().to_string();
11704 return Some(vec![(c.start_us, t_us, word.clone()), (t_us, c.end_us, word)]);
11705 }
11706 split_words(c, t_us)
11707}
11708
11709/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
11710/// dropping what is inside the hole, splitting what straddles it and trimming
11711/// what overlaps an edge. The windows follow the cut by proportion
11712/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
11713fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
11714 sub_clear_with(subs, start, end, &mut |_| (None, None));
11715}
11716
11717/// [`sub_clear`] with the (head, tail) links its pieces carry, as [`clear_with`] has for clips.
11718fn sub_clear_with(subs: &mut Vec<SubClip>, start: u32, end: u32, links: &mut dyn FnMut(Option<u32>) -> (Option<u32>, Option<u32>)) {
11719 let mut out = Vec::with_capacity(subs.len() + 1);
11720 for s in subs.drain(..) {
11721 if s.end() <= start || s.start >= end {
11722 out.push(s);
11723 continue;
11724 }
11725 if s.start < start {
11726 let cut = s.window_at(start);
11727 let (head_link, _) = links(s.link);
11728 let mut head = SubClip {
11729 frames: start - s.start,
11730 link: head_link,
11731 ..s
11732 };
11733 // `window_at` already answers inside the window, and `set_window`
11734 // is the shape that says so once, for every composer, rather than
11735 // leaving each of them to re-derive it.
11736 set_window(&mut head, s.in_us, cut);
11737 out.push(head);
11738 }
11739 if s.end() > end {
11740 let cut = s.window_at(end);
11741 let (_, tail_link) = links(s.link);
11742 let mut tail = SubClip {
11743 start: end,
11744 frames: s.end() - end,
11745 link: tail_link,
11746 ..s
11747 };
11748 set_window(&mut tail, cut, s.out_us);
11749 out.push(tail);
11750 }
11751 }
11752 *subs = out;
11753}
11754
11755/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
11756/// `len`, splitting a placement that straddles `at` so the two halves end up on
11757/// either side of the hole. A `len` of 0 is that split alone, which is what a
11758/// [`Project::split`] over a subtitle lane is.
11759fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
11760 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
11761 let s = subs[idx];
11762 let cut = s.window_at(at);
11763 let mut head = SubClip {
11764 frames: at - s.start,
11765 link: None,
11766 ..s
11767 };
11768 set_window(&mut head, s.in_us, cut);
11769 subs[idx] = head;
11770 let mut tail = SubClip {
11771 start: at,
11772 frames: s.end() - at,
11773 link: None,
11774 ..s
11775 };
11776 set_window(&mut tail, cut, s.out_us);
11777 subs.insert(idx + 1, tail);
11778 }
11779 for s in subs.iter_mut().filter(|s| s.start >= at) {
11780 s.start += len;
11781 }
11782}
11783
11784/// [`joinable`] for a subtitle lane: the first of the two placements a
11785/// [`Project::regroup`] at `frame` would rejoin. What a split could have
11786/// produced and nothing else -- they touch on the timeline, they read the same
11787/// track, and the second one's window carries on where the first's stopped.
11788fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
11789 let idx = subs.iter().position(|s| s.end() == frame)?;
11790 let next = subs.get(idx + 1)?;
11791 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
11792 .then_some(idx)
11793}
11794
11795/// How far one `edge` of the caption at `idx` may travel against its own lane's
11796/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
11797/// rate, which a caption *following* a group's trim does not have to be exact
11798/// about -- its own walls, its own one surviving frame, and nothing that needs
11799/// a clock.
11800fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
11801 let s = &subs[idx];
11802 match edge {
11803 Edge::Start => (idx.checked_sub(1).map_or(0, |p| subs[p].end()), s.end() - 1),
11804 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
11805 }
11806}
11807
11808/// Move one `edge` of `s` to timeline frame `to`, its window following by the
11809/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
11810/// forwards and backwards. The caption a group's trim is carrying has no rate
11811/// of its own and needs none: what one frame of it is worth in microseconds is
11812/// the window it already shows over the frames it already takes.
11813fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
11814 let per_frame = s.window_us() / i64::from(s.frames.max(1));
11815 // The `saturating_mul` keeps a `SubClip` that reached here without a door
11816 // behind it from wrapping the window negative; `set_window` is what keeps
11817 // the result legal rather than merely finite. This is the group-follow twin
11818 // of [`Project::trim_sub`], and it reaches the same field from both edges --
11819 // so a fix that only walled the primary trim's End arm left the head (and
11820 // the whole group path) open.
11821 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
11822 match edge {
11823 Edge::Start => {
11824 set_window(s, s.in_us.saturating_add(by(s.start, to)), s.out_us);
11825 s.frames = s.end() - to;
11826 s.start = to;
11827 }
11828 Edge::End => {
11829 set_window(s, s.in_us, s.out_us.saturating_add(by(s.end(), to)));
11830 s.frames = to - s.start;
11831 }
11832 }
11833 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
11834}
11835
11836/// The grouping invariant, checked in release at [`Project::from_parts`] and
11837/// asserted by the tests after every edit: a link id names **at most one**
11838/// placement per lane -- a clip on a media lane or a caption on a subtitle
11839/// one, whichever carries it. That is all "these move together" can mean now
11840/// that a group is assembled by hand: the members keep their own spans and
11841/// their own offsets, and what binds them is the id alone.
11842///
11843/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
11844/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
11845/// placements of one group may cover different frames -- the offset-preserving
11846/// group a hand builds with [`Project::group_all`], which a drag moves by one
11847/// delta rather than by one span.
11848///
11849/// A link no other lane carries is legal and is not an error: lifting one half
11850/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
11851/// timeline has to load again.
11852/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
11853/// asked by the sweep suite's universal law.
11854#[cfg(test)]
11855pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
11856 links_are_consistent(&p.lanes)
11857}
11858
11859/// What a take is, for [`Project::ungroup`]: the halves of one take read the
11860/// same source over the same frames, so they share these four numbers.
11861type TakeKey = (usize, u32, u32, u32);
11862
11863fn take_key(c: &Clip) -> TakeKey {
11864 (c.source, c.start, c.in_frame, c.out_frame)
11865}
11866
11867fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
11868 let handles = handles(lanes);
11869 for (data, lane) in lanes.iter().zip(&handles) {
11870 for (i, c) in data.clips.iter().enumerate() {
11871 let Some(id) = c.link else { continue };
11872 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
11873 return Err(
11874 format!("link {id} names two clips in the {} lane", lane.label()).into(),
11875 );
11876 }
11877 }
11878 // ...and the same for the captions, in their own list on the same lane:
11879 // a subtitle lane holds no `Clip`, so this is the only list a caption's
11880 // id could be doubled on.
11881 for (i, s) in data.subs.iter().enumerate() {
11882 let Some(id) = s.link else { continue };
11883 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
11884 return Err(
11885 format!("link {id} names two captions in the {} lane", lane.label()).into(),
11886 );
11887 }
11888 }
11889 }
11890 Ok(())
11891}
11892
11893/// Removes the timeline frames `[start, end)` from `clips`: placements inside
11894/// it go, one straddling it is split in two, one overlapping an edge is
11895/// trimmed. Source frames follow the trim, so what is left plays what it always
11896/// played. Leaves the lane sorted and disjoint.
11897///
11898/// A piece the hole cut is no longer the take its group id names -- and both
11899/// halves of a straddled placement carrying that id would be the same id twice
11900/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
11901fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
11902 clear_with(clips, start, end, &mut |_| (None, None));
11903}
11904
11905/// [`clear`] with the links the pieces it leaves carry: `links` gives the (head, tail) ids of a clip
11906/// that straddles the hole. `clear` itself gives both none, the detach rule of a delete.
11907fn clear_with(clips: &mut Vec<Clip>, start: u32, end: u32, links: &mut dyn FnMut(Option<u32>) -> (Option<u32>, Option<u32>)) {
11908 let mut out = Vec::with_capacity(clips.len() + 1);
11909 for c in clips.drain(..) {
11910 // Disjoint from the hole: untouched.
11911 if c.end() <= start || c.start >= end {
11912 out.push(c);
11913 continue;
11914 }
11915 // The head that survives in front of the hole -- as much source as fits
11916 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
11917 // which at real time is that room itself. Never *more*: a head that
11918 // outgrew its room would reach into the hole it is being cut out of,
11919 // which is exactly the overlap a slow clip punched at a frame its rate
11920 // cannot address used to leave (at 0.25x a single source frame is four
11921 // timeline frames, and three frames of room hold none of it). `None`
11922 // there means no remainder at all, and the piece simply goes.
11923 if let Some(keep) = c.fit_source(start.saturating_sub(c.start))
11924 && c.start < start
11925 {
11926 let (head, _) = links(c.link);
11927 let mut piece = Clip {
11928 fade_in: 0,
11929 fade_out: 0,
11930 transition_out: 0,
11931 transition_kind: Default::default(),
11932 link: head,
11933 ..c.clone()
11934 };
11935 // What survives in front plays the window's far end when it is reversed.
11936 match c.reversed {
11937 true => piece.in_frame = c.out_frame - keep.min(c.len()),
11938 false => piece.out_frame = c.in_frame + keep.min(c.len()),
11939 }
11940 out.push(piece);
11941 }
11942 // ...and the tail behind it, which keeps reading up to where it would
11943 // have: measured from its out-point for the head's reason, so what it
11944 // occupies still ends where the whole clip did -- and dropped whole on
11945 // the same `None`.
11946 // A ramp's tail restarts at `end`, so its keys are rebased to that frame
11947 // ([`ramp_keys_from`]) and its room is measured with them.
11948 let tail_keys = if c.speed_keys.is_empty() {
11949 Vec::new()
11950 } else {
11951 ramp_keys_from(&c.speed_keys, end.saturating_sub(c.start))
11952 };
11953 let tail_probe = Clip { speed_keys: tail_keys.clone(), ..c.clone() };
11954 if let Some(keep) = tail_probe.fit_source(c.end().saturating_sub(end))
11955 && c.end() > end
11956 {
11957 let (_, tail) = links(c.link);
11958 let mut piece = Clip {
11959 fade_in: 0,
11960 fade_out: 0,
11961 transition_out: 0,
11962 transition_kind: Default::default(),
11963 start: end,
11964 link: tail,
11965 speed_keys: tail_keys,
11966 ..c.clone()
11967 };
11968 match c.reversed {
11969 true => piece.out_frame = c.in_frame + keep.min(c.len()),
11970 false => piece.in_frame = c.out_frame - keep.min(c.len()),
11971 }
11972 out.push(piece);
11973 }
11974 }
11975 *clips = out;
11976}
11977
11978/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
11979/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
11980/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
11981/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
11982/// the caller.
11983fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
11984 for &i in on {
11985 let clips = &mut lanes[i].clips;
11986 clear(clips, at, at + len);
11987 for c in clips.iter_mut().filter(|c| c.start >= at) {
11988 c.start -= len;
11989 }
11990 debug_assert!(sorted_disjoint(clips));
11991 // The subtitle lanes close the hole with everything else: a caption
11992 // left standing where the picture it belongs to was cut out is the
11993 // desync a lane model exists to make impossible.
11994 let subs = &mut lanes[i].subs;
11995 sub_clear(subs, at, at + len);
11996 for s in subs.iter_mut().filter(|s| s.start >= at) {
11997 s.start -= len;
11998 }
11999 debug_assert!(subs_sorted_disjoint(subs));
12000 }
12001}
12002
12003/// Moves every clip and caption on `lane` that starts at or after `from` by `delta` frames: the
12004/// second half of a ripple trim ([`Project::ripple_trim`]), which closes or opens the hole an edge
12005/// left. No snapshot of its own.
12006fn shift_behind(lane: &mut LaneData, from: u32, delta: i64) {
12007 let step = |s: u32| (i64::from(s) + delta) as u32;
12008 for c in lane.clips.iter_mut().filter(|c| c.start >= from) {
12009 c.start = step(c.start);
12010 }
12011 debug_assert!(sorted_disjoint(&lane.clips));
12012 for s in lane.subs.iter_mut().filter(|s| s.start >= from) {
12013 s.start = step(s.start);
12014 }
12015 debug_assert!(subs_sorted_disjoint(&lane.subs));
12016}
12017
12018/// [`ripple`] for a cut that keeps its takes together: every take it splits keeps its id on the
12019/// piece before the cut, and the pieces after it share one fresh id per take, as the razor's
12020/// split does ([`Project::split_on`]). Only [`Project::cut_regions`] calls it, and that refuses
12021/// any scope that would take one half of a take with it, so every take it splits is whole in scope.
12022fn ripple_keeping_takes(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32, next_link: &mut u32) {
12023 let mut tails: Vec<(u32, u32)> = Vec::new();
12024 let mut links = |old: Option<u32>| -> (Option<u32>, Option<u32>) {
12025 let Some(id) = old else { return (None, None) };
12026 let tail = match tails.iter().find(|(o, _)| *o == id) {
12027 Some(&(_, t)) => t,
12028 None => {
12029 let t = *next_link;
12030 *next_link = next_link.saturating_add(1);
12031 tails.push((id, t));
12032 t
12033 }
12034 };
12035 (Some(id), Some(tail))
12036 };
12037 for &i in on {
12038 let clips = &mut lanes[i].clips;
12039 clear_with(clips, at, at + len, &mut links);
12040 for c in clips.iter_mut().filter(|c| c.start >= at) {
12041 c.start -= len;
12042 }
12043 debug_assert!(sorted_disjoint(clips));
12044 let subs = &mut lanes[i].subs;
12045 sub_clear_with(subs, at, at + len, &mut links);
12046 for s in subs.iter_mut().filter(|s| s.start >= at) {
12047 s.start -= len;
12048 }
12049 debug_assert!(subs_sorted_disjoint(subs));
12050 }
12051}
12052
12053/// Every lane, as the index list the two above take: what "the whole timeline"
12054/// is spelled as, and the scope [`Project::ripple_delete`] and
12055/// [`Project::split`] have always had.
12056fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
12057 (0..lanes.len()).collect()
12058}
12059
12060/// A caller's region list as a batch may use it: sorted by start, empty entries
12061/// dropped, and touching or overlapping entries merged into one.
12062///
12063/// Overlapping regions are the one thing a batch cannot take -- cutting the
12064/// second would cut frames the first already moved -- and a detector handing
12065/// back two that touch means one silence, not two cuts. Merged rather than
12066/// refused: this is arithmetic on a preview, not a user's mistake.
12067fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
12068 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
12069 sorted.sort_by_key(|&(at, _)| at);
12070 let mut out: Vec<(u32, u32)> = Vec::new();
12071 for (at, len) in sorted {
12072 let end = at.saturating_add(len);
12073 match out.last_mut() {
12074 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
12075 _ => out.push((at, len)),
12076 }
12077 }
12078 out
12079}
12080
12081/// Slides everything from `at` on later by `len`, splitting a placement that
12082/// straddles `at` so the two halves end up on either side of the hole. The
12083/// insert half of a rippling paste. The two halves lose the group id for the
12084/// reason [`clear`] gives.
12085fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
12086 if let Some(idx) = splittable(clips, at) {
12087 let mut tail = clips[idx].clone();
12088 // The cut in *source* frames, at the clip's own rate. `splittable` has
12089 // already refused a frame the rate cannot address, which is why
12090 // [`Project::paste`] refuses one too rather than opening room inside a
12091 // clip that cannot be cut there.
12092 let cut_at = split_source(&tail, at).expect("splittable said so");
12093 let (head_speed, tail_speed) = split_keys(&tail, at);
12094 tail.speed_keys = tail_speed;
12095 clips[idx].speed_keys = head_speed;
12096 match tail.reversed {
12097 true => {
12098 tail.out_frame = cut_at;
12099 clips[idx].in_frame = cut_at;
12100 }
12101 false => {
12102 tail.in_frame = cut_at;
12103 clips[idx].out_frame = cut_at;
12104 }
12105 }
12106 tail.start = at;
12107 tail.link = None;
12108 clips[idx].link = None;
12109 clips.insert(idx + 1, tail);
12110 }
12111 for c in clips.iter_mut().filter(|c| c.start >= at) {
12112 c.start += len;
12113 }
12114}
12115
12116/// Absolute, symlink-resolved when the file is reachable; the path as given
12117/// when it is not -- an unreadable path still deserves an index, it simply
12118/// dedups by spelling.
12119pub(crate) fn canonical(path: &Path) -> PathBuf {
12120 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
12121}
12122
12123#[cfg(test)]
12124mod tests {
12125 use super::*;
12126
12127 const FPS: f64 = 30.0;
12128
12129 /// A caption track that ends between two frames places with a window of
12130 /// whole frames: 4.750 s at 30 fps is 143 frames, and its cues keep their
12131 /// times (0.5 s is frame 15, 4.5 s is frame 135) instead of being stretched
12132 /// by 143 / 142.5 as they were when the window was the track's own length.
12133 #[test]
12134 fn a_whole_track_drop_is_not_stretched_by_its_last_frame() {
12135 let sub = SubClip::whole_track(2, 4_750_000, FPS);
12136 assert_eq!((sub.track, sub.start, sub.in_us), (2, 0, 0));
12137 assert_eq!(sub.frames, 143, "the fewest frames that hold the last cue");
12138 assert_eq!(sub.out_us, 4_766_667, "the window is the frames' own length");
12139 let frame_of = |us: i64| f64::from(sub.frames) * us as f64 / sub.window_us() as f64;
12140 for (us, want) in [(500_000i64, 15.0), (750_000, 22.5), (4_500_000, 135.0)] {
12141 assert!((frame_of(us) - want).abs() < 1e-3, "cue at {us} us lands on frame {}", frame_of(us));
12142 }
12143 // The old window (the track's length) put 4.5 s on 135.47 frames.
12144 assert!((4_500_000f64 * 143.0 / 4_750_000.0 - 135.0).abs() > 0.4);
12145 // A track that ends on a frame is that many frames, with no extra one.
12146 let exact = SubClip::whole_track(0, 1_000_000, FPS);
12147 assert_eq!((exact.frames, exact.out_us), (30, 1_000_000));
12148 }
12149 /// Never opened -- `Project` is pure data, so a path that does not exist is
12150 /// simply a path that dedups by spelling.
12151 const FILE: &str = "/nonexistent/a.mp4";
12152 const FILE2: &str = "/nonexistent/b.mp4";
12153
12154 /// A batch is one undo step however many edits it makes, far past the cap; undo takes
12155 /// back the whole batch, and an edit after `end_batch` takes its own step.
12156 #[test]
12157 fn a_batch_is_one_undo_step_past_the_cap() {
12158 let mut p = Project::single(FILE, 1);
12159 let v = p.add_lane(LaneKind::Video);
12160 let base = p.history_len();
12161 p.begin_batch();
12162 for k in 0..150u32 {
12163 assert!(p.place(v, k * 3, clip(k * 3, 0, 3, 0)));
12164 }
12165 p.end_batch();
12166 assert_eq!(p.history_len(), base + 1, "the batch is one step");
12167 assert_eq!(p.lane_clips_pub(v).len(), 150);
12168
12169 assert!(p.undo());
12170 assert!(p.lane_clips_pub(v).is_empty(), "undo takes the whole batch back");
12171 assert_eq!(p.history_len(), base);
12172
12173 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
12174 assert_eq!(p.history_len(), base + 1, "an edit outside a batch is its own step");
12175 }
12176
12177 /// Undo inside a batch starts a fresh step for what follows it, so the edits after it
12178 /// are not lost from the history.
12179 #[test]
12180 fn an_undo_inside_a_batch_opens_a_new_step() {
12181 let mut p = Project::single(FILE, 1);
12182 let v = p.add_lane(LaneKind::Video);
12183 let base = p.history_len();
12184 p.begin_batch();
12185 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
12186 assert!(p.undo());
12187 assert!(p.place(v, 0, clip(0, 0, 4, 0)));
12188 p.end_batch();
12189 assert_eq!(p.history_len(), base + 1);
12190 assert!(p.undo());
12191 assert!(p.lane_clips_pub(v).is_empty());
12192 }
12193
12194 /// A contiguous placement, group id ignored: what most assertions compare.
12195 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
12196 Clip {
12197 speed_keys: Vec::new(),
12198 reversed: false,
12199 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
12200 angle: Default::default(),
12201 fade_in: 0,
12202 fade_out: 0,
12203 transition_out: 0,
12204 transition_kind: Default::default(),
12205 visualizer: 0,
12206 viz_paint: 0,
12207 gain_db: 0.0,
12208 gain_keys: Vec::new(),
12209 pan: 0,
12210 pitch: 0,
12211 transform_keys: Vec::new(),
12212 opacity_keys: Vec::new(),
12213 color_keys: Vec::new(),
12214 effects: Vec::new(),
12215 start,
12216 in_frame,
12217 out_frame,
12218 source,
12219 link: None,
12220 eq: None,
12221 color: None,
12222 transform: None,
12223 fit: FitPolicy::default(),
12224 speed: Speed::NORMAL,
12225 }
12226 }
12227
12228 /// A reversed clip's timeline head is its source out side: a split gives the
12229 /// head the late footage and the tail the early, a trim of the head eats the
12230 /// source's end, and joining the halves gives the one clip back.
12231 #[test]
12232 fn a_reversed_clip_splits_trims_and_joins_from_its_out_side() {
12233 let mut p = Project::single(FILE, 100);
12234 let v = p.add_lane(LaneKind::Video);
12235 let mut c = clip(0, 0, 100, 0);
12236 c.reversed = true;
12237 assert!(p.place(v, 0, c.clone()));
12238 assert!(p.split(30));
12239 let halves = p.lane_clips_pub(v).to_vec();
12240 assert_eq!((halves[0].start, halves[0].in_frame, halves[0].out_frame), (0, 70, 100));
12241 assert_eq!((halves[1].start, halves[1].in_frame, halves[1].out_frame), (30, 0, 70));
12242 assert!(halves.iter().all(|h| h.reversed));
12243 assert!(p.regroup(30), "the halves are one reversed run again");
12244 let one = &p.lane_clips_pub(v)[0];
12245 assert_eq!((one.in_frame, one.out_frame, one.reversed), (0, 100, true));
12246 // Trimming the head by 10 frames drops the source's last 10.
12247 assert!(p.trim(v, 0, Edge::Start, 10, &[100]));
12248 let t = &p.lane_clips_pub(v)[0];
12249 assert_eq!((t.start, t.in_frame, t.out_frame), (10, 0, 90));
12250 }
12251
12252 /// Toggling is one undo step, mirrors a key anchored to the footage so the
12253 /// timeline behaviour does not change, and refuses a still.
12254 #[test]
12255 fn set_reverse_is_one_undoable_step_and_mirrors_footage_keys() {
12256 let mut p = Project::single(FILE, 100);
12257 let v = p.add_lane(LaneKind::Video);
12258 assert!(p.place(v, 0, clip(0, 0, 100, 0)));
12259 let steps = p.history_len();
12260 p.set_reverse(v, 0, true).expect("reverse");
12261 assert_eq!(p.history_len(), steps + 1);
12262 assert!(p.reversed_of(v, 0));
12263 p.set_reverse(v, 0, true).expect("already so is a no-op");
12264 assert_eq!(p.history_len(), steps + 1, "no second step");
12265 assert_eq!(source_pos(&p.lane_clips_pub(v)[0], 0).floor() as u32, 99, "the first timeline frame shows the last footage");
12266 assert!(p.undo());
12267 assert!(!p.reversed_of(v, 0));
12268 assert!(p.set_reverse(v, 7, true).is_err(), "no such clip");
12269 }
12270
12271 /// The shape `captions_place` makes: one placement covering a three-cue
12272 /// track, where cue 1 ("second") is exactly frames 93..176 at 30 fps.
12273 fn three_cue_captions() -> (Project, Lane) {
12274 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12275 start_us,
12276 end_us,
12277 text: text.into(),
12278 image: None,
12279 words: Vec::new(),
12280 karaoke: Vec::new(),
12281 };
12282 let mut words = subtitle_track();
12283 words.cues = vec![
12284 cue(0, 3_100_000, "first"),
12285 cue(3_100_000, 5_866_667, "second"),
12286 cue(5_866_667, 9_000_000, "third"),
12287 ];
12288 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12289 let s1 = p.add_lane(LaneKind::Subtitle);
12290 let sub = SubClip {
12291 start: 0,
12292 frames: 270,
12293 track: 0,
12294 in_us: 0,
12295 out_us: 9_000_000,
12296 link: None,
12297 };
12298 p.place_sub(s1, 0, sub).expect("placed");
12299 (p, s1)
12300 }
12301
12302 /// A cut over a span nothing lies in changes nothing: it costs no undo step,
12303 /// keeps the revision, and pushes nothing the batch counter would count.
12304 #[test]
12305 fn a_cut_over_an_empty_span_costs_no_step_and_keeps_the_revision() {
12306 let mut p = Project::single(FILE, 270);
12307 let empty = p.add_lane(LaneKind::Audio);
12308 let (depth, pushes, rev) = (p.history_len(), p.history_pushes(), p.revision());
12309 p.cut_regions(&[(10, 20)], &[empty]).expect("an empty lane is a legal scope");
12310 assert_eq!(p.history_len(), depth, "no undo step");
12311 assert_eq!(p.history_pushes(), pushes, "no snapshot counted");
12312 assert_eq!(p.revision(), rev, "same state, same revision");
12313 p.cut_regions(&[(400, 20)], &[Lane::V1, Lane::A1]).expect("a span past the last clip");
12314 assert_eq!(p.history_len(), depth, "still no undo step");
12315 assert_eq!(p.revision(), rev, "still the same revision");
12316 }
12317
12318 /// A cut that removes something still costs exactly one undo step and a new revision.
12319 #[test]
12320 fn a_real_cut_still_adds_one_step() {
12321 let mut p = Project::single(FILE, 270);
12322 let (depth, rev) = (p.history_len(), p.revision());
12323 p.cut_regions(&[(30, 30)], &[Lane::V1, Lane::A1]).expect("cut");
12324 assert_eq!(p.history_len(), depth + 1, "one undo step");
12325 assert_ne!(p.revision(), rev, "a new state");
12326 }
12327
12328 /// A no-op after the save leaves the saved revision in place, and undoing the
12329 /// real edit back to that save reads as the saved state again.
12330 #[test]
12331 fn undo_back_to_the_saved_point_clears_the_dot_after_a_no_op() {
12332 let mut p = Project::single(FILE, 270);
12333 let empty = p.add_lane(LaneKind::Audio);
12334 p.cut_regions(&[(30, 30)], &[Lane::V1, Lane::A1]).expect("cut");
12335 let saved = p.revision();
12336 p.cut_regions(&[(10, 20)], &[empty]).expect("empty span");
12337 assert_eq!(p.revision(), saved, "a no-op after the save leaves the dot clear");
12338 p.cut_regions(&[(100, 10)], &[Lane::V1, Lane::A1]).expect("a real cut");
12339 assert_ne!(p.revision(), saved, "the real cut moves off the saved state");
12340 assert!(p.undo());
12341 assert_eq!(p.revision(), saved, "undo back to the saved point clears the dot");
12342 }
12343
12344 /// The undo bookkeeping a no-op must leave exactly as it found it.
12345 fn undo_state(p: &Project) -> (usize, u64, usize, u64) {
12346 (p.history_len(), p.revision(), p.redo_len(), p.history_pushes())
12347 }
12348
12349 /// Mutators given arguments that change nothing (the value a setting already
12350 /// holds, an empty list, a move by 0) take no undo step, move no revision and
12351 /// keep the redo branch an edit would have cleared.
12352 #[test]
12353 fn no_op_mutators_leave_the_undo_state_alone() {
12354 let mut p = Project::single(FILE, 270);
12355 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12356 assert!(p.set_enabled(Lane::V1, 0, false));
12357 assert!(p.set_label(Lane::V1, 0, 2));
12358 assert!(p.set_clip_gain(Lane::A1, 0, -6.0));
12359 assert!(p.undo());
12360 let before = undo_state(&p);
12361 assert_eq!(before.2, 1, "the undone gain waits on the redo stack");
12362
12363 // Each call below sets a value the project already holds (or nothing).
12364 p.set_lane_gain_db(Lane::A1, -3.0);
12365 assert_eq!(undo_state(&p), before, "set_lane_gain_db");
12366 p.set_enabled(Lane::V1, 0, false);
12367 assert_eq!(undo_state(&p), before, "set_enabled");
12368 p.set_label(Lane::V1, 0, 2);
12369 assert_eq!(undo_state(&p), before, "set_label");
12370 p.set_clip_gain(Lane::A1, 0, 0.0);
12371 assert_eq!(undo_state(&p), before, "set_clip_gain");
12372 p.set_fade_in(Lane::V1, 0, 0);
12373 assert_eq!(undo_state(&p), before, "set_fade_in");
12374 p.set_fade_out(Lane::V1, 0, 0);
12375 assert_eq!(undo_state(&p), before, "set_fade_out");
12376 let _ = p.set_reverse(Lane::V1, 0, false);
12377 assert_eq!(undo_state(&p), before, "set_reverse");
12378 assert_eq!(p.slip(Lane::V1, 0, 0, SourceWalls::same(&[270])), Some(0));
12379 assert_eq!(undo_state(&p), before, "slip by 0");
12380 p.set_eq(Lane::A1, 0, None);
12381 assert_eq!(undo_state(&p), before, "set_eq");
12382 p.set_color_keys(Lane::V1, 0, Vec::new());
12383 assert_eq!(undo_state(&p), before, "set_color_keys");
12384 p.set_gain_keys(Lane::A1, 0, Vec::new());
12385 assert_eq!(undo_state(&p), before, "set_gain_keys");
12386 p.set_opacity_keys(Lane::V1, 0, Vec::new());
12387 assert_eq!(undo_state(&p), before, "set_opacity_keys");
12388 let _ = p.set_lane_name(Lane::A1, "");
12389 assert_eq!(undo_state(&p), before, "set_lane_name");
12390 p.clear_lane_duck(Lane::A1, 0);
12391 assert_eq!(undo_state(&p), before, "clear_lane_duck");
12392 p.remap_chapters(|f| f);
12393 assert_eq!(undo_state(&p), before, "remap_chapters");
12394 p.remap_markers(|f| f);
12395 assert_eq!(undo_state(&p), before, "remap_markers");
12396 p.add_subtitles_all(&[]);
12397 assert_eq!(undo_state(&p), before, "add_subtitles_all");
12398 p.relink_sources(&[]);
12399 assert_eq!(undo_state(&p), before, "relink_sources");
12400 let _ = p.cut_regions(&[(10, 0)], &[Lane::V1]);
12401 assert_eq!(undo_state(&p), before, "cut_regions of nothing");
12402
12403 // And the redo branch is still there to walk forward.
12404 let depth = p.history_len();
12405 assert!(p.redo(), "the gain comes back");
12406 assert_eq!(p.history_len(), depth + 1, "redo is one step forward");
12407 }
12408
12409 /// Real edits still cost exactly one undo step each, also right after a no-op.
12410 #[test]
12411 fn real_edits_still_add_exactly_one_step_after_no_ops() {
12412 let mut p = Project::single(FILE, 270);
12413 assert!(!p.set_enabled(Lane::V1, 0, true), "already on: nothing to do");
12414 let steps = p.history_len();
12415 let rev = p.revision();
12416 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12417 assert_eq!(p.history_len(), steps + 1, "one step for the gain");
12418 assert_ne!(p.revision(), rev, "a new state");
12419 assert!(p.set_enabled(Lane::V1, 0, false));
12420 assert_eq!(p.history_len(), steps + 2, "one step for the switch");
12421 assert!(p.set_label(Lane::V1, 0, 2));
12422 assert_eq!(p.history_len(), steps + 3, "one step for the label");
12423 assert!(p.set_clip_gain(Lane::A1, 0, -6.0));
12424 assert_eq!(p.history_len(), steps + 4, "one step for the clip gain");
12425 }
12426
12427 /// A no-op right after a real edit does not hide that edit from undo: one undo
12428 /// takes back the real edit, and nothing is left behind to undo next.
12429 #[test]
12430 fn undo_right_after_a_no_op_takes_back_the_real_edit() {
12431 let mut p = Project::single(FILE, 270);
12432 let start = p.revision();
12433 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12434 let edited = p.revision();
12435 p.set_lane_gain_db(Lane::A1, -3.0);
12436 assert_eq!(p.revision(), edited, "the no-op leaves the edited state's revision");
12437 assert!(p.undo());
12438 assert_eq!(p.revision(), start, "undo lands on the state before the edit");
12439 assert_eq!(p.history_len(), 0, "and no phantom step is left");
12440 assert!(!p.undo());
12441 }
12442
12443 /// A no-op between two edits leaves no step behind for the second to stack on.
12444 #[test]
12445 fn a_no_op_between_two_edits_is_not_a_step() {
12446 let mut p = Project::single(FILE, 270);
12447 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12448 p.set_lane_gain_db(Lane::A1, -3.0);
12449 assert!(p.set_enabled(Lane::V1, 0, false));
12450 assert_eq!(p.history_len(), 2, "the two edits, and no more");
12451 assert!(p.undo());
12452 assert!(p.undo());
12453 assert!(!p.undo(), "the no-op is gone for good");
12454 }
12455
12456 /// A no-op never destroys a redo branch: after an undo, a no-op keeps it, and
12457 /// redo still walks forward to the edit that was undone.
12458 #[test]
12459 fn a_no_op_after_undo_keeps_the_redo_branch() {
12460 let mut p = Project::single(FILE, 270);
12461 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12462 let edited = p.revision();
12463 assert!(p.undo());
12464 p.set_lane_gain_db(Lane::A1, 0.0);
12465 assert_eq!(p.redo_len(), 1, "the undone edit is still on the branch");
12466 assert!(p.redo());
12467 assert_eq!(p.revision(), edited, "redo walks back to the same state");
12468 }
12469
12470 /// Inside a batch a no-op adds no step, and a batch with a real edit and no-ops
12471 /// in it is one step.
12472 #[test]
12473 fn no_ops_inside_a_batch_add_no_step() {
12474 let mut p = Project::single(FILE, 270);
12475 let before = undo_state(&p);
12476 p.begin_batch();
12477 p.set_lane_gain_db(Lane::A1, 0.0);
12478 p.set_enabled(Lane::V1, 0, true);
12479 p.end_batch();
12480 assert_eq!(undo_state(&p), before, "an all-no-op batch is no step");
12481
12482 p.begin_batch();
12483 p.set_lane_gain_db(Lane::A1, 0.0);
12484 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12485 p.set_lane_gain_db(Lane::A1, -3.0);
12486 assert!(p.set_enabled(Lane::V1, 0, false));
12487 p.end_batch();
12488 assert_eq!(p.history_len(), before.0 + 1, "the batch is one step");
12489 assert!(p.undo());
12490 assert_eq!(p.revision(), before.1, "undo takes the whole batch back");
12491 assert!(!p.undo());
12492 }
12493
12494 /// At the cap a no-op neither evicts the oldest step nor loses it: the next real
12495 /// edit evicts it as it would have, and every step but that one can be undone.
12496 #[test]
12497 fn a_no_op_at_the_cap_keeps_every_step_it_should() {
12498 let mut p = Project::single(FILE, 400);
12499 for frame in 1..=HISTORY_CAP as u32 {
12500 assert!(p.split(frame));
12501 }
12502 let before = undo_state(&p);
12503 assert_eq!(before.0, HISTORY_CAP);
12504 p.set_enabled(Lane::V1, 0, true);
12505 assert_eq!(undo_state(&p), before, "a no-op at the cap");
12506 assert!(p.split(HISTORY_CAP as u32 + 1));
12507 assert_eq!(p.history_len(), HISTORY_CAP);
12508 let mut steps = 0;
12509 while p.undo() {
12510 steps += 1;
12511 }
12512 assert_eq!(steps, HISTORY_CAP, "every step but the evicted oldest one");
12513 }
12514
12515 /// The cues `s1` shows, as `(text, start_us, end_us)` in timeline order.
12516 fn shown_cues(p: &Project, s1: Lane) -> Vec<(String, i64, i64)> {
12517 p.sub_lane_cue_refs(s1, 30.0)
12518 .into_iter()
12519 .map(|(a, b, t, c)| (p.subtitles()[t].cues[c].text.clone(), a, b))
12520 .collect()
12521 }
12522
12523 /// A cut that covers a whole cue removes it: no zero-length copy, no
12524 /// duplicate, and the cues after it slide back. A cut that covers part of
12525 /// a cue trims it, and a cut spanning two cues trims both.
12526 #[test]
12527 fn a_cut_removes_or_trims_the_cues_it_covers() {
12528 let (mut p, s1) = three_cue_captions();
12529 p.cut_regions(&[(93, 83)], &[s1]).expect("cut the second sentence");
12530 let shown = shown_cues(&p, s1);
12531 assert_eq!(
12532 shown.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
12533 ["first", "third"],
12534 "the covered cue is gone, once: {shown:?}"
12535 );
12536 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12537 assert!((shown[1].1 - 3_100_000).abs() <= 3, "the third cue slides back to the cut: {shown:?}");
12538 assert!((shown[1].2 - shown[1].1 - 3_133_333).abs() <= 3, "third keeps its length: {shown:?}");
12539
12540 // Part of the second cue (frames 100..150) is cut out of the middle.
12541 let (mut p, s1) = three_cue_captions();
12542 p.cut_regions(&[(100, 50)], &[s1]).expect("cut inside the second cue");
12543 let shown = shown_cues(&p, s1);
12544 let total = |text: &str| -> i64 {
12545 shown.iter().filter(|c| c.0 == text).map(|c| c.2 - c.1).sum()
12546 };
12547 // "second" is one word: it keeps the longer side the cut leaves (5.0 s to 5.87 s, 0.87 s), once.
12548 assert!((total("second") - 866_667).abs() <= 3, "second keeps its longer side, once: {shown:?}");
12549 assert_eq!(shown.iter().filter(|c| c.0 == "second").count(), 1, "{shown:?}");
12550 assert!((total("first") - 3_100_000).abs() <= 3, "first is untouched: {shown:?}");
12551 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12552
12553 // A cut from inside the first cue to inside the second.
12554 let (mut p, s1) = three_cue_captions();
12555 p.cut_regions(&[(60, 60)], &[s1]).expect("cut across two cues");
12556 let shown = shown_cues(&p, s1);
12557 let total = |text: &str| -> i64 {
12558 shown.iter().filter(|c| c.0 == text).map(|c| c.2 - c.1).sum()
12559 };
12560 assert!((total("first") - 2_000_000).abs() <= 3, "first keeps its first two seconds: {shown:?}");
12561 assert!((total("second") - 1_866_667).abs() <= 3, "second keeps its last 1.87 s: {shown:?}");
12562 assert!((total("third") - 3_133_333).abs() <= 3, "third is untouched: {shown:?}");
12563 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12564 }
12565
12566 /// A sentence over one placement, nine seconds at 30 fps.
12567 fn sentence_captions() -> (Project, Lane) {
12568 let mut words = subtitle_track();
12569 words.cues = vec![crate::subtitle::Cue {
12570 start_us: 0,
12571 end_us: 9_000_000,
12572 text: "alpha beta gamma delta".into(),
12573 image: None,
12574 words: Vec::new(),
12575 karaoke: Vec::new(),
12576 }];
12577 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12578 let s1 = p.add_lane(LaneKind::Subtitle);
12579 let sub = SubClip { start: 0, frames: 270, track: 0, in_us: 0, out_us: 9_000_000, link: None };
12580 p.place_sub(s1, 0, sub).expect("placed");
12581 (p, s1)
12582 }
12583
12584 /// Cutting the middle of a sentence keeps the words either side of the cut
12585 /// and drops the ones inside it: "beta gamma" lies in frames 90..180 (3 s
12586 /// to 6 s), so only "alpha" and "delta" are left to show. Undo brings the
12587 /// one sentence back as it was.
12588 #[test]
12589 fn a_cut_through_a_sentence_drops_the_words_inside_it() {
12590 let (mut p, s1) = sentence_captions();
12591 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12592 let shown: Vec<String> = shown_cues(&p, s1).into_iter().map(|c| c.0).collect();
12593 assert_eq!(shown, ["alpha", "delta"], "the cut words are gone and the rest stays");
12594
12595 assert!(p.undo(), "the cut is one undo step");
12596 assert_eq!(p.subtitles()[0].cues.len(), 1, "undo restores the one cue");
12597 assert_eq!(p.subtitles()[0].cues[0].text, "alpha beta gamma delta");
12598 }
12599
12600 /// A ripple delete over the same span splits the same way, and so does a
12601 /// split at a point inside a sentence, which divides the words once.
12602 #[test]
12603 fn a_ripple_delete_and_a_split_divide_the_words_too() {
12604 let (mut p, s1) = sentence_captions();
12605 assert!(p.ripple_delete(90, 90));
12606 let shown: Vec<String> = shown_cues(&p, s1).into_iter().map(|c| c.0).collect();
12607 assert_eq!(shown, ["alpha", "delta"], "{shown:?}");
12608
12609 let (mut p, _) = sentence_captions();
12610 assert!(p.split(150), "a frame inside the sentence splits it");
12611 let texts: Vec<String> = p.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
12612 assert_eq!(texts, ["alpha beta", "gamma delta"], "a split at the half divides the words");
12613 }
12614
12615 /// `split_cues_at` divides the cue at the word boundary nearest the point,
12616 /// keeps every piece's time inside the cue, and is one undo step. Where no
12617 /// cue straddles the point it changes nothing and takes no step.
12618 #[test]
12619 fn split_cues_at_divides_the_words_and_is_one_undo_step() {
12620 let (mut p, _) = sentence_captions();
12621 assert!(!p.split_cues_at(0, 0), "a point at the cue's start splits nothing");
12622 assert!(p.split_cues_at(0, 2_250_000));
12623 let cues: Vec<(String, i64, i64)> =
12624 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12625 assert_eq!(
12626 cues,
12627 [("alpha".to_string(), 0, 2_250_000), ("beta gamma delta".to_string(), 2_250_000, 9_000_000)],
12628 "the pieces meet at the point and keep the words either side"
12629 );
12630 assert!(p.undo());
12631 assert_eq!(p.subtitles()[0].cues.len(), 1, "undo restores the sentence");
12632
12633 // "second" is one word: it stays whole on the longer side of 4 s (the tail, 4 s to 5.87 s).
12634 let (mut p, _) = three_cue_captions();
12635 assert!(p.split_cues_at(0, 4_000_000));
12636 let cues: Vec<(String, i64, i64)> =
12637 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12638 assert_eq!(cues.len(), 3, "a one-word cue is not duplicated: {cues:?}");
12639 assert_eq!(cues[1], ("second".to_string(), 4_000_000, 5_866_667));
12640 }
12641
12642 /// A cue with one word cut by an edge keeps its text on the longer piece only
12643 /// (ties: the piece before the edge), so the word is never shown twice.
12644 #[test]
12645 fn a_one_word_cue_cut_by_an_edge_keeps_its_text_on_one_piece() {
12646 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() };
12647 let before = cue(0, 4_000_000);
12648 assert_eq!(
12649 split_words(&before, 3_000_000),
12650 Some(vec![(0, 3_000_000, "Onewordcue".to_string())]),
12651 "the longer piece before the edge keeps the word"
12652 );
12653 assert_eq!(
12654 split_words(&cue(0, 4_000_000), 1_000_000),
12655 Some(vec![(1_000_000, 4_000_000, "Onewordcue".to_string())]),
12656 "the longer piece after the edge keeps the word"
12657 );
12658 assert_eq!(
12659 split_words(&cue(0, 4_000_000), 2_000_000),
12660 Some(vec![(0, 2_000_000, "Onewordcue".to_string())]),
12661 "a tie keeps the word on the piece before"
12662 );
12663 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);
12664 }
12665
12666 /// A cut through a one-word caption ("first", 0 to 3.1 s) at 2 s keeps the
12667 /// word on the longer piece before the cut, and no piece after it shows it.
12668 #[test]
12669 fn a_cut_through_a_one_word_caption_shows_it_once() {
12670 let (mut p, _) = three_cue_captions();
12671 assert!(p.split_cues_at(0, 2_000_000));
12672 let cues: Vec<(String, i64, i64)> =
12673 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12674 assert_eq!(cues[0], ("first".to_string(), 0, 2_000_000), "{cues:?}");
12675 assert_eq!(cues.iter().filter(|c| c.0 == "first").count(), 1, "one copy of the word: {cues:?}");
12676 }
12677
12678 /// Divided cues are written by a save as cue edits and cue adds, so a reopen
12679 /// of the saved project shows the same words, not the sentence it began as.
12680 #[test]
12681 fn divided_cues_survive_a_save_and_reopen() {
12682 let (mut p, s1) = sentence_captions();
12683 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12684 let edits = p.cue_edits().to_vec();
12685 let adds = p.cue_adds().to_vec();
12686 let mut words = subtitle_track();
12687 words.cues = vec![crate::subtitle::Cue {
12688 start_us: 0,
12689 end_us: 9_000_000,
12690 text: "alpha beta gamma delta".into(),
12691 image: None,
12692 words: Vec::new(),
12693 karaoke: Vec::new(),
12694 }];
12695 let reopened = Project::single(FILE, 270)
12696 .with_subtitles(vec![words])
12697 .with_cue_edits(&edits)
12698 .with_cue_adds(&adds);
12699 let texts = |p: &Project| -> Vec<(String, i64, i64)> {
12700 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect()
12701 };
12702 assert_eq!(texts(&reopened), texts(&p), "the reopened cues are the divided ones");
12703 }
12704
12705 /// The rippling delete is the same cut on every lane, so it must leave the
12706 /// same captions as the scoped one: no covered cue survives it either.
12707 #[test]
12708 fn a_ripple_delete_over_a_cue_leaves_no_copy_of_it() {
12709 let (mut p, s1) = three_cue_captions();
12710 assert!(p.ripple_delete(93, 83));
12711 let shown = shown_cues(&p, s1);
12712 assert_eq!(
12713 shown.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
12714 ["first", "third"],
12715 "{shown:?}"
12716 );
12717 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12718 }
12719
12720 /// How many of track `track`'s cues some placement window overlaps: a cue no
12721 /// window overlaps is an orphan, one nothing on the timeline can show.
12722 fn placed_cues_of(p: &Project, track: usize) -> usize {
12723 let windows: Vec<(i64, i64)> = p
12724 .lanes
12725 .iter()
12726 .flat_map(|l| l.subs.iter())
12727 .filter(|s| s.track == track)
12728 .map(|s| (s.in_us, s.out_us))
12729 .collect();
12730 p.subtitles()[track]
12731 .cues
12732 .iter()
12733 .filter(|c| windows.iter().any(|&(a, b)| c.start_us < b && a < c.end_us))
12734 .count()
12735 }
12736
12737 /// A cut through a sentence leaves no orphan. "beta gamma" lies in the cut,
12738 /// so it is removed with its words: the track keeps only "alpha" and
12739 /// "delta", and each is under the placement window that is left.
12740 #[test]
12741 fn a_cut_through_a_sentence_leaves_no_orphan_piece() {
12742 let (mut p, s1) = sentence_captions();
12743 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12744 let texts: Vec<String> = p.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
12745 assert_eq!(texts, ["alpha", "delta"], "the removed middle is not a cue: {texts:?}");
12746 assert_eq!(placed_cues_of(&p, 0), 2, "every cue is under a window");
12747 }
12748
12749 /// A cut that ends inside a one-word cue keeps the part the timeline still
12750 /// shows. "Over" runs 1.0 s to 1.7 s; cutting frames 1.0 s to 1.5 s leaves
12751 /// 1.5 s to 1.7 s on the timeline, so that is the cue that stays, with its
12752 /// word. The removed 1.0 s to 1.5 s piece is dropped.
12753 #[test]
12754 fn a_cut_ending_in_a_one_word_cue_keeps_the_visible_part() {
12755 let mut words = subtitle_track();
12756 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() }];
12757 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12758 let s1 = p.add_lane(LaneKind::Subtitle);
12759 // The file's 1 s to 4 s, played from timeline frame 30 (1.0 s) for 90 frames.
12760 let sub = SubClip { start: 30, frames: 90, track: 0, in_us: 1_000_000, out_us: 4_000_000, link: None };
12761 p.place_sub(s1, 30, sub).expect("placed");
12762 p.cut_regions(&[(30, 15)], &[s1]).expect("cut 1.0 s to 1.5 s");
12763 let cues: Vec<(String, i64, i64)> =
12764 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12765 assert_eq!(cues, [("Over".to_string(), 1_500_000, 1_700_000)], "{cues:?}");
12766 let shown = shown_cues(&p, s1);
12767 assert_eq!(shown.len(), 1, "{shown:?}");
12768 assert_eq!(shown[0].0, "Over");
12769 assert!((shown[0].1 - 1_000_000).abs() <= 3, "the word now starts where the cut ended: {shown:?}");
12770 assert!((shown[0].2 - 1_200_000).abs() <= 3, "and keeps its 0.2 s: {shown:?}");
12771 }
12772
12773 /// Three cuts in a row over a captioned timeline keep the track to the cues
12774 /// the placement shows: after each one every cue is under a window, so the
12775 /// cue count is the placed count.
12776 #[test]
12777 fn three_cuts_keep_the_cue_count_at_the_placed_count() {
12778 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() };
12779 let mut words = subtitle_track();
12780 words.cues = vec![
12781 cue(0, 1_900_000, "a b"),
12782 cue(1_900_000, 4_200_000, "c d e"),
12783 cue(4_200_000, 6_000_000, "f g"),
12784 cue(6_000_000, 8_100_000, "h i j"),
12785 cue(8_100_000, 10_000_000, "k l"),
12786 cue(10_000_000, 12_000_000, "m n"),
12787 ];
12788 let mut p = Project::single(FILE, 360).with_subtitles(vec![words]);
12789 let s1 = p.add_lane(LaneKind::Subtitle);
12790 let sub = SubClip { start: 0, frames: 360, track: 0, in_us: 0, out_us: 12_000_000, link: None };
12791 p.place_sub(s1, 0, sub).expect("placed");
12792 assert_eq!(placed_cues_of(&p, 0), 6);
12793 for (at, len) in [(45, 20), (100, 30), (200, 25)] {
12794 p.cut_regions(&[(at, len)], &[s1]).expect("cut");
12795 let total = p.subtitles()[0].cues.len();
12796 assert_eq!(placed_cues_of(&p, 0), total, "every cue is under a window after a cut: {total} cues");
12797 }
12798 }
12799
12800 /// A cue no placement ever covered is not the cut's to remove. A caption
12801 /// placed over the first part of its track leaves the rest of the cues in
12802 /// the track, so a cut through the placed part keeps them for later.
12803 #[test]
12804 fn a_cue_no_placement_covers_survives_a_cut() {
12805 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() };
12806 let mut words = subtitle_track();
12807 words.cues = vec![cue(0, 2_000_000, "x y"), cue(5_000_000, 7_000_000, "z w")];
12808 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12809 let s1 = p.add_lane(LaneKind::Subtitle);
12810 // Only the first two seconds are placed.
12811 let sub = SubClip { start: 0, frames: 60, track: 0, in_us: 0, out_us: 2_000_000, link: None };
12812 p.place_sub(s1, 0, sub).expect("placed");
12813 p.cut_regions(&[(30, 15)], &[s1]).expect("cut inside the placed part");
12814 let kept = p.subtitles()[0]
12815 .cues
12816 .iter()
12817 .filter(|c| c.text == "z w" && c.start_us == 5_000_000 && c.end_us == 7_000_000)
12818 .count();
12819 assert_eq!(kept, 1, "the unplaced cue stays in the track: {:?}", p.subtitles()[0].cues);
12820 }
12821
12822 /// A caption placement for pure timeline tests: the track window is the
12823 /// same duration as the placement, so assertions can stay in frames.
12824 fn caption(start: u32, frames: u32) -> SubClip {
12825 SubClip {
12826 start,
12827 frames,
12828 track: 0,
12829 in_us: 0,
12830 out_us: i64::from(frames) * 1_000_000,
12831 link: None,
12832 }
12833 }
12834
12835 /// A language retype is one undo step, refused (with no step) for a track
12836 /// that is not there or that already reads it, and a load puts a saved
12837 /// language back over the file's own.
12838 #[test]
12839 fn a_subtitle_language_is_one_undo_step_and_a_load_puts_it_back() {
12840 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track()]);
12841 assert!(p.set_subtitle_language(0, "fra"));
12842 assert_eq!(p.subtitles()[0].language, "fra");
12843 assert!(!p.set_subtitle_language(0, "fra"), "it already reads that: no step");
12844 assert!(!p.set_subtitle_language(5, "fra"), "no such track");
12845 assert!(p.undo());
12846 assert_eq!(p.subtitles()[0].language, "eng", "one step takes it back");
12847
12848 let back = Project::single(FILE, 300)
12849 .with_subtitles(vec![subtitle_track()])
12850 .with_sub_langs(&[(0, "deu".to_string()), (9, "xxx".to_string())]);
12851 assert_eq!(back.subtitles()[0].language, "deu");
12852 }
12853
12854 /// A subtitle palette row for tests that place captions on lanes.
12855 fn subtitle_track() -> SubtitleTrack {
12856 SubtitleTrack {
12857 path: FILE.into(),
12858 track: None,
12859 language: "eng".into(),
12860 name: String::new(),
12861 label: "eng".into(),
12862 cues: Vec::new(),
12863 bitmap: false,
12864 refused: None,
12865 }
12866 }
12867
12868 /// A retyped cue is the track's words, so every placement of that track
12869 /// shows it; a retype that changes nothing, or names no cue, costs no undo
12870 /// step; one undo takes the words and the save list back together; and a
12871 /// removed row's overrides go with it while the others keep their place.
12872 #[test]
12873 fn a_cue_is_trimmed_moved_and_merged_inside_its_neighbours_one_undo_step_each() {
12874 let (mut p, s1) = three_cue_captions();
12875 let times = |p: &Project| -> Vec<(i64, i64)> {
12876 p.subtitles()[0].cues.iter().map(|c| (c.start_us, c.end_us)).collect()
12877 };
12878 assert_eq!(p.cue_room(0, 1), Some((3_100_000, 5_866_667)));
12879 assert!(p.set_cue_times(0, 1, 3_100_000, 5_866_667).is_ok_and(|changed| !changed), "same times, no edit");
12880 assert!(p.set_cue_times(0, 1, 3_000_000, 5_000_000).is_err(), "into the cue before");
12881 assert!(p.set_cue_times(0, 1, 3_100_000, 6_000_000).is_err(), "into the cue after");
12882 assert!(p.set_cue_times(0, 1, 3_100_000, 3_150_000).is_err(), "too short");
12883 assert!(matches!(p.set_cue_times(0, 1, 3_500_000, 5_000_000), Ok(true)));
12884 assert_eq!(times(&p)[1], (3_500_000, 5_000_000));
12885 assert_eq!(p.subtitles()[0].cues[1].text, "second");
12886 assert_eq!(
12887 shown_cues(&p, s1)[1],
12888 ("second".to_string(), 3_500_000, 5_000_000),
12889 "the timeline shows the moved cue"
12890 );
12891 // The file cue leaves and its new times are an added cue: a save keeps both.
12892 assert_eq!(p.cue_adds().len(), 1);
12893 assert!(p.cue_edits().iter().any(|(_, _, t)| t.is_empty()));
12894 // A second trim of the same (now added) cue stays one added entry.
12895 assert!(matches!(p.set_cue_times(0, 1, 3_400_000, 5_000_000), Ok(true)));
12896 assert_eq!(p.cue_adds().len(), 1);
12897 assert_eq!(p.cue_adds()[0].start_us, 3_400_000);
12898
12899 assert_eq!(p.cue_track_us_at(s1, 0, 1, 4_000_000, 30.0), Some(4_000_000));
12900
12901 assert!(p.merge_cue_next(2, 0).is_err(), "no such track");
12902 assert!(p.merge_cue_next(0, 2).is_err(), "nothing after the last");
12903 assert!(p.merge_cue_next(0, 0).is_ok());
12904 assert_eq!(p.subtitles()[0].cues.len(), 2);
12905 assert_eq!(p.subtitles()[0].cues[0].text, "first second");
12906 assert_eq!(times(&p)[0], (0, 5_000_000));
12907
12908 assert!(p.undo(), "the merge goes");
12909 assert_eq!(p.subtitles()[0].cues.len(), 3);
12910 assert!(p.undo(), "the second trim goes");
12911 assert_eq!(times(&p)[1], (3_500_000, 5_000_000));
12912 assert!(p.undo(), "the first trim goes");
12913 assert_eq!(times(&p)[1], (3_100_000, 5_866_667));
12914 assert!(p.cue_adds().is_empty() && p.cue_edits().is_empty());
12915 }
12916
12917 #[test]
12918 fn a_retyped_cue_is_the_tracks_words_and_one_undo_step() {
12919 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12920 start_us,
12921 end_us,
12922 text: text.into(),
12923 image: None,
12924 words: Vec::new(),
12925 karaoke: Vec::new(),
12926 };
12927 let mut words = subtitle_track();
12928 words.cues = vec![cue(0, 1_000_000, "one"), cue(2_000_000, 3_000_000, "two")];
12929 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), words]);
12930 let s1 = p.add_lane(LaneKind::Subtitle);
12931 // A window of the track's first three seconds, played over three: one
12932 // timeline second is one of the file's, so the cues land where they are.
12933 for at in [0, 100] {
12934 let sub = SubClip {
12935 start: at,
12936 frames: 90,
12937 track: 1,
12938 in_us: 0,
12939 out_us: 3_000_000,
12940 link: None,
12941 };
12942 p.place_sub(s1, at, sub).expect("placed");
12943 }
12944 let texts = |p: &Project| -> Vec<String> {
12945 p.sub_lane_cues(s1, 30.0)
12946 .into_iter()
12947 .map(|c| c.text)
12948 .collect()
12949 };
12950 assert_eq!(texts(&p), ["one", "two", "one", "two"]);
12951
12952 assert!(!p.set_cue_text(1, 0, "one"), "the same words are no edit");
12953 assert!(!p.set_cue_text(1, 9, "x"), "a cue that is not there");
12954 assert!(!p.set_cue_text(7, 0, "x"), "a track that is not there");
12955 assert!(p.set_cue_text(1, 1, "TWO\nlines"));
12956 assert_eq!(
12957 texts(&p),
12958 ["one", "TWO\nlines", "one", "TWO\nlines"],
12959 "both placements show the retyped words"
12960 );
12961 assert_eq!(p.cue_edits(), [(1, 1, "TWO\nlines".to_string())]);
12962
12963 let refs = p.sub_lane_cue_refs(s1, 30.0);
12964 let drawn = p.sub_lane_cues(s1, 30.0);
12965 assert_eq!(refs.len(), drawn.len(), "one ref for each cue drawn");
12966 for (&(start, end, track, cue_idx), c) in refs.iter().zip(&drawn) {
12967 assert_eq!((start, end), (c.start_us, c.end_us));
12968 assert_eq!(p.subtitles()[track].cues[cue_idx].text, c.text);
12969 }
12970
12971 assert!(p.undo(), "one step back");
12972 assert_eq!(texts(&p), ["one", "two", "one", "two"]);
12973 assert!(
12974 p.cue_edits().is_empty(),
12975 "the save list goes back with the words"
12976 );
12977 assert!(p.redo());
12978 assert_eq!(texts(&p)[1], "TWO\nlines");
12979
12980 // The row above the edited one comes off: the edit moves down with its
12981 // track, and still names the cue it changed.
12982 p.remove_subtitles(0).expect("nothing is placed on it");
12983 assert_eq!(p.cue_edits(), [(0, 1, "TWO\nlines".to_string())]);
12984 assert_eq!(texts(&p)[1], "TWO\nlines");
12985 }
12986
12987 /// A deleted cue is gone from every placement of its track, and no placement
12988 /// moves. Deleting cue 1 and then cue 0 (by the indices a listing shows
12989 /// after each) leaves the file's third cue; a retype after the deletes lands
12990 /// on that cue's file index; and a reload of the same file, with the saved
12991 /// overrides put back, shows exactly what the session showed.
12992 #[test]
12993 fn a_deleted_cue_leaves_the_track_and_survives_a_reload() {
12994 let file_words = || {
12995 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12996 start_us,
12997 end_us,
12998 text: text.into(),
12999 image: None,
13000 words: Vec::new(),
13001 karaoke: Vec::new(),
13002 };
13003 let mut words = subtitle_track();
13004 words.cues = vec![
13005 cue(0, 1_000_000, "one"),
13006 cue(2_000_000, 3_000_000, "two"),
13007 cue(4_000_000, 5_000_000, "three"),
13008 ];
13009 words
13010 };
13011 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), file_words()]);
13012 let s1 = p.add_lane(LaneKind::Subtitle);
13013 let sub = SubClip { start: 0, frames: 150, track: 1, in_us: 0, out_us: 5_000_000, link: None };
13014 p.place_sub(s1, 0, sub).expect("placed");
13015 let texts = |p: &Project| -> Vec<String> {
13016 p.sub_lane_cues(s1, 30.0).into_iter().map(|c| c.text).collect()
13017 };
13018 assert_eq!(texts(&p), ["one", "two", "three"]);
13019
13020 assert!(p.delete_cue(1, 1), "cue 1 (\"two\") goes");
13021 assert!(!p.delete_cue(1, 9), "a cue that is not there");
13022 assert_eq!(texts(&p), ["one", "three"]);
13023 assert_eq!((p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].frames), (0, 150), "nothing moves");
13024 assert_eq!(p.cue_edits(), [(1, 1, String::new())]);
13025
13026 // Cue 1 is now "three"; its file index is 2, which the save names.
13027 assert!(p.set_cue_text(1, 1, "THREE"));
13028 assert_eq!(texts(&p), ["one", "THREE"]);
13029 assert_eq!(p.cue_edits(), [(1, 1, String::new()), (1, 2, "THREE".to_string())]);
13030
13031 // Empty text is a removal, not a blank cue: "one" goes.
13032 assert!(p.set_cue_text(1, 0, ""));
13033 assert_eq!(texts(&p), ["THREE"]);
13034 assert_eq!(
13035 p.cue_edits(),
13036 [(1, 1, String::new()), (1, 2, "THREE".to_string()), (1, 0, String::new())]
13037 );
13038
13039 // A reload: the file's three cues, the saved overrides put back.
13040 let saved = p.cue_edits().to_vec();
13041 let mut reopened =
13042 Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), file_words()]).with_cue_edits(&saved);
13043 let s1r = reopened.add_lane(LaneKind::Subtitle);
13044 reopened.place_sub(s1r, 0, SubClip { start: 0, frames: 150, track: 1, in_us: 0, out_us: 5_000_000, link: None }).expect("placed");
13045 let got: Vec<String> = reopened.sub_lane_cues(s1r, 30.0).into_iter().map(|c| c.text).collect();
13046 assert_eq!(got, ["THREE"], "the reload shows what the session did");
13047 assert_eq!(reopened.cue_edits(), saved.as_slice(), "and saves the same list");
13048
13049 // Undo takes back the last removal, then the retype, then the first removal.
13050 assert!(p.undo());
13051 assert_eq!(texts(&p), ["one", "THREE"]);
13052 assert!(p.undo());
13053 assert_eq!(texts(&p), ["one", "three"]);
13054 assert!(p.undo());
13055 assert_eq!(texts(&p), ["one", "two", "three"]);
13056 }
13057
13058 /// A cue a window edge shortened to under [`CUT_SLIVER_FRAMES`] is no cue;
13059 /// a cue that was short in the file, and whole, stays one.
13060 #[test]
13061 fn a_cut_sliver_under_four_frames_is_dropped_and_a_short_cue_is_not() {
13062 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
13063 start_us,
13064 end_us,
13065 text: text.into(),
13066 image: None,
13067 words: Vec::new(),
13068 karaoke: Vec::new(),
13069 };
13070 let mut words = subtitle_track();
13071 words.cues = vec![
13072 cue(0, 1_000_000, "whole"),
13073 // Shortened by the window's end at 1.1 s: 0.1 s, three frames.
13074 cue(1_000_000, 2_000_000, "edge"),
13075 // Two frames long in the file itself, inside the window.
13076 cue(1_000_000, 1_066_667, "born"),
13077 ];
13078 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), words]);
13079 let s1 = p.add_lane(LaneKind::Subtitle);
13080 let sub = SubClip { start: 0, frames: 33, track: 1, in_us: 0, out_us: 1_100_000, link: None };
13081 p.place_sub(s1, 0, sub).expect("placed");
13082 let shown: Vec<String> = p.sub_lane_cues(s1, 30.0).into_iter().map(|c| c.text).collect();
13083 assert_eq!(shown, ["whole", "born"], "the three-frame edge is no cue: {shown:?}");
13084 }
13085
13086 /// A recognisable equalizer setting: one peak band, `n` telling two of them
13087 /// apart -- which is what makes the table's dedup and its prune visible.
13088 fn band_at(n: u32) -> EqParams {
13089 EqParams {
13090 bands: vec![crate::eq::Band {
13091 freq_hz: 1000.0,
13092 gain_db: f64::from(n) as f32 * 1.5,
13093 q: 0.707,
13094 kind: crate::eq::BandKind::Peak,
13095 }],
13096 }
13097 }
13098
13099 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
13100 /// for the colour table.
13101 fn grade_at(n: u32) -> ColorParams {
13102 ColorParams {
13103 brightness: f64::from(n) as f32 * 0.05,
13104 ..Default::default()
13105 }
13106 }
13107
13108 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
13109 /// twin for the transform table.
13110 fn transform_at(n: u32) -> TransformParams {
13111 TransformParams {
13112 pos_x: f64::from(n) as f32 * 0.05,
13113 ..Default::default()
13114 }
13115 }
13116
13117 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
13118 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
13119 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
13120 }
13121
13122 /// Every lane with its group ids blanked, for comparing shape.
13123 fn shape(p: &Project) -> Vec<Vec<Clip>> {
13124 p.lanes()
13125 .into_iter()
13126 .map(|l| {
13127 p.lane(l)
13128 .iter()
13129 .map(|c| Clip {
13130 link: None,
13131 ..c.clone()
13132 })
13133 .collect()
13134 })
13135 .collect()
13136 }
13137
13138 /// The *source frame* every timeline frame reads, per lane -- the traversal
13139 /// a player performs. Deliberately not the clip index: a split changes which
13140 /// clip a frame belongs to, and nothing else.
13141 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
13142 (0..p.timeline_frames() + 2)
13143 .map(|f| {
13144 p.lanes()
13145 .into_iter()
13146 .map(|l| p.map(l, f).map(|(_, source)| source))
13147 .collect()
13148 })
13149 .collect()
13150 }
13151
13152 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
13153 /// fixture. Built through `split` so the constructor path is exercised too.
13154 fn three() -> Project {
13155 let mut p = Project::single(FILE, 9);
13156 assert!(p.split(3));
13157 assert!(p.split(5));
13158 assert_eq!(
13159 shape(&p),
13160 [
13161 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
13162 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
13163 ]
13164 );
13165 p
13166 }
13167
13168 #[test]
13169 fn single_is_the_whole_file_on_both_lanes() {
13170 let p = Project::single(FILE, 150);
13171 assert_eq!(p.clips().len(), 1);
13172 assert_eq!(p.lane(Lane::A1).len(), 1);
13173 assert_eq!(p.timeline_frames(), 150);
13174 assert_eq!(p.clip_spans(), vec![(0, 150)]);
13175 // grouped: video and audio carry the same link
13176 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
13177 assert!(p.clips()[0].link.is_some());
13178 // degenerate mapping: timeline == source
13179 assert_eq!(p.map_timeline(0), Some((0, 0)));
13180 assert_eq!(p.map_timeline(149), Some((0, 149)));
13181 assert_eq!(p.map_timeline(150), None);
13182 // never-empty invariant survives a bogus frame count
13183 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
13184 }
13185
13186 #[test]
13187 fn split_cuts_every_lane_and_regroups_it_back() {
13188 let mut p = Project::single(FILE, 9);
13189 let before = traversal(&p);
13190 let before_shape = shape(&p);
13191
13192 assert!(p.split(4));
13193 for l in p.lanes() {
13194 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
13195 }
13196 // The two sides are two groups, one per side, matching across the lanes.
13197 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
13198 assert_eq!(v[0].link, a[0].link);
13199 assert_eq!(v[1].link, a[1].link);
13200 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
13201 // A split changes no mapping, in either lane.
13202 assert_eq!(traversal(&p), before, "a split moves nothing");
13203
13204 assert!(p.regroup(4), "the inverse rejoins them");
13205 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
13206 assert_eq!(traversal(&p), before);
13207 assert_eq!(
13208 p.lane(Lane::V1)[0].link,
13209 p.lane(Lane::A1)[0].link,
13210 "and the rejoined clip is one group again"
13211 );
13212 }
13213
13214 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
13215 /// the very first frame of a fade-in, unity at its last, equal-power
13216 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
13217 /// at all.
13218 #[test]
13219 fn clip_gain_set_clamps_refuses_and_undoes() {
13220 let mut p = Project::single(FILE, 150);
13221 let a1 = Lane::new(LaneKind::Audio, 0);
13222 assert_eq!(p.clip_gain(a1, 0), Some(0.0));
13223 assert!(p.set_clip_gain(a1, 0, -6.0));
13224 assert_eq!(p.clip_gain(a1, 0), Some(-6.0));
13225 assert!(p.set_clip_gain(a1, 0, -100.0));
13226 assert_eq!(p.clip_gain(a1, 0), Some(-60.0), "clamped to the floor");
13227 assert!(!p.set_clip_gain(a1, 0, -60.0), "the same value is no step");
13228 assert!(!p.set_clip_gain(a1, 0, f32::NAN), "not finite");
13229 assert!(
13230 !p.set_clip_gain(Lane::V1, 0, -3.0),
13231 "a video clip takes no gain"
13232 );
13233 assert!(!p.set_clip_gain(a1, 5, -3.0), "no clip there");
13234 assert!(p.set_clip_gain(a1, 0, 30.0));
13235 assert_eq!(p.clip_gain(a1, 0), Some(24.0), "clamped to the ceiling");
13236 assert!(p.undo());
13237 assert_eq!(p.clip_gain(a1, 0), Some(-60.0));
13238 assert!(p.undo());
13239 assert_eq!(p.clip_gain(a1, 0), Some(-6.0));
13240 assert!(p.undo());
13241 assert_eq!(p.clip_gain(a1, 0), Some(0.0));
13242 }
13243
13244 #[test]
13245 fn gain_rides_the_envelope_and_a_split_carries_it_to_both_halves() {
13246 let mut p = Project::single(FILE, 150);
13247 let a1 = Lane::new(LaneKind::Audio, 0);
13248 assert!(p.set_clip_gain(a1, 0, -6.0));
13249 let fade = p.audio_fades_from(0, 30.0)[0][0]
13250 .clone()
13251 .expect("a gained clip has an envelope");
13252 assert!((fade.gain - 0.5012).abs() < 1e-3, "-6 dB is a linear 0.501");
13253 assert!(
13254 (fade.gain_at(75) - fade.gain).abs() < 1e-6,
13255 "no ramps: the gain alone"
13256 );
13257 assert!(p.split(60));
13258 assert_eq!(p.lane(a1).len(), 2);
13259 for c in p.lane(a1) {
13260 assert_eq!(c.gain_db, -6.0, "both halves keep the gain");
13261 }
13262 }
13263
13264 #[test]
13265 fn gain_envelope_is_linear_in_db_and_holds_at_both_ends() {
13266 let keys = [GainKey::new(10, -12.0), GainKey::new(20, 0.0)];
13267 assert_eq!(
13268 gain_keys_db_at(&keys, 15.0),
13269 -6.0,
13270 "the midpoint is the midpoint of the dB"
13271 );
13272 assert_eq!(gain_keys_db_at(&keys, 10.0), -12.0, "exact at a point");
13273 assert_eq!(gain_keys_db_at(&keys, 20.0), 0.0, "exact at the last point");
13274 assert_eq!(
13275 gain_keys_db_at(&keys, 0.0),
13276 -12.0,
13277 "held before the first point"
13278 );
13279 assert_eq!(
13280 gain_keys_db_at(&keys, 99.0),
13281 0.0,
13282 "held after the last point"
13283 );
13284 assert_eq!(gain_keys_db_at(&[], 5.0), 0.0, "no points is unity");
13285 let three = [
13286 GainKey::new(0, 0.0),
13287 GainKey::new(10, -20.0),
13288 GainKey::new(30, -20.0),
13289 ];
13290 assert_eq!(gain_keys_db_at(&three, 5.0), -10.0);
13291 assert_eq!(
13292 gain_keys_db_at(&three, 20.0),
13293 -20.0,
13294 "a flat run stays flat"
13295 );
13296 }
13297
13298 #[test]
13299 fn gain_keys_are_sorted_clamped_capped_and_refused_where_they_must_be() {
13300 let mut p = Project::single(FILE, 150);
13301 let a1 = Lane::new(LaneKind::Audio, 0);
13302 assert!(p.set_gain_keys(
13303 a1,
13304 0,
13305 vec![GainKey::new(30, -20.0), GainKey::new(0, 0.0)]
13306 ));
13307 assert_eq!(
13308 p.gain_keys_of(a1, 0),
13309 &[GainKey::new(0, 0.0), GainKey::new(30, -20.0)],
13310 "sorted by source frame"
13311 );
13312 assert!(
13313 !p.set_gain_keys(
13314 a1,
13315 0,
13316 vec![GainKey::new(5, 1.0), GainKey::new(5, 2.0)]
13317 ),
13318 "two points at one source frame are refused"
13319 );
13320 assert!(
13321 !p.set_gain_keys(Lane::V1, 0, vec![GainKey::new(0, 0.0)]),
13322 "a video clip takes no envelope"
13323 );
13324 assert!(!p.set_gain_keys(a1, 9, Vec::new()), "no such clip");
13325 assert!(p.set_gain_keys(a1, 0, vec![GainKey::new(0, 100.0)]));
13326 assert_eq!(p.gain_keys_of(a1, 0)[0].db, MAX_CLIP_GAIN_DB, "clamped");
13327 assert!(
13328 !p.set_gain_keys(a1, 0, vec![GainKey::new(0, 100.0)]),
13329 "an envelope already exactly so changes nothing, and costs no undo"
13330 );
13331 assert!(!p.set_gain_keys(
13332 a1,
13333 0,
13334 vec![GainKey::new(0, f32::NAN)]
13335 ));
13336 let over: Vec<GainKey> = (0..=MAX_GAIN_KEYS as u32)
13337 .map(|at| GainKey::new(at, 0.0))
13338 .collect();
13339 assert!(!p.set_gain_keys(a1, 0, over), "257 points is over the cap");
13340 let full: Vec<GainKey> = (0..MAX_GAIN_KEYS as u32)
13341 .map(|at| GainKey::new(at, 0.0))
13342 .collect();
13343 assert!(p.set_gain_keys(a1, 0, full), "256 is the cap itself");
13344 let extra = GainKey::new(9_999, 0.0);
13345 assert!(
13346 !p.add_gain_key(a1, 0, extra),
13347 "a 257th point through add is refused"
13348 );
13349 assert!(
13350 p.add_gain_key(a1, 0, GainKey::new(3, -3.0)),
13351 "a replacement still fits"
13352 );
13353 }
13354
13355 #[test]
13356 fn gain_keys_add_replace_remove_and_undo_each_take_one_step() {
13357 let mut p = Project::single(FILE, 150);
13358 let a1 = Lane::new(LaneKind::Audio, 0);
13359 assert!(p.add_gain_key(a1, 0, GainKey::new(0, 0.0)));
13360 assert!(p.add_gain_key(a1, 0, GainKey::new(30, -20.0)));
13361 assert!(
13362 p.add_gain_key(a1, 0, GainKey::new(30, -3.0)),
13363 "same frame replaces"
13364 );
13365 assert_eq!(
13366 p.gain_keys_of(a1, 0),
13367 &[GainKey::new(0, 0.0), GainKey::new(30, -3.0)]
13368 );
13369 assert!(
13370 !p.add_gain_key(a1, 0, GainKey::new(30, -3.0)),
13371 "the point already there changes nothing"
13372 );
13373 assert!(p.remove_gain_key(a1, 0, 0));
13374 assert!(!p.remove_gain_key(a1, 0, 0), "no point left at 0");
13375 assert_eq!(p.gain_keys_of(a1, 0), &[GainKey::new(30, -3.0)]);
13376 assert!(p.undo());
13377 assert_eq!(p.gain_keys_of(a1, 0).len(), 2, "the removal undone");
13378 assert!(p.undo());
13379 assert_eq!(
13380 p.gain_keys_of(a1, 0),
13381 &[GainKey::new(0, 0.0), GainKey::new(30, -20.0)],
13382 "the replacement undone"
13383 );
13384 assert!(p.undo());
13385 assert_eq!(p.gain_keys_of(a1, 0), &[GainKey::new(0, 0.0)]);
13386 assert!(p.undo());
13387 assert!(p.gain_keys_of(a1, 0).is_empty(), "back to flat");
13388 assert!(!p.undo(), "and no step is left to take");
13389 }
13390
13391 #[test]
13392 fn gain_db_at_maps_timeline_to_source_through_in_point_and_speed() {
13393 let mut p = Project::single(FILE, 150);
13394 let a1 = Lane::new(LaneKind::Audio, 0);
13395 assert!(p.set_gain_keys(
13396 a1,
13397 0,
13398 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)]
13399 ));
13400 assert!((p.gain_db_at(a1, 0, 50).unwrap() + 10.0).abs() < 1e-4);
13401 assert_eq!(
13402 p.gain_db_at(Lane::V1, 0, 50),
13403 None,
13404 "a video lane has no envelope"
13405 );
13406 assert_eq!(p.gain_db_at(a1, 3, 50), None, "no such clip");
13407 assert!(p.set_speed(a1, 0, Speed::from_permille(2000)).is_ok());
13408 assert!(
13409 (p.gain_db_at(a1, 0, 20).unwrap() + 8.0).abs() < 1e-3,
13410 "at 2x, timeline frame 20 plays source 40"
13411 );
13412 assert!(p.set_clip_gain(a1, 0, -6.0));
13413 assert!(
13414 (p.gain_db_at(a1, 0, 20).unwrap() + 14.0).abs() < 1e-3,
13415 "clip gain adds"
13416 );
13417 }
13418
13419 #[test]
13420 fn split_keeps_the_gain_curve_on_both_halves() {
13421 let mut p = Project::single(FILE, 150);
13422 let a1 = Lane::new(LaneKind::Audio, 0);
13423 assert!(p.set_gain_keys(
13424 a1,
13425 0,
13426 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)]
13427 ));
13428 let before: Vec<f32> = (0..150).map(|t| p.gain_db_at(a1, 0, t).unwrap()).collect();
13429 assert!(p.split(60));
13430 assert_eq!(p.lane(a1).len(), 2);
13431 for c in p.lane(a1) {
13432 assert_eq!(
13433 c.gain_keys,
13434 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)],
13435 "both halves keep every point"
13436 );
13437 }
13438 let after: Vec<f32> = (0..150)
13439 .map(|t| p.gain_db_at(a1, usize::from(t >= 60), t).unwrap())
13440 .collect();
13441 assert_eq!(before, after, "the curve is unchanged by the cut");
13442 }
13443
13444 #[test]
13445 fn gain_envelope_rides_the_fade_in_timeline_frames_and_scales_to_audio() {
13446 let mut p = Project::single(FILE, 150);
13447 let a1 = Lane::new(LaneKind::Audio, 0);
13448 assert!(p.set_gain_keys(
13449 a1,
13450 0,
13451 vec![GainKey::new(0, 0.0), GainKey::new(30, -20.0)]
13452 ));
13453 let fade = p.lane_fades_from(a1, 0, 30.0)[0]
13454 .clone()
13455 .expect("an enveloped clip has a fade");
13456 let minus_ten = 10f32.powf(-10.0 / 20.0);
13457 assert!(
13458 (fade.gain_at(15) - minus_ten).abs() < 1e-4,
13459 "frame 15 is -10 dB, which is {}",
13460 fade.gain_at(15)
13461 );
13462 assert!(
13463 (fade.gain_at(45) - 0.1).abs() < 1e-4,
13464 "held at -20 dB past the last point"
13465 );
13466 let scaled = fade.clone().scaled(1000.0);
13467 assert!(
13468 (scaled.gain_at(15_000) - fade.gain_at(15)).abs() < 1e-4,
13469 "audio frames"
13470 );
13471 }
13472
13473 #[test]
13474 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
13475 let f = Fade {
13476 elapsed: 0,
13477 fade_in: 10,
13478 fade_out: 10,
13479 total: 40,
13480 gain: 1.0,
13481 pan: (1.0, 1.0),
13482 curve: None,
13483 };
13484 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
13485 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
13486 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
13487 assert!(
13488 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
13489 "equal-power midpoint is sin(pi/4)"
13490 );
13491 assert_eq!(
13492 f.gain_at(20),
13493 1.0,
13494 "unchanged in the body, past either ramp"
13495 );
13496 // The fade-out is the same curve, mirrored, counting down from the
13497 // clip's end: unity at the frame the ramp starts, the same
13498 // equal-power midpoint, and -- since `total` itself is one past the
13499 // clip's last valid frame -- the very last frame is one step short of
13500 // the silence a fade-in's own frame `0` lands on exactly.
13501 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
13502 assert!(
13503 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
13504 "the fade-out's own equal-power midpoint"
13505 );
13506 assert!(
13507 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
13508 "one step short of silence at the clip's last playable frame"
13509 );
13510 }
13511
13512 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
13513 /// not adjacent, and otherwise sets the shared edge's fades and nothing
13514 /// else.
13515 #[test]
13516 fn crossfade_only_joins_adjacent_audio_clips() {
13517 let mut p = Project::single(FILE, 20);
13518 assert!(p.split(10));
13519 assert!(!p.crossfade(Lane::V1, 0, 5), "video is not an audio lane");
13520 assert!(!p.crossfade(Lane::A1, 1, 5), "there is no clip after idx 1");
13521 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
13522 let a = p.lane(Lane::A1);
13523 assert_eq!(a[0].fade_out, 5);
13524 assert_eq!(a[1].fade_in, 5);
13525 assert_eq!(a[0].fade_in, 0);
13526 assert_eq!(a[1].fade_out, 0);
13527
13528 // A gap between two clips is not adjacency, even on an audio lane.
13529 let mut p2 = Project::single(FILE, 1);
13530 let a2 = p2.add_lane(LaneKind::Audio);
13531 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
13532 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
13533 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
13534 }
13535
13536 /// The rule [`Project::write_split`] follows for the edge the razor makes:
13537 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
13538 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
13539 /// mirror image.
13540 #[test]
13541 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
13542 let mut p = Project::single(FILE, 20);
13543 assert!(p.set_fade_in(Lane::V1, 0, 15));
13544 assert!(p.set_fade_out(Lane::V1, 0, 15));
13545 assert!(p.split(5));
13546 let v = p.lane(Lane::V1);
13547 assert_eq!(
13548 v[0].fade_in, 5,
13549 "the left half's kept fade-in, clamped to 5 frames"
13550 );
13551 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
13552 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
13553 assert_eq!(
13554 v[1].fade_out, 15,
13555 "the right half's kept fade-out, unclamped: 15 frames fit in 15"
13556 );
13557 }
13558
13559 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
13560 /// no successor, and two clips that do not touch, and otherwise clamps
13561 /// the dissolve to the shorter of the two clips it spans.
13562 #[test]
13563 fn set_transition_out_only_dissolves_adjacent_video_clips() {
13564 let mut p = Project::single(FILE, 20);
13565 assert!(p.split(15), "a short 5-frame tail to clamp against");
13566 assert!(
13567 !p.set_transition_out(Lane::A1, 0, 5),
13568 "audio is not a video lane"
13569 );
13570 assert!(
13571 !p.set_transition_out(Lane::V1, 1, 5),
13572 "there is no clip after idx 1"
13573 );
13574 assert!(
13575 p.set_transition_out(Lane::V1, 0, 100),
13576 "the two halves are adjacent"
13577 );
13578 assert_eq!(
13579 p.transition_out_of(Lane::V1, 0),
13580 5,
13581 "clamped to the shorter neighbour's 5 frames"
13582 );
13583
13584 // A gap between two clips is not adjacency, even on the video lane.
13585 let mut p2 = Project::single(FILE, 1);
13586 let v2 = p2.add_lane(LaneKind::Video);
13587 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
13588 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
13589 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
13590 }
13591
13592 /// The two transition doors' bool is the WEAK shape, stated here as
13593 /// behaviour rather than left as something a front-end has to know: both
13594 /// answer "these two clips are adjacent", and both snapshot and clamp --
13595 /// so a write that lands the value the join already carries is still
13596 /// reported as a write. The step it pushed changed nothing, so it is settled
13597 /// away and costs no undo step. The front-end's before/after comparison
13598 /// (`Player::transition_edges`) still decides what it shows.
13599 #[test]
13600 fn a_transition_door_says_yes_to_a_write_that_moved_nothing() {
13601 let mut p = Project::single(FILE, 20);
13602 assert!(p.split(10), "two halves to join");
13603 assert!(p.set_transition_out(Lane::V1, 0, 5), "the dissolve lands");
13604 assert!(p.crossfade(Lane::A1, 0, 5), "the crossfade lands");
13605 let history = p.history_len();
13606
13607 // The very same numbers again: nothing moved, and both doors report a
13608 // write anyway.
13609 assert!(
13610 p.set_transition_out(Lane::V1, 0, 5),
13611 "set_transition_out answers 'the clips are adjacent', not 'the \
13612 dissolve moved', so a no-op reads as a write"
13613 );
13614 assert!(
13615 p.crossfade(Lane::A1, 0, 5),
13616 "crossfade answers the same way for the same reason"
13617 );
13618 assert_eq!(
13619 p.history_len(),
13620 history,
13621 "and neither spent an undo step: a write that changed nothing is settled away"
13622 );
13623
13624 // What did not move -- the comparison the front-end makes: both edges
13625 // a crossfade writes, and the dissolve itself.
13626 let a = p.lane(Lane::A1);
13627 assert_eq!((a[0].fade_out, a[1].fade_in), (5, 5), "unchanged");
13628 assert_eq!(p.transition_out_of(Lane::V1, 0), 5, "unchanged");
13629
13630 // And a refusal still answers no, so the arm is not simply always on:
13631 // the last clip has no successor to dissolve into.
13632 assert!(
13633 !p.set_transition_out(Lane::V1, 1, 5),
13634 "no neighbour end to end"
13635 );
13636 }
13637
13638 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
13639 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
13640 /// only the half that kept the clip's original *end* keeps the dissolve,
13641 /// re-clamped to its own now-shorter length; the head the cut just made
13642 /// has no successor to dissolve into and starts flat.
13643 #[test]
13644 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
13645 let mut p = Project::single(FILE, 20);
13646 assert!(
13647 !p.set_transition_out(Lane::V1, 0, 0),
13648 "one clip on the lane, no successor to dissolve into yet"
13649 );
13650 // Give the clip a dissolve by hand, then cut it in two.
13651 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
13652 assert!(p.split(5));
13653 let v = p.lane(Lane::V1);
13654 assert_eq!(
13655 v[0].transition_out, 0,
13656 "the cut edge it made has no successor"
13657 );
13658 assert_eq!(
13659 v[1].transition_out, 15,
13660 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
13661 );
13662 }
13663
13664 /// The music video's own path: the take comes apart into halves that carry
13665 /// ids of their own, one undo puts it back, and two clips over the same
13666 /// frames become one take again by hand.
13667 #[test]
13668 fn a_take_comes_apart_and_goes_back_together() {
13669 let mut p = Project::single(FILE, 9);
13670 let one = p.clips()[0].link.expect("a fresh project is one take");
13671 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
13672
13673 // A third lane in the same group -- and the merge case with it: a
13674 // placement is in no group, and grouping it in leaves *one* group.
13675 let v2 = p.add_lane(LaneKind::Video);
13676 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
13677 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
13678 p.group(Lane::V1, 0, v2, 0)
13679 .expect("the same frames, one lane over");
13680 let id = p.clips()[0].link.expect("still a group");
13681 assert!(
13682 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
13683 "one id over the three, not two groups sharing a span"
13684 );
13685 links_are_consistent(&p.lanes).expect("one id, one span");
13686
13687 // Detached by the sound: every half of the group, not only the two.
13688 assert!(p.ungroup(Lane::A1, 0));
13689 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
13690 assert!(
13691 ids.iter().all(Option::is_some),
13692 "a half keeps an id of its own"
13693 );
13694 assert!(
13695 ids.iter()
13696 .enumerate()
13697 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
13698 "and no two halves are the same group any more: {ids:?}"
13699 );
13700 links_are_consistent(&p.lanes).expect("a lone id is legal");
13701
13702 // One snapshot for the whole detach.
13703 assert!(p.undo());
13704 assert!(
13705 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
13706 "one undo puts the whole group back"
13707 );
13708
13709 // And back together by hand: the two the pointer named, and only them.
13710 assert!(p.ungroup(Lane::V1, 0));
13711 p.group(Lane::V1, 0, Lane::A1, 0)
13712 .expect("both cover [0, 9)");
13713 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
13714 assert_ne!(
13715 p.lane(v2)[0].link,
13716 p.lane(Lane::V1)[0].link,
13717 "the third half stayed detached"
13718 );
13719 links_are_consistent(&p.lanes).expect("one id, one span");
13720 }
13721
13722 /// What a group may not be, and what a detach has nothing to take apart --
13723 /// none of which may cost an undo step.
13724 #[test]
13725 fn a_group_is_one_span_and_one_clip_per_lane() {
13726 let mut p = three();
13727 let before = shape(&p);
13728 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
13729
13730 assert!(
13731 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
13732 "two clips of one lane are never one take"
13733 );
13734 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
13735 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
13736 assert!(
13737 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
13738 "{spans}"
13739 );
13740 assert!(
13741 spans.contains("trim them to matching bounds first"),
13742 "{spans}"
13743 );
13744 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
13745
13746 // A half nothing else is grouped with is already detached, a placement
13747 // is in no group at all, and an index that is not there has nothing to
13748 // detach either.
13749 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
13750 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
13751 assert!(p.lift(Lane::A1, 0));
13752 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
13753 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
13754
13755 // Two undos, one per edit: not one of the refusals pushed a snapshot.
13756 assert!(p.undo());
13757 assert!(p.undo());
13758 assert_eq!(shape(&p), before);
13759 }
13760
13761 /// Where a re-rate puts a playhead: the scene under the cursor stays the
13762 /// scene under the cursor, measured the way a viewer would -- the source
13763 /// frame playing at the playhead is the same frame after the write, at
13764 /// every playhead position the re-rate can catch one.
13765 #[test]
13766 fn a_re_rate_keeps_the_frame_under_the_playhead() {
13767 let caption = |start: u32, frames: u32| SubClip {
13768 start,
13769 frames,
13770 track: 0,
13771 in_us: 0,
13772 out_us: i64::from(frames) * 1_000_000,
13773 link: None,
13774 };
13775 let track = || SubtitleTrack {
13776 path: FILE.into(),
13777 track: None,
13778 language: "eng".into(),
13779 name: String::new(),
13780 label: "eng".into(),
13781 cues: Vec::new(),
13782 bitmap: false,
13783 refused: None,
13784 };
13785 // A group of a 300-frame clip and a caption offset 30 frames into it.
13786 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
13787 let s1 = p.add_lane(LaneKind::Subtitle);
13788 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
13789 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13790
13791 // The frame playing at `at`: which clip, and which source frame of it.
13792 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
13793 p.span_at(Lane::V1, at).and_then(|s| s.from)
13794 };
13795
13796 // Inside the held clip: the source frame under the playhead is the
13797 // same one after the re-rate, at 2x and at half speed both.
13798 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
13799 let at = 120;
13800 let before = playing(&p, at).expect("a clip under the playhead");
13801 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
13802 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
13803 .expect("room for it");
13804 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
13805 assert_eq!(before, after, "{what}: the same source frame plays");
13806 // ...and the write itself is untouched by the question.
13807 assert!(p.undo(), "{what}: one step back");
13808 }
13809
13810 // Past the group -- the clip ends at 300 and the caption at 270, so
13811 // from 300 on nothing is re-timed under the playhead: unmoved.
13812 for at in [300u32, 301, 1_000] {
13813 assert_eq!(
13814 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
13815 Some(at),
13816 "at {at}: outside every member, unmoved"
13817 );
13818 }
13819 // The boundary is exact: the held clip's own last frame (299) maps
13820 // to its new one (149 -- the last frame inside [0, 150), where the
13821 // shrunken clip's last source frame plays), and its first stays put.
13822 assert_eq!(
13823 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
13824 Some(149)
13825 );
13826 assert_eq!(
13827 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
13828 Some(0)
13829 );
13830 // A spot the caption shares with the clip maps by the clip (it is
13831 // what is *playing* there): the held clip's own proportion, which on
13832 // this fixture is also its head.
13833 assert_eq!(
13834 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
13835 Some(45),
13836 "the clip under the caption owns the spot"
13837 );
13838 }
13839
13840 /// A playhead inside another clip member of the group: that member keeps
13841 /// its own head, so the mapping is by its proportion and not the held
13842 /// clip's -- and the frame under the cursor is still the frame that was.
13843 #[test]
13844 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
13845 let mut p = Project::single(FILE, 300);
13846 // A second clip, grouped with the first but starting 300 later: the
13847 // head the group shares and its own differ by exactly that.
13848 let v2 = p.add_lane(LaneKind::Video);
13849 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
13850 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
13851 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
13852
13853 let at = 450; // inside the second member, 150 past its head
13854 let before = p.span_at(v2, at).and_then(|s| s.from);
13855 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
13856 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
13857 .expect("room for it");
13858 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
13859 assert_eq!(before, after, "the second member's own frame plays");
13860 // ...and the mapping itself: 150 past its head halves, the head stays.
13861 assert_eq!(mapped, Some(375));
13862 }
13863
13864 /// The link counter a load seeds sits past every id the file names,
13865 /// captions included: a hand-grouped caption may carry the highest id there
13866 /// is, and a counter that read the clips alone would hand it to the next
13867 /// group that asked -- silently grouping the caption with clips it never
13868 /// met.
13869 #[test]
13870 fn the_link_counter_sits_past_a_caption_only_id() {
13871 let track = || SubtitleTrack {
13872 path: FILE.into(),
13873 track: None,
13874 language: "eng".into(),
13875 name: String::new(),
13876 label: "eng".into(),
13877 cues: Vec::new(),
13878 bitmap: false,
13879 refused: None,
13880 };
13881 let mut p = Project::single(FILE, 9);
13882 p.add_lane(LaneKind::Subtitle);
13883 let caption = SubClip {
13884 start: 0,
13885 frames: 6,
13886 track: 0,
13887 in_us: 0,
13888 out_us: 6_000_000,
13889 // The highest id in the file, and only a caption carries it.
13890 link: Some(1),
13891 };
13892 let mut p = p
13893 .with_subtitles(vec![track()])
13894 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
13895 .expect("a caption may carry the file's highest id");
13896
13897 // A new group on lanes the caption is not on mints the next id -- which
13898 // must not be the caption's.
13899 let v2 = p.add_lane(LaneKind::Video);
13900 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
13901 p.group_all(&[(Lane::V1, 0), (v2, 0)])
13902 .expect("the clips group");
13903 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
13904 assert_ne!(minted, 1, "the caption's id is not re-issued to clips");
13905 assert_eq!(
13906 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
13907 Some(1),
13908 "the caption keeps its own group"
13909 );
13910 assert!(links_are_consistent(&p.lanes).is_ok());
13911 }
13912
13913 /// A rate re-times the caption members of the group by the ratio it gives
13914 /// the held clip: the span on the timeline compresses about the held clip's
13915 /// head, the words' own window untouched -- and one undo puts it back.
13916 #[test]
13917 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
13918 let caption = |start: u32, frames: u32| SubClip {
13919 start,
13920 frames,
13921 track: 0,
13922 in_us: 0,
13923 out_us: i64::from(frames) * 1_000_000,
13924 link: None,
13925 };
13926 let track = || SubtitleTrack {
13927 path: FILE.into(),
13928 track: None,
13929 language: "eng".into(),
13930 name: String::new(),
13931 label: "eng".into(),
13932 cues: Vec::new(),
13933 bitmap: false,
13934 refused: None,
13935 };
13936 let grouped = || {
13937 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
13938 let s1 = p.add_lane(LaneKind::Subtitle);
13939 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
13940 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13941 (p, s1)
13942 };
13943
13944 // An aligned take, doubled: the caption plays in half the frames.
13945 let (mut p, s1) = grouped();
13946 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
13947 .expect("room for it");
13948 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
13949 let s = p.sub_lane(s1)[0];
13950 assert_eq!(
13951 (s.start, s.frames),
13952 (0, 45),
13953 "same words, half the timeline"
13954 );
13955 assert_eq!(
13956 (s.in_us, s.out_us),
13957 (0, 90_000_000),
13958 "the window is untouched"
13959 );
13960 assert!(links_are_consistent(&p.lanes).is_ok());
13961 assert!(p.undo());
13962 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
13963
13964 // An offset group, slowed to half: the caption's *offset from the held
13965 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
13966 // 0.5x, and still ends where the clip does.
13967 let (mut p, s1) = grouped();
13968 p.lift_sub(s1, 0);
13969 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
13970 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13971 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
13972 .expect("room for it");
13973 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
13974 let s = p.sub_lane(s1)[0];
13975 assert_eq!(
13976 (s.start, s.frames),
13977 (60, 120),
13978 "the offset doubles with the clip"
13979 );
13980 assert_eq!(
13981 s.end(),
13982 p.lane(Lane::V1)[0].end(),
13983 "still ends with the clip"
13984 );
13985
13986 // A stretch that runs the caption into its neighbour is refused, by
13987 // lane and frame, and costs no undo step.
13988 let (mut p, s1) = grouped();
13989 p.lift_sub(s1, 0);
13990 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
13991 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
13992 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13993 let history = p.history.len();
13994 let err = p
13995 .set_speed(Lane::V1, 0, Speed::from_permille(500))
13996 .unwrap_err()
13997 .to_string();
13998 assert!(
13999 err.contains(
14000 "the S1 caption at frame 0 would run to frame 180 and the next starts at 95"
14001 ),
14002 "{err}"
14003 );
14004 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
14005 }
14006
14007 /// The silence scan's speed-up re-times the captions on a scoped lane with
14008 /// everything else: the piece inside the region plays in the region's new
14009 /// frames, and what sits behind the region slides up with the clips.
14010 #[test]
14011 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
14012 let caption = |start: u32, frames: u32| SubClip {
14013 start,
14014 frames,
14015 track: 0,
14016 in_us: 0,
14017 out_us: i64::from(frames) * 1_000_000,
14018 link: None,
14019 };
14020 let track = || SubtitleTrack {
14021 path: FILE.into(),
14022 track: None,
14023 language: "eng".into(),
14024 name: String::new(),
14025 label: "eng".into(),
14026 cues: Vec::new(),
14027 bitmap: false,
14028 refused: None,
14029 };
14030 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14031 let s1 = p.add_lane(LaneKind::Subtitle);
14032 // Words over the region [30, 60) and words behind it.
14033 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
14034 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
14035
14036 // The region [30, 60) plays at 4x: 30 frames become 8, everything
14037 // behind slides up 22.
14038 // The scope is what the card's Take row says, caption lane included.
14039 p.speed_regions(
14040 &[(30, 30)],
14041 Speed::from_permille(4000),
14042 &[Lane::V1, Lane::A1, s1],
14043 )
14044 .expect("the region speeds up");
14045 let subs = p.sub_lane(s1);
14046 assert_eq!(
14047 (subs[0].start, subs[0].frames),
14048 (30, 8),
14049 "the piece inside plays in the region's new frames"
14050 );
14051 assert_eq!(
14052 (subs[1].start, subs[1].frames),
14053 (38, 30),
14054 "the piece behind slides up by what the region gave back"
14055 );
14056 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
14057 }
14058
14059 /// [`Project::speeded_playhead`]'s caption arm fires only when the
14060 /// playhead is inside a caption member and outside every clip member --
14061 /// a shape every other fixture avoids by keeping its caption inside the
14062 /// held clip. Here the caption overhangs the clip's tail, and the
14063 /// playhead standing in that overhang is answered by the caption's own
14064 /// piece: it scales about the held clip's head by the held clip's own
14065 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
14066 #[test]
14067 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
14068 let caption = |start: u32, frames: u32| SubClip {
14069 start,
14070 frames,
14071 track: 0,
14072 in_us: 0,
14073 out_us: i64::from(frames) * 1_000_000,
14074 link: None,
14075 };
14076 let track = || SubtitleTrack {
14077 path: FILE.into(),
14078 track: None,
14079 language: "eng".into(),
14080 name: String::new(),
14081 label: "eng".into(),
14082 cues: Vec::new(),
14083 bitmap: false,
14084 refused: None,
14085 };
14086 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14087 let s1 = p.add_lane(LaneKind::Subtitle);
14088 // The caption spans [80, 100) -- ten frames past the clip's own end
14089 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
14090 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
14091 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14092 // At 2x the clip halves to 45 frames; the overhang frame 95, which
14093 // no clip member's old span reaches, is the caption's own question:
14094 // half of 95 is 47.5, rounded to 48.
14095 assert_eq!(
14096 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
14097 Some(48),
14098 "the overhang frame answers through the caption's own piece"
14099 );
14100 }
14101
14102 /// `write_speed` and `speeded_playhead` are two questions of the SAME
14103 /// map ([`map`]'s architecture law): a caption's landed span comes from
14104 /// the map's own ends, and the playhead standing at the caption's own
14105 /// last frame before the write has to land exactly where the write put
14106 /// it -- across clip lengths and rates that round differently, and an
14107 /// odd-length caption straddling the clip's own tail edge, the corner
14108 /// where `write_speed` used to answer a frame short.
14109 #[test]
14110 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
14111 let caption = |start: u32, frames: u32| SubClip {
14112 start,
14113 frames,
14114 track: 0,
14115 in_us: 0,
14116 out_us: i64::from(frames) * 1_000_000,
14117 link: None,
14118 };
14119 let track = || SubtitleTrack {
14120 path: FILE.into(),
14121 track: None,
14122 language: "eng".into(),
14123 name: String::new(),
14124 label: "eng".into(),
14125 cues: Vec::new(),
14126 bitmap: false,
14127 refused: None,
14128 };
14129 for &len in &[90u32, 91, 177, 300, 301] {
14130 for &permille in &[500u16, 2000, 2500, 3000] {
14131 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
14132 let s1 = p.add_lane(LaneKind::Subtitle);
14133 // An odd-length caption straddling the clip's tail edge: its
14134 // own last frame lands past the held clip.
14135 let c_start = len.saturating_sub(3);
14136 p.place_sub(s1, c_start, caption(c_start, 7))
14137 .expect("placed");
14138 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14139 let speed = Speed::from_permille(permille);
14140 let last = c_start + 7 - 1;
14141 let mapped = p
14142 .speeded_playhead(Lane::V1, 0, speed, last)
14143 .expect("the caption is there");
14144 if p.set_speed(Lane::V1, 0, speed).is_err() {
14145 continue; // a refusal changes nothing: not this law's cell
14146 }
14147 let landed = p.sub_lane(s1)[0];
14148 if permille >= 1000 {
14149 // A speed-up compresses the timeline: many old frames
14150 // share one new frame, so the caption's own last old
14151 // frame lands flush with the write's own boundary --
14152 // the exact law [`write_speed`]'s worked drift-fix case
14153 // is stated against.
14154 assert_eq!(
14155 mapped,
14156 landed.end() - 1,
14157 "len {len} permille {permille}: the playhead at the caption's own \
14158 last frame lands where the write actually put it"
14159 );
14160 } else {
14161 // A slow-down expands it: one old frame becomes several
14162 // new ones, and `apply` answers where that frame's own
14163 // block *starts*, not where the caption's last new
14164 // frame (the end of that same block) sits -- a
14165 // one-frame gap inherent to the piece's own semantics,
14166 // not a drift between the two callers. Both still have
14167 // to agree the answer sits inside the caption the write
14168 // actually landed.
14169 assert!(
14170 (landed.start..landed.end()).contains(&mapped),
14171 "len {len} permille {permille}: the playhead lands inside the \
14172 caption the write actually put ({landed:?}), got {mapped}"
14173 );
14174 }
14175 }
14176 }
14177 }
14178
14179 /// A grouped caption's cues re-time with its clip: the placement's window
14180 /// crossed the timeline at its own proportion before any rate, and a
14181 /// re-rate changes that proportion (the frames compress, the window does
14182 /// not). A cue eight seconds into a window played at 2x crosses the screen
14183 /// four seconds in -- and at unity every cue lands exactly where it always
14184 /// did, byte for byte.
14185 #[test]
14186 fn a_grouped_captions_cues_re_time_with_its_clip() {
14187 let track = SubtitleTrack {
14188 path: FILE.into(),
14189 track: None,
14190 language: "eng".into(),
14191 name: String::new(),
14192 label: "eng".into(),
14193 cues: vec![crate::subtitle::Cue {
14194 start_us: 8_000_000,
14195 end_us: 9_000_000,
14196 text: "late line".into(),
14197 image: None,
14198 words: Vec::new(),
14199 karaoke: Vec::new(),
14200 }],
14201 bitmap: false,
14202 refused: None,
14203 };
14204 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
14205 let s1 = p.add_lane(LaneKind::Subtitle);
14206 // Ten seconds of the track over ten seconds of timeline: unity.
14207 p.place_sub(
14208 s1,
14209 0,
14210 SubClip {
14211 start: 0,
14212 frames: 300,
14213 track: 0,
14214 in_us: 0,
14215 out_us: 10_000_000,
14216 link: None,
14217 },
14218 )
14219 .expect("placed");
14220
14221 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
14222 let unity = p.sub_lane_cues(s1, FPS);
14223 assert_eq!(
14224 unity
14225 .iter()
14226 .map(|c| (c.start_us, c.end_us, &*c.text))
14227 .collect::<Vec<_>>(),
14228 [(8_000_000, 9_000_000, "late line")],
14229 "a unity placement maps exactly as it always did"
14230 );
14231
14232 // Grouped with the clip and re-rated to 2x: the same window now crosses
14233 // in half the time, so the cue at 8s of it lands 4s in.
14234 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14235 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
14236 .expect("room for it");
14237 let re_timed = p.sub_lane_cues(s1, FPS);
14238 assert_eq!(
14239 re_timed
14240 .iter()
14241 .map(|c| (c.start_us, c.end_us))
14242 .collect::<Vec<_>>(),
14243 [(4_000_000, 4_500_000)],
14244 "the cue crosses with the clip's new rate"
14245 );
14246 }
14247
14248 /// A video arriving on a timeline of words mutates none of them: the
14249 /// import's rippling insert used to open room on the subtitle lanes too,
14250 /// splitting a caption it landed inside and sliding the rest behind the
14251 /// video -- the hand asked for an add, and got a cut it never made. The
14252 /// words keep their own clock; co-travel is what a group is for.
14253 #[test]
14254 fn an_arriving_clip_never_touches_the_captions() {
14255 let caption = |start: u32, frames: u32| SubClip {
14256 start,
14257 frames,
14258 track: 0,
14259 in_us: i64::from(start) * 1_000_000 / 30,
14260 out_us: i64::from(start + frames) * 1_000_000 / 30,
14261 link: None,
14262 };
14263 let track = || SubtitleTrack {
14264 path: FILE.into(),
14265 track: None,
14266 language: "eng".into(),
14267 name: String::new(),
14268 label: "eng".into(),
14269 cues: Vec::new(),
14270 bitmap: false,
14271 refused: None,
14272 };
14273 // A timeline of words alone: 60 frames of caption, no media clips.
14274 let mut p = Project::single(FILE, 60).with_subtitles(vec![track()]);
14275 for l in [Lane::V1, Lane::A1] {
14276 while !p.lane(l).is_empty() {
14277 p.lift(l, 0);
14278 }
14279 }
14280 let s1 = p.add_lane(LaneKind::Subtitle);
14281 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
14282 let before = p.sub_lane(s1).to_vec();
14283
14284 // The video lands BEFORE the caption's span: nothing moves.
14285 let vid = clip(0, 0, 30, 0);
14286 assert!(p.paste(0, vid.clone()), "the video goes down at the head");
14287 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
14288
14289 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
14290 // byte the placement the hand made.
14291 assert!(p.paste(15, vid), "a second video lands inside the caption");
14292 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
14293 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
14294 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
14295 assert!(links_are_consistent(&p.lanes).is_ok());
14296 }
14297
14298 /// The region's caption pieces re-time by mapped boundaries forced apart:
14299 /// rounding start and length independently can land two cues on one frame,
14300 /// and the artifact is clamped -- one frame each, in order, none past the
14301 /// region's new end -- never an overlap on the lane.
14302 #[test]
14303 fn a_regions_caption_pieces_never_round_onto_one_another() {
14304 let caption = |start: u32, frames: u32| SubClip {
14305 start,
14306 frames,
14307 track: 0,
14308 in_us: 0,
14309 out_us: i64::from(frames) * 1_000_000,
14310 link: None,
14311 };
14312 let track = |n| SubtitleTrack {
14313 path: FILE.into(),
14314 track: None,
14315 language: "eng".into(),
14316 name: String::new(),
14317 label: format!("eng{n}"),
14318 cues: Vec::new(),
14319 bitmap: false,
14320 refused: None,
14321 };
14322 // Three lanes, one repro shape each: adjacent one-frame cues, a
14323 // three-frame pair, and the region's last cue against the first
14324 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
14325 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
14326 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
14327 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
14328 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
14329 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
14330 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
14331 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
14332 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
14333
14334 let mut scope = vec![Lane::V1, Lane::A1];
14335 scope.extend(lanes.iter().copied());
14336 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
14337 .expect("the region speeds up");
14338 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
14339 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
14340 p.sub_lane(lane)
14341 .iter()
14342 .map(|s| (s.start, s.frames))
14343 .collect()
14344 };
14345 assert_eq!(
14346 spans(&p, lanes[0]),
14347 [(5, 1), (6, 1)],
14348 "one frame each, in order"
14349 );
14350 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
14351 // and the walk pushes the second to where the first ends.
14352 assert_eq!(
14353 spans(&p, lanes[1]),
14354 [(3, 1), (4, 2)],
14355 "forced apart, kept in order"
14356 );
14357 // The last cue of the region ends exactly where the region now does
14358 // (frame 15), and the caption behind it lands on that same frame:
14359 // touching, never overlapping.
14360 assert_eq!(
14361 spans(&p, lanes[2]),
14362 [(14, 1), (15, 15)],
14363 "the cue ends with the region"
14364 );
14365 for &lane in &lanes {
14366 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
14367 }
14368 }
14369
14370 /// The scope law names a caption half too: a scoped cut that would move one
14371 // track of a group whose caption sits outside the scope is refused.
14372 #[test]
14373 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
14374 let caption = |start: u32, frames: u32| SubClip {
14375 start,
14376 frames,
14377 track: 0,
14378 in_us: 0,
14379 out_us: i64::from(frames) * 1_000_000,
14380 link: None,
14381 };
14382 let track = || SubtitleTrack {
14383 path: FILE.into(),
14384 track: None,
14385 language: "eng".into(),
14386 name: String::new(),
14387 label: "eng".into(),
14388 cues: Vec::new(),
14389 bitmap: false,
14390 refused: None,
14391 };
14392 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14393 let s1 = p.add_lane(LaneKind::Subtitle);
14394 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
14395 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14396
14397 // The subtitle lane is not in the scope, so the group's caption half
14398 // sits outside it: refused, in the law's own words.
14399 let err = p
14400 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
14401 .unwrap_err()
14402 .to_string();
14403 assert!(
14404 err.contains("is one take with the S1 caption at frame 0"),
14405 "{err}"
14406 );
14407
14408 // ...and with the caption's lane in the scope, the cut carries it:
14409 // the words over the hole go, and the words behind slide up.
14410 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
14411 .expect("the whole group is in the scope");
14412 let subs = p.sub_lane(s1);
14413 assert_eq!(
14414 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
14415 [(0, 10), (10, 75)],
14416 "the caption is cut and shifted with the clips"
14417 );
14418 }
14419
14420 /// The caption a hand groups: `group_all` over clips *and* a caption, the
14421 /// mates riding along, the offsets kept, the refusals in words.
14422 #[test]
14423 fn a_hand_built_group_holds_clips_and_a_caption() {
14424 let caption = |start: u32, frames: u32| SubClip {
14425 start,
14426 frames,
14427 track: 0,
14428 in_us: 0,
14429 out_us: i64::from(frames) * 1_000_000,
14430 link: None,
14431 };
14432 let track = || SubtitleTrack {
14433 path: FILE.into(),
14434 track: None,
14435 language: "eng".into(),
14436 name: String::new(),
14437 label: "eng".into(),
14438 cues: Vec::new(),
14439 bitmap: false,
14440 refused: None,
14441 };
14442 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14443 let v2 = p.add_lane(LaneKind::Video);
14444 let s1 = p.add_lane(LaneKind::Subtitle);
14445 // A layer at its own offset, and a caption over the head of the take.
14446 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
14447 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
14448
14449 // Too few, one lane twice, and an index that is not there: words, no
14450 // snapshot.
14451 let history = p.history.len();
14452 assert!(
14453 p.group_all(&[])
14454 .unwrap_err()
14455 .to_string()
14456 .contains("two placements or more")
14457 );
14458 assert!(
14459 p.group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
14460 .unwrap_err()
14461 .to_string()
14462 .contains("V1 is picked twice")
14463 );
14464 assert!(
14465 p.group_all(&[(Lane::V1, 0), (s1, 9)])
14466 .unwrap_err()
14467 .to_string()
14468 .contains("no subtitle 9")
14469 );
14470 assert_eq!(p.history.len(), history, "refusals cost no undo step");
14471
14472 // The group: the picture, the layer, and the caption -- and the sound
14473 // the picture was already grouped with comes along unasked.
14474 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
14475 .expect("three picks, three lanes");
14476 let id = p.lane(Lane::V1)[0].link.expect("grouped");
14477 for lane in [Lane::V1, Lane::A1, v2] {
14478 assert_eq!(
14479 p.lane(lane)[0].link,
14480 Some(id),
14481 "{} rides along",
14482 lane.label()
14483 );
14484 }
14485 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
14486 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
14487 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
14488 assert!(links_are_consistent(&p.lanes).is_ok());
14489 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
14490
14491 // ...and one undo takes it apart again.
14492 assert!(p.undo());
14493 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
14494
14495 // Detach names a caption like it names a clip: every member an id of
14496 // its own, which is never `None` (see `ungroup`).
14497 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
14498 assert!(p.ungroup(s1, 0));
14499 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
14500 assert!(loose_sub.is_some() && loose_clip.is_some());
14501 assert_ne!(loose_sub, loose_clip);
14502 assert!(links_are_consistent(&p.lanes).is_ok());
14503 }
14504
14505 /// Two captions on one sub lane, each already grouped with a *different*
14506 /// clip: `group_all` over both those clips would merge the two existing
14507 /// groups into one id and leave both captions on `s1` carrying it --
14508 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
14509 /// group closes. Refused by name, and nothing moves.
14510 #[test]
14511 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
14512 let caption = |start: u32, frames: u32| SubClip {
14513 start,
14514 frames,
14515 track: 0,
14516 in_us: 0,
14517 out_us: i64::from(frames) * 1_000_000,
14518 link: None,
14519 };
14520 let track = || SubtitleTrack {
14521 path: FILE.into(),
14522 track: None,
14523 language: "eng".into(),
14524 name: String::new(),
14525 label: "eng".into(),
14526 cues: Vec::new(),
14527 bitmap: false,
14528 refused: None,
14529 };
14530 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14531 let v2 = p.add_lane(LaneKind::Video);
14532 let s1 = p.add_lane(LaneKind::Subtitle);
14533 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
14534 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
14535 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
14536 // V1 grouped with the first caption, v2 with the second -- two
14537 // separate groups, each already one member per lane.
14538 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14539 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
14540 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
14541
14542 let history = p.history.len();
14543 let err = p
14544 .group_all(&[(Lane::V1, 0), (v2, 0)])
14545 .unwrap_err()
14546 .to_string();
14547 assert!(err.contains("one placement per lane"), "{err}");
14548 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
14549 assert_eq!(
14550 p.lane(Lane::V1)[0].link,
14551 v1_link,
14552 "the first group untouched"
14553 );
14554 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
14555 assert!(links_are_consistent(&p.lanes).is_ok());
14556 }
14557
14558 /// A split hands the caption of a group the same ids it hands the clips:
14559 /// the left halves keep the group, the right halves share a fresh one.
14560 #[test]
14561 fn a_split_cuts_a_grouped_caption_with_its_clips() {
14562 let caption = |start: u32, frames: u32| SubClip {
14563 start,
14564 frames,
14565 track: 0,
14566 in_us: 0,
14567 out_us: i64::from(frames) * 1_000_000,
14568 link: None,
14569 };
14570 let track = || SubtitleTrack {
14571 path: FILE.into(),
14572 track: None,
14573 language: "eng".into(),
14574 name: String::new(),
14575 label: "eng".into(),
14576 cues: Vec::new(),
14577 bitmap: false,
14578 refused: None,
14579 };
14580 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14581 let s1 = p.add_lane(LaneKind::Subtitle);
14582 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
14583 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14584 let take = p.lane(Lane::V1)[0].link.expect("the group id");
14585
14586 assert!(p.split(4));
14587 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
14588 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
14589 assert_eq!(left.frames, 4);
14590 assert_eq!(
14591 right.link,
14592 p.lane(Lane::V1)[1].link,
14593 "the caption's tail shares the clips' fresh id"
14594 );
14595 assert_ne!(right.link, Some(take));
14596 assert!(links_are_consistent(&p.lanes).is_ok());
14597
14598 // Regroup at the seam restores the take, caption included.
14599 assert!(p.regroup(4));
14600 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
14601 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
14602 }
14603
14604 /// Deleting a member of a hand-built group takes the group: every
14605 /// member's own span out of its own lane, hole closed -- the lanes may
14606 /// end up out of step, which is what one undo restores together.
14607 #[test]
14608 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
14609 let caption = |start: u32, frames: u32| SubClip {
14610 start,
14611 frames,
14612 track: 0,
14613 in_us: 0,
14614 out_us: i64::from(frames) * 1_000_000,
14615 link: None,
14616 };
14617 let track = || SubtitleTrack {
14618 path: FILE.into(),
14619 track: None,
14620 language: "eng".into(),
14621 name: String::new(),
14622 label: "eng".into(),
14623 cues: Vec::new(),
14624 bitmap: false,
14625 refused: None,
14626 };
14627 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14628 let s1 = p.add_lane(LaneKind::Subtitle);
14629 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
14630 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14631 // A neighbour on a lane the group does not touch.
14632 let v2 = p.add_lane(LaneKind::Video);
14633 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
14634
14635 // By the picture or by the caption, the same whole-group delete.
14636 assert!(p.delete_sub_in(s1, 0));
14637 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
14638 assert!(
14639 p.sub_lane(s1).is_empty(),
14640 "the caption's span left its lane"
14641 );
14642 assert_eq!(
14643 p.lane(v2)[0].start,
14644 10,
14645 "a lane the group does not touch stays"
14646 );
14647 assert!(links_are_consistent(&p.lanes).is_ok());
14648 assert!(p.undo(), "one step puts the group back");
14649 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
14650 }
14651
14652 /// The delete law, one statement for every anchor: a caption deleted
14653 /// WITH its group ripples its lane exactly as its clip siblings do --
14654 /// the hole closes and what follows slides up -- while a caption lifted
14655 /// alone leaves its gap, as it always has. And the delete of a grouped
14656 /// clip takes the group from whichever member was clicked.
14657 #[test]
14658 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
14659 let caption = |start: u32, frames: u32| SubClip {
14660 start,
14661 frames,
14662 track: 0,
14663 in_us: 0,
14664 out_us: i64::from(frames) * 1_000_000,
14665 link: None,
14666 };
14667 let track = || SubtitleTrack {
14668 path: FILE.into(),
14669 track: None,
14670 language: "eng".into(),
14671 name: String::new(),
14672 label: "eng".into(),
14673 cues: Vec::new(),
14674 bitmap: false,
14675 refused: None,
14676 };
14677 // V+A+S grouped, with a second caption BEHIND the group's caption:
14678 // closing the hole is what the second caption's position says.
14679 let group = || {
14680 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14681 let s1 = p.add_lane(LaneKind::Subtitle);
14682 p.place_sub(s1, 30, caption(30, 30))
14683 .expect("the group's caption");
14684 p.place_sub(s1, 90, caption(90, 30))
14685 .expect("the caption behind");
14686 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14687 (p, s1)
14688 };
14689
14690 // Deleted by the picture: all three lanes close.
14691 let (mut p, s1) = group();
14692 assert!(p.delete_in(Lane::V1, 0));
14693 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
14694 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
14695 assert_eq!(
14696 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
14697 [60],
14698 "the caption's lane closed by its own span: the follower slid up"
14699 );
14700 assert!(p.undo(), "one step");
14701 assert_eq!(
14702 p.sub_lane(s1).len(),
14703 2,
14704 "both captions back, offsets and all"
14705 );
14706
14707 // By the sound: the same whole-group delete.
14708 let (mut p, s1) = group();
14709 assert!(p.delete_in(Lane::A1, 0));
14710 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
14711 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
14712
14713 // By the caption itself: the same again.
14714 let (mut p, s1) = group();
14715 assert!(p.delete_sub_in(s1, 0));
14716 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
14717 assert_eq!(
14718 p.sub_lane(s1)[0].start,
14719 60,
14720 "closed from the caption's own door"
14721 );
14722 assert!(links_are_consistent(&p.lanes).is_ok());
14723
14724 // A caption lifted ALONE still leaves its gap: the ungrouped law,
14725 // unchanged.
14726 let (mut p, s1) = group();
14727 assert!(p.ungroup(s1, 0), "the caption stands alone");
14728 assert!(p.lift_sub(s1, 0));
14729 assert_eq!(
14730 p.sub_lane(s1)[0].start,
14731 90,
14732 "the follower stayed put: a lone caption's lift is a gap"
14733 );
14734 }
14735
14736 /// Dragging a grouped caption carries its clips, one delta for all of them
14737 /// -- and a caption in no group refuses an overlap exactly as it always did.
14738 #[test]
14739 fn dragging_a_grouped_caption_carries_its_group() {
14740 let caption = |start: u32, frames: u32| SubClip {
14741 start,
14742 frames,
14743 track: 0,
14744 in_us: 0,
14745 out_us: i64::from(frames) * 1_000_000,
14746 link: None,
14747 };
14748 let track = || SubtitleTrack {
14749 path: FILE.into(),
14750 track: None,
14751 language: "eng".into(),
14752 name: String::new(),
14753 label: "eng".into(),
14754 cues: Vec::new(),
14755 bitmap: false,
14756 refused: None,
14757 };
14758 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14759 let s1 = p.add_lane(LaneKind::Subtitle);
14760 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
14761 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14762
14763 // Same lane, further along: everyone moves by the same eight frames.
14764 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
14765 assert_eq!(p.sub_lane(s1)[0].start, 10);
14766 assert_eq!(
14767 p.lane(Lane::V1)[0].start,
14768 8,
14769 "the clip follows by the delta"
14770 );
14771 assert!(links_are_consistent(&p.lanes).is_ok());
14772
14773 // ...and an ungrouped caption is the caption it always was.
14774 assert!(p.ungroup(s1, 0));
14775 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
14776 let s1 = q.add_lane(LaneKind::Subtitle);
14777 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
14778 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
14779 assert!(
14780 q.move_sub(s1, 0, s1, 3)
14781 .unwrap_err()
14782 .to_string()
14783 .contains("already covers")
14784 );
14785 }
14786
14787 /// A trim carries a group's caption by the same delta as its clips, clamped
14788 /// to the caption's own walls -- the offsets between the members survive.
14789 #[test]
14790 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
14791 let caption = |start: u32, frames: u32| SubClip {
14792 start,
14793 frames,
14794 track: 0,
14795 in_us: 0,
14796 out_us: i64::from(frames) * 1_000_000,
14797 link: None,
14798 };
14799 let track = || SubtitleTrack {
14800 path: FILE.into(),
14801 track: None,
14802 language: "eng".into(),
14803 name: String::new(),
14804 label: "eng".into(),
14805 cues: Vec::new(),
14806 bitmap: false,
14807 refused: None,
14808 };
14809 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14810 let s1 = p.add_lane(LaneKind::Subtitle);
14811 // The caption sits two frames into the take and ends one early. The
14812 // source runs past the clip, or there is no tail to pull out.
14813 let src = &[20];
14814 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
14815 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14816
14817 // The tail goes out by three: the clip to 12, the caption to 11.
14818 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
14819 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
14820 assert_eq!(
14821 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
14822 (2, 11),
14823 "the caption follows by the delta"
14824 );
14825 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
14826
14827 // The head comes in by two: everyone's start moves two along.
14828 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
14829 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
14830 assert!(links_are_consistent(&p.lanes).is_ok());
14831 }
14832
14833 #[test]
14834 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
14835 let mut p = three();
14836 let before = shape(&p);
14837 assert!(!p.split(0), "timeline 0 has nothing before it");
14838 assert!(!p.split(3), "existing boundary");
14839 assert!(!p.split(5), "existing boundary");
14840 assert!(!p.split(9), "one past the last frame");
14841 assert!(!p.split(1_000));
14842 assert_eq!(shape(&p), before);
14843 // one undo lands before the *second* split, so the refusals pushed nothing
14844 assert!(p.undo());
14845 assert_eq!(p.clips().len(), 2, "refused splits push no history");
14846
14847 // ...and a frame that is a gap in both lanes has nothing to split.
14848 let mut p = three();
14849 assert!(p.lift(Lane::V1, 1));
14850 assert!(p.lift(Lane::A1, 1));
14851 assert!(!p.split(4), "a gap is not a clip");
14852 }
14853
14854 #[test]
14855 fn regroup_refuses_what_a_split_could_not_have_made() {
14856 let mut p = three();
14857 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
14858 assert!(p.regroup(5));
14859 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
14860 // A boundary with a gap on one side, and one where the sources do not
14861 // meet, are both refused.
14862 let mut p = three();
14863 assert!(p.lift(Lane::V1, 1));
14864 assert!(p.lift(Lane::A1, 1));
14865 assert!(!p.regroup(3), "nothing starts at 3 any more");
14866 let mut p = three();
14867 for l in p.lanes() {
14868 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
14869 }
14870 assert!(!p.regroup(3), "source 100 does not follow source 3");
14871 assert!(!p.regroup(0), "nothing ends at 0");
14872 assert!(!p.regroup(1_000));
14873 }
14874
14875 #[test]
14876 fn map_and_spans_sweep_every_boundary() {
14877 let p = three();
14878 assert_eq!(p.timeline_frames(), 9);
14879 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
14880 // contiguous source here, so the clip index is what actually moves
14881 let expect = [
14882 (0, (0, 0)),
14883 (1, (0, 1)),
14884 (2, (0, 2)),
14885 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
14886 (4, (1, 4)),
14887 (5, (2, 5)),
14888 (6, (2, 6)),
14889 (7, (2, 7)),
14890 (8, (2, 8)),
14891 ];
14892 for (t, want) in expect {
14893 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
14894 }
14895 assert_eq!(p.map_timeline(9), None);
14896 // A span is the rest of the clip from where it was asked about.
14897 assert_eq!(
14898 p.span_at(Lane::V1, 6),
14899 Some(Span {
14900 reverse: false,
14901 ramp: None,
14902 start: 6,
14903 len: 3,
14904 from: Some((0, 6)),
14905 speed: Speed::NORMAL,
14906 pitch: 0,
14907 })
14908 );
14909 assert_eq!(p.span_at(Lane::V1, 9), None);
14910 }
14911
14912 /// The fit policy is one byte *in* the clip rather than an index into a
14913 /// table like the eq and the grade: there is nothing for a table to share.
14914 /// It costs the clip nothing at all -- the fields before it (a `usize`
14915 /// source and two `Option<u16>`s) already left the struct padded to 40
14916 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
14917 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
14918 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
14919 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
14920 /// words after it pads out to the next multiple of 8: 56 bytes total.
14921 /// The transform index is a third `Option<u16>`, same reason as the eq and
14922 /// colour ones before it -- it lands in bytes already spent on padding, so
14923 /// the struct still costs 56.
14924 /// The visualizer look is the first field whose own width outgrows the
14925 /// padding it lands in: it is a `u64` (a strand colour needs bytes above
14926 /// the clip's own four), so the words after it come to 60 and the
14927 /// alignment rounds them to 64 -- one word more than a clip used to cost.
14928 /// Since the gain envelope (`gain_db` plus the `gain_keys` `Vec`, 24 bytes
14929 /// of pointer, length and capacity) the clip is 96 bytes and no longer
14930 /// `Copy`; the `Vec` is what the copy-cost comment above no longer covers.
14931 /// The placement keys (`transform_keys`, a second `Vec`) take it to 120.
14932 /// The fit policy itself is still one byte: it sits in the padding among
14933 /// the other fields, and the total is the 224 (144 before the opacity and colour keys' `Vec`s,
14934 /// 192 before the effects stack's)
14935 /// rounded up to the alignment of 8, so removing it would not shrink the clip.
14936 /// This asserts the one-byte enum and the exact size, so any further growth
14937 /// shows up here first.
14938 #[test]
14939 fn a_fit_policy_costs_the_clip_no_word() {
14940 assert_eq!(std::mem::size_of::<FitPolicy>(), 1);
14941 assert_eq!(
14942 std::mem::size_of::<Clip>(),
14943 224,
14944 "Clip changed size: {} bytes",
14945 std::mem::size_of::<Clip>()
14946 );
14947 }
14948
14949 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
14950 /// anything in `three()` so it is recognisable wherever it lands.
14951 const PASTED: Clip = Clip {
14952 speed_keys: Vec::new(),
14953 reversed: false,
14954 stabilise: None, deinterlace: Deinterlace::Frame, mark: ClipMark { label: 0, off: false },
14955 angle: Angle { video: 0, audio: None },
14956 fade_in: 0,
14957 fade_out: 0,
14958 transition_out: 0,
14959 transition_kind: crate::transitions::TransitionKind::Dissolve,
14960 visualizer: 0,
14961 viz_paint: 0,
14962 gain_db: 0.0,
14963 gain_keys: Vec::new(),
14964 pan: 0,
14965 transform_keys: Vec::new(),
14966 opacity_keys: Vec::new(),
14967 color_keys: Vec::new(),
14968 effects: Vec::new(),
14969 start: 0,
14970 in_frame: 100,
14971 out_frame: 102,
14972 source: 0,
14973 link: None,
14974 eq: None,
14975 color: None,
14976 transform: None,
14977 fit: FitPolicy::Fit,
14978 speed: Speed::NORMAL,
14979 pitch: 0,
14980 };
14981
14982 #[test]
14983 fn paste_mid_clip_splits_around_it() {
14984 let mut p = three();
14985 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
14986 assert_eq!(p.timeline_frames(), 11);
14987 assert_eq!(
14988 shape(&p)[0],
14989 vec![
14990 clip(0, 0, 3, 0),
14991 clip(3, 3, 5, 0),
14992 clip(5, 5, 6, 0),
14993 clip(6, 100, 102, 0),
14994 clip(8, 6, 9, 0),
14995 ]
14996 );
14997 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
14998 // The pasted frames are exactly where they were asked for, and the
14999 // split-off remainder resumes after them.
15000 assert_eq!(p.map_timeline(6), Some((3, 100)));
15001 assert_eq!(p.map_timeline(7), Some((3, 101)));
15002 assert_eq!(p.map_timeline(8), Some((4, 6)));
15003 }
15004
15005 #[test]
15006 fn paste_at_boundary_zero_and_end() {
15007 let mut p = three();
15008 assert!(p.paste(3, PASTED), "existing boundary: no split");
15009 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
15010 assert_eq!(p.map_timeline(3), Some((1, 100)));
15011
15012 let mut p = three();
15013 assert!(p.paste(0, PASTED));
15014 assert_eq!(p.map_timeline(0), Some((0, 100)));
15015 assert_eq!(p.map_timeline(2), Some((1, 0)));
15016
15017 // At the end: appended, there being nothing in front to leave black.
15018 let mut p = three();
15019 assert!(p.paste(9, PASTED));
15020 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
15021 // Past it: down on the frame it was asked for, black in front of it --
15022 // a row let go on the open bed lands under the ghost that promised it.
15023 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
15024 assert!(p.paste(1_000, PASTED));
15025 assert_eq!(p.timeline_frames(), 1_002);
15026 assert_eq!(
15027 p.lane(Lane::V1).last().expect("the pasted clip").start,
15028 1_000
15029 );
15030 assert_eq!(
15031 p.lane(Lane::A1).last().expect("its other half").start,
15032 1_000
15033 );
15034
15035 // An empty clip is the one thing refused, and it pushes no history.
15036 let mut p = three();
15037 assert!(!p.paste(4, clip(0, 7, 7, 0)));
15038 assert_eq!(p.clips().len(), 3);
15039 }
15040
15041 /// The data-loss paste: a clip of a source with no picture used to land on
15042 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
15043 /// carried it was refused on the way back in ("a box with a larger size").
15044 #[test]
15045 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
15046 let mut p = three();
15047 let wav = p.import("/nonexistent/song.wav", 0);
15048 let copied = Clip {
15049 fade_in: 0,
15050 fade_out: 0,
15051 transition_out: 0,
15052 transition_kind: Default::default(),
15053 visualizer: 0,
15054 viz_paint: 0,
15055 gain_db: 0.0,
15056 source: wav,
15057 ..PASTED
15058 };
15059 assert!(p.paste(3, copied));
15060 // The room is opened on every lane, or the two would slide apart...
15061 assert_eq!(p.timeline_frames(), 11);
15062 assert_eq!(
15063 shape(&p)[0],
15064 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
15065 "the video lane got room and nothing else"
15066 );
15067 // ...but the clip itself only reaches the lane that can play it.
15068 assert_eq!(
15069 shape(&p)[1],
15070 vec![
15071 clip(0, 0, 3, 0),
15072 clip(3, 100, 102, wav),
15073 clip(5, 3, 5, 0),
15074 clip(7, 5, 9, 0)
15075 ]
15076 );
15077 // A source with a picture is unchanged: still the grouped pair.
15078 let mut p = three();
15079 assert!(p.paste(3, PASTED));
15080 assert_eq!(shape(&p)[0], shape(&p)[1]);
15081 }
15082
15083 /// A hand-written file may hold a clip that ends at the very last frame
15084 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
15085 /// to wrap its start round to the front of the lane: an overlap in debug, a
15086 /// project no reload would accept in release.
15087 #[test]
15088 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
15089 let far = clip(u32::MAX - 90, 0, 90, 0);
15090 let parts = |c: Clip| {
15091 Project::from_parts(
15092 vec![Source::new(FILE, 0)],
15093 two(vec![c.clone()], vec![c]),
15094 Vec::new(),
15095 Vec::new(),
15096 Vec::new(),
15097 )
15098 .expect("valid parts")
15099 };
15100 let mut p = parts(far.clone());
15101 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
15102 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
15103 assert!(!p.undo(), "...and pushes no history either");
15104 assert!(
15105 !p.paste(u32::MAX, PASTED),
15106 "appending has nowhere to go either: the timeline ends at the last frame"
15107 );
15108 // With room for exactly those frames the same paste is taken.
15109 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
15110 assert!(p.paste(0, PASTED));
15111 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
15112 }
15113
15114 #[test]
15115 fn paste_undoes_in_one_step() {
15116 let mut p = three();
15117 let before = shape(&p);
15118 assert!(p.paste(6, PASTED));
15119 assert!(p.undo());
15120 assert_eq!(shape(&p), before, "a paste is one undo step");
15121 }
15122
15123 #[test]
15124 fn a_copy_outlives_the_clip_it_came_from() {
15125 let mut p = three();
15126 let copied = p.clips()[1].clone(); // [3,5)
15127 assert!(p.delete(1));
15128 // Just a frame range: the source is still on disk either way.
15129 assert!(p.paste(0, copied));
15130 assert_eq!(p.map_timeline(0), Some((0, 3)));
15131 assert_eq!(p.timeline_frames(), 9);
15132 }
15133
15134 #[test]
15135 fn delete_closes_the_gap_on_both_lanes() {
15136 let mut p = three();
15137 assert!(p.delete(1));
15138 assert_eq!(p.timeline_frames(), 7);
15139 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
15140 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
15141 // timeline 3 used to be source 3; the gap closed so it is source 5 now
15142 assert_eq!(p.map_timeline(3), Some((1, 5)));
15143 assert_eq!(p.map_timeline(6), Some((1, 8)));
15144 assert_eq!(p.map_timeline(7), None);
15145 }
15146
15147 #[test]
15148 fn delete_first_last_and_only() {
15149 let mut p = three();
15150 assert!(p.delete(0));
15151 assert_eq!(p.map_timeline(0), Some((0, 3)));
15152 assert_eq!(p.timeline_frames(), 6);
15153
15154 let mut p = three();
15155 assert!(p.delete(2));
15156 assert_eq!(p.timeline_frames(), 5);
15157 assert_eq!(p.map_timeline(4), Some((1, 4)));
15158
15159 assert!(!p.delete(2), "index past the end");
15160 assert!(p.delete(1));
15161 assert!(p.delete(0), "and the last remaining clip goes too");
15162 assert_eq!(p.clips().len(), 0);
15163 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
15164 assert!(!p.delete(0), "there is nothing left to delete");
15165 assert!(p.undo(), "one gesture, one undo");
15166 assert_eq!(p.clips().len(), 1);
15167 }
15168
15169 /// The offset model's point: one lane loses a clip, the other does not move.
15170 #[test]
15171 fn a_lift_leaves_a_gap_and_moves_nothing() {
15172 let mut p = three();
15173 let video_before = shape(&p)[0].clone();
15174 assert!(p.lift(Lane::A1, 1));
15175 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
15176 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
15177 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
15178 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
15179 assert_eq!(p.map(Lane::A1, 4), None);
15180 assert_eq!(
15181 p.span_at(Lane::A1, 3),
15182 Some(Span {
15183 reverse: false,
15184 ramp: None,
15185 start: 3,
15186 len: 2,
15187 from: None,
15188 speed: Speed::NORMAL,
15189 pitch: 0,
15190 })
15191 );
15192 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
15193 assert!(p.undo());
15194 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
15195 }
15196
15197 #[test]
15198 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
15199 let mut p = three();
15200 assert!(p.lift(Lane::A1, 2));
15201 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
15202 assert_eq!(
15203 p.span_at(Lane::A1, 5),
15204 Some(Span {
15205 reverse: false,
15206 ramp: None,
15207 start: 5,
15208 len: 4,
15209 from: None,
15210 speed: Speed::NORMAL,
15211 pitch: 0,
15212 }),
15213 "the audio lane holds silence to the end of the picture"
15214 );
15215 assert_eq!(p.span_at(Lane::A1, 9), None);
15216 // Every lane covers the timeline exactly, gaps included.
15217 for l in p.lanes() {
15218 let spans = p.spans_from(l, 0);
15219 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
15220 assert_eq!(spans[0].start, 0);
15221 }
15222 }
15223
15224 /// The timeline is emptiable: the last placement comes off like any other,
15225 /// the project holds "nothing on any lane" as a state, and one undo per
15226 /// gesture brings it back.
15227 #[test]
15228 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
15229 let mut p = Project::single(FILE, 9);
15230 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
15231 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
15232 assert_eq!(p.timeline_frames(), 0);
15233 assert_eq!(p.composite_span_at(0), None, "nothing to show");
15234 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
15235 assert!(!p.lift(Lane::A1, 0), "index past the end");
15236 assert!(p.undo(), "and the last lift comes back");
15237 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
15238 // A saved-and-loaded empty timeline is a project like any other, and it
15239 // still names the file its frame rate came from.
15240 assert!(p.lift(Lane::V1, 0));
15241 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
15242 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
15243 let back = Project::from_parts(sources, lanes, eq, color, Vec::new())
15244 .expect("an empty project loads");
15245 assert_eq!(back.timeline_frames(), 0);
15246 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
15247 }
15248
15249 /// What a keyboard selection walks: one answer per lane, gaps included --
15250 /// the composite's own answer is one lane's and cannot say what the audio
15251 /// lane holds under the same playhead.
15252 #[test]
15253 fn lane_clip_at_answers_for_each_lane_separately() {
15254 let mut p = Project::single(FILE, 9);
15255 assert!(p.split(3), "both lanes split");
15256 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
15257 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
15258 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
15259 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
15260 // A gap on one lane leaves the other's clip selectable there.
15261 assert!(p.lift(Lane::A1, 0));
15262 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
15263 assert_eq!(
15264 p.lane_clip_at(Lane::A1, 3),
15265 Some(0),
15266 "indices moved with it"
15267 );
15268 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
15269 // A lane that is not there is not a panic.
15270 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
15271 }
15272
15273 #[test]
15274 fn place_overwrites_only_its_own_lane() {
15275 let mut p = three();
15276 let audio_before = shape(&p)[1].clone();
15277 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
15278 // is trimmed, nothing shifts.
15279 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
15280 assert_eq!(
15281 shape(&p)[0],
15282 vec![
15283 clip(0, 0, 3, 0),
15284 clip(3, 3, 4, 0),
15285 clip(4, 100, 102, 0),
15286 clip(6, 6, 9, 0),
15287 ]
15288 );
15289 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
15290 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
15291
15292 // Placed inside one clip, it splits it in two.
15293 let mut p = Project::single(FILE, 9);
15294 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
15295 assert_eq!(
15296 shape(&p)[0],
15297 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
15298 );
15299 // ...and placed past the end it makes a gap, which is the whole point.
15300 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
15301 assert_eq!(p.timeline_frames(), 22);
15302 assert_eq!(
15303 p.span_at(Lane::V1, 9),
15304 Some(Span {
15305 reverse: false,
15306 ramp: None,
15307 start: 9,
15308 len: 11,
15309 from: None,
15310 speed: Speed::NORMAL,
15311 pitch: 0,
15312 })
15313 );
15314 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
15315 }
15316
15317 /// A file with sound let go over a further video track: both halves go down,
15318 /// on the same frames, and the audio row is added when the `+ V` button left
15319 /// the project without one. One undo takes the lane and both clips back.
15320 #[test]
15321 fn a_take_placed_on_a_layer_lands_with_its_sound() {
15322 let mut p = three();
15323 let v2 = p.add_lane(LaneKind::Video);
15324 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
15325
15326 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
15327 let a2 = Lane::new(LaneKind::Audio, 1);
15328 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
15329 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
15330 assert_eq!(p.lane(v2)[0].start, 4);
15331 assert_eq!(p.lane(v2)[0].end(), 6);
15332 assert_eq!(
15333 p.lane(v2)[0].link,
15334 p.lane(a2)[0].link,
15335 "one take, not two placements"
15336 );
15337 assert!(p.lane(v2)[0].link.is_some());
15338 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
15339 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
15340
15341 // The pair overwrites its own two lanes and nothing else, exactly as a
15342 // one-lane place does.
15343 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
15344 assert_eq!(p.lane(v2), p.lane(a2));
15345 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
15346 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
15347
15348 assert!(p.undo(), "one step for the second pair");
15349 assert_eq!(p.lane(v2).len(), 1);
15350 assert!(p.undo(), "one step for the first pair *and* its lane");
15351 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
15352 assert!(p.lane(v2).is_empty());
15353
15354 // Refusals cost nothing: sound placed alone is `place`'s door.
15355 assert!(
15356 !p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)),
15357 "audio lane"
15358 );
15359 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
15360 assert!(
15361 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
15362 "a lane that is not there"
15363 );
15364 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
15365 }
15366
15367 /// The drag between tracks: let go at the frames it already covers the clip
15368 /// keeps them, one undo takes it back, and every way it can be refused
15369 /// leaves the project untouched.
15370 #[test]
15371 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
15372 let v2 = Lane::new(LaneKind::Video, 1);
15373 let mut p = three();
15374 assert_eq!(p.add_lane(LaneKind::Video), v2);
15375 let before = shape(&p);
15376
15377 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
15378 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
15379 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
15380 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
15381 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
15382 // One snapshot: a single undo, and the lane list survives it.
15383 assert!(p.undo());
15384 assert_eq!(shape(&p), before);
15385
15386 // A lane that is not there, the lane and frame it is already at, an
15387 // index that is not there, and a move across kinds: all refused,
15388 // nothing changed.
15389 let history = p.history.len();
15390 for (from, idx, to, start) in [
15391 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
15392 (Lane::V1, 1, Lane::V1, 3),
15393 (Lane::V1, 9, v2, 3),
15394 (Lane::V1, 1, Lane::A1, 3),
15395 (Lane::A1, 1, v2, 3),
15396 ] {
15397 assert!(
15398 !p.move_clip(from, idx, to, start),
15399 "{from:?} {idx} -> {to:?} at {start}"
15400 );
15401 }
15402 assert_eq!(shape(&p), before);
15403 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
15404
15405 // Landing on another clip is refused rather than overwriting it: the
15406 // pointer named the lane, never the take already sitting there.
15407 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
15408 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
15409 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
15410 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
15411 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
15412 }
15413
15414 /// A lane's name is a label: the address is unchanged, it is one undo step, an
15415 /// empty name clears it, a lane's removal takes it along, and a clip's deinterlace
15416 /// choice survives a split, a copy and an undo.
15417 #[test]
15418 fn lane_names_and_deinterlace_follow_the_usual_edit_rules() {
15419 let sources = vec![Source::new(FILE, 0)];
15420 let lanes = vec![(LaneKind::Video, vec![clip(0, 0, 10, 0)]), (LaneKind::Audio, vec![clip(0, 0, 10, 0)])];
15421 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15422 assert_eq!(p.set_lane_name(Lane::V1, " Interview "), Ok(true));
15423 assert_eq!(p.lane_name(Lane::V1), Some("Interview"));
15424 assert_eq!(p.lane_title(Lane::V1), "Interview");
15425 assert_eq!(p.lane_title(Lane::A1), "A1");
15426 assert_eq!(p.set_lane_name(Lane::V1, "Interview"), Ok(false), "no change, no history");
15427 assert!(p.set_lane_name(Lane::V1, &"x".repeat(MAX_LANE_NAME_CHARS + 1)).is_err());
15428 assert!(p.set_lane_name(Lane::V1, "a\nb").is_err());
15429 assert_eq!(p.set_lane_name(Lane::S1, "x"), Ok(false), "no such lane");
15430 assert!(p.undo());
15431 assert_eq!(p.lane_name(Lane::V1), None);
15432 assert!(p.redo());
15433 assert_eq!(p.lane_names(), vec!["Interview".to_string(), String::new()]);
15434 assert_eq!(p.set_lane_name(Lane::V1, " "), Ok(true), "blank clears");
15435 assert_eq!(p.lane_name(Lane::V1), None);
15436
15437 assert!(p.set_deinterlace(Lane::V1, 0, Deinterlace::Field));
15438 assert!(!p.set_deinterlace(Lane::V1, 0, Deinterlace::Field));
15439 assert!(!p.set_deinterlace(Lane::A1, 0, Deinterlace::Off), "video clips only");
15440 assert!(p.split(5));
15441 assert_eq!(p.deinterlace_of(Lane::V1, 0), Deinterlace::Field);
15442 assert_eq!(p.deinterlace_of(Lane::V1, 1), Deinterlace::Field, "both halves keep it");
15443 assert!(p.undo() && p.undo());
15444 assert_eq!(p.deinterlace_of(Lane::V1, 0), Deinterlace::Frame);
15445 assert!(p.redo());
15446 let copy = p.lane(Lane::V1)[0].clone();
15447 assert_eq!(copy.deinterlace, Deinterlace::Field, "a copy carries it");
15448 }
15449
15450 /// The drag *along* a track, which is the one every other editor has: the
15451 /// clip lands on the frame the pointer let it go at, and stops dead against
15452 /// the neighbour rather than overwriting it.
15453 #[test]
15454 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
15455 let sources = vec![Source::new(FILE, 0)];
15456 let lanes = vec![
15457 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
15458 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
15459 ];
15460 let mut p =
15461 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15462 let before = shape(&p);
15463
15464 // Into the gap, exactly where it was let go -- nothing else moves.
15465 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
15466 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
15467 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
15468 // Dragged past the clip in front of it: clamped to its wall, laid end
15469 // to end with it, never over it.
15470 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
15471 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
15472 // One undo per drag, and both of them together are the state it started
15473 // in -- the frames each clip plays never changed.
15474 assert!(p.undo() && p.undo());
15475 assert_eq!(shape(&p), before);
15476
15477 // A drop that changes nothing is a click, not an edit.
15478 let history = p.history.len();
15479 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
15480 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
15481 }
15482
15483 /// A move lands on any empty frames of its lane, jumping over the clips
15484 /// between -- where a drag only slides up to the first one it meets.
15485 #[test]
15486 fn a_move_jumps_over_clips_to_empty_frames() {
15487 let sources = vec![Source::new(FILE, 0)];
15488 let lanes = vec![
15489 (LaneKind::Video, vec![clip(0, 0, 4, 0), clip(6, 4, 8, 0), clip(12, 8, 12, 0)]),
15490 (LaneKind::Audio, vec![clip(0, 0, 4, 0)]),
15491 ];
15492 let mut p =
15493 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15494
15495 // [0,4) to [16,20): past the clip at 6 and the clip at 12, both empty
15496 // frames of the lane -- a move, not an insert, so nothing else shifts.
15497 assert!(p.move_clip(Lane::V1, 0, Lane::V1, 16));
15498 assert_eq!(
15499 shape(&p)[0],
15500 vec![clip(6, 4, 8, 0), clip(12, 8, 12, 0), clip(16, 0, 4, 0)]
15501 );
15502 // A gap of two frames (10..12) is too narrow for a four-frame clip: refused.
15503 let before = shape(&p);
15504 assert!(!p.move_clip(Lane::V1, 2, Lane::V1, 10), "no gap that wide");
15505 assert_eq!(shape(&p), before);
15506 }
15507
15508 /// A linked take jumps as one: its partner on the audio lane must be free
15509 /// at the same frames, and where it is not the drop is clamped to the
15510 /// partner's wall rather than overlapping it.
15511 #[test]
15512 fn a_linked_take_jumps_only_where_its_partner_is_free() {
15513 let link = |mut c: Clip| {
15514 c.link = Some(7);
15515 c
15516 };
15517 let sources = vec![Source::new(FILE, 0)];
15518 let lanes = vec![
15519 (LaneKind::Video, vec![link(clip(0, 0, 4, 0)), clip(12, 4, 8, 0)]),
15520 (LaneKind::Audio, vec![link(clip(0, 0, 4, 0))]),
15521 ];
15522 let mut p =
15523 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15524 let v2 = p.add_lane(LaneKind::Video);
15525
15526 // Both halves free at [20,24): the take lands there, partner included.
15527 assert!(p.move_clip(Lane::V1, 0, v2, 20));
15528 assert_eq!(p.lane(v2).iter().map(|c| c.start).collect::<Vec<_>>(), [20]);
15529 assert_eq!(p.lane(Lane::A1)[0].start, 20, "partner moves the same distance");
15530 assert_eq!(p.lane(Lane::A1)[0].link, Some(7));
15531
15532 // A partner blocked at [22,26) on the audio lane: the drop stops at the
15533 // frame where the partner meets nothing, never over the blocker.
15534 let sources = vec![Source::new(FILE, 0)];
15535 let lanes = vec![
15536 (LaneKind::Video, vec![link(clip(0, 0, 4, 0))]),
15537 (LaneKind::Audio, vec![link(clip(0, 0, 4, 0)), clip(22, 0, 4, 0)]),
15538 ];
15539 let mut p =
15540 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15541 let v2 = p.add_lane(LaneKind::Video);
15542 assert!(p.move_clip(Lane::V1, 0, v2, 20));
15543 assert_eq!(p.lane(v2)[0].start, 18, "clamped to the partner's wall");
15544 assert_eq!(p.lane(Lane::A1)[0].start, 18);
15545 assert_eq!(p.lane(Lane::A1)[1].start, 22, "the blocker is not moved");
15546 }
15547
15548 /// A drag carries the whole take: the sound half travels exactly as far as
15549 /// the picture does, and the tighter of their two walls stops both.
15550 #[test]
15551 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
15552 let mut p = three();
15553 assert!(
15554 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
15555 "room to the right"
15556 );
15557 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
15558 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
15559 // Something in the sound's way, and nothing at all in the picture's.
15560 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
15561 let before = shape(&p);
15562
15563 // Let go over empty frames on both lanes: the take lands there whole,
15564 // jumping the blocker that lies between.
15565 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
15566 assert!(p.lane(Lane::V1).iter().any(|c| c.start == 30));
15567 assert!(p.lane(Lane::A1).iter().any(|c| c.start == 30), "sound came with it");
15568 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15569 assert!(p.undo());
15570 assert_eq!(shape(&p), before, "one undo for the whole take");
15571
15572 // Let go on the sound's blocker: the take stops against it, picture
15573 // and sound alike, short of the frame the pointer named.
15574 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 9), "dropped on the blocker");
15575 assert!(p.lane(Lane::V1).iter().any(|c| c.start == 8), "stopped where the sound did");
15576 assert!(p.lane(Lane::A1).iter().any(|c| c.start == 8), "and the sound came with it");
15577 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15578 assert!(p.undo());
15579 assert_eq!(shape(&p), before, "one undo for the whole take");
15580 }
15581
15582 /// The drag that does both at once -- another lane *and* another frame --
15583 /// which is what a pointer let go over a lane always names.
15584 #[test]
15585 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
15586 let v2 = Lane::new(LaneKind::Video, 1);
15587 let mut p = three();
15588 assert_eq!(p.add_lane(LaneKind::Video), v2);
15589
15590 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
15591 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
15592 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
15593 assert_eq!(
15594 p.lane(Lane::A1)[2].start,
15595 20,
15596 "its sound travelled the same distance"
15597 );
15598 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15599 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
15600 }
15601
15602 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
15603 /// [`three`] cuts up all nine of its frames.
15604 const SRC: &[u32] = &[9];
15605
15606 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
15607 /// else on the lane moves, and every wall stops the edge rather than
15608 /// refusing the gesture.
15609 #[test]
15610 fn trimming_the_tail_stops_at_every_wall() {
15611 let mut p = three();
15612
15613 // Pulled in: a gap opens behind it and the clip after it stays put.
15614 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
15615 assert_eq!(
15616 shape(&p)[0],
15617 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
15618 );
15619 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
15620 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
15621
15622 // ...and back out, no further than the clip behind it.
15623 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
15624 assert_eq!(
15625 shape(&p)[0][1],
15626 clip(3, 3, 5, 0),
15627 "stopped at the neighbour"
15628 );
15629 assert!(
15630 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
15631 "already at the wall"
15632 );
15633
15634 // One frame of clip always survives, however far back the pointer went.
15635 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
15636 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
15637
15638 // The last clip has no neighbour, so what stops it is the file: nine
15639 // frames is nine frames.
15640 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
15641 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
15642 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
15643 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
15644 // A source nobody told us the length of may not grow at all -- an
15645 // out-point past the end of a file is a save that will not open again.
15646 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
15647 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
15648 }
15649
15650 /// The head pulled in takes the in-point with it -- what stays plays what it
15651 /// always played -- and stops at the source's own first frame.
15652 #[test]
15653 fn trimming_the_head_moves_the_in_point() {
15654 let mut p = three();
15655 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
15656 assert_eq!(
15657 shape(&p)[0][0],
15658 clip(2, 2, 3, 0),
15659 "two frames off the front"
15660 );
15661 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
15662 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
15663 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
15664 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
15665 // One frame survives here too.
15666 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
15667 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
15668
15669 // A clip that does not begin at its source's first frame: its head goes
15670 // back to source frame 0 and not one frame further.
15671 let mut p = Project::single(FILE, 9);
15672 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
15673 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
15674 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
15675 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
15676 }
15677
15678 /// A clip whose in-point is *past* its own start -- what a ripple delete
15679 /// leaves, the piece in front of it gone and this one slid back to frame 0
15680 /// carrying the in-point the cut gave it. Its head has more source behind it
15681 /// than the timeline has room for, and the timeline's own first frame is the
15682 /// wall: asking is not an overflow, and the answer is 0.
15683 #[test]
15684 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
15685 let mut p = Project::single(FILE, 9);
15686 assert!(p.split(5));
15687 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
15688 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
15689
15690 assert_eq!(
15691 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
15692 Some((0, 3)),
15693 "back to frame 0 at most, and one frame of clip always survives"
15694 );
15695 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
15696 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
15697 assert_eq!(
15698 shape(&p)[0],
15699 vec![clip(2, 7, 9, 0)],
15700 "the in-point followed"
15701 );
15702 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
15703 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
15704 }
15705
15706 /// A still is trimmed from its head exactly as it is from its tail: it has
15707 /// no earlier frame to walk an in-point back to, so the wall is the length
15708 /// the caller's table allows it, measured back from the tail. Measured from
15709 /// the in-point -- which a placed picture has at 0 -- its left edge could
15710 /// never be dragged outwards at all.
15711 #[test]
15712 fn a_stills_head_stretches_out_like_its_tail() {
15713 const STILL: &str = "/nonexistent/card.png";
15714 /// What a still is held to, as `PlaybackSession` fills the table in.
15715 const CAP: &[u32] = &[60];
15716
15717 let mut p = Project::single(STILL, 20);
15718 assert!(p.lift(Lane::A1, 0), "a picture is silent");
15719 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
15720 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
15721
15722 // A source with no entry in the table may not grow, here as at the tail.
15723 assert_eq!(
15724 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
15725 Some((100, 119)),
15726 "a length nobody told us buys no head room"
15727 );
15728 assert_eq!(
15729 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
15730 Some((60, 119)),
15731 "back to a whole cap's worth, one frame of clip surviving"
15732 );
15733 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
15734 assert_eq!(
15735 shape(&p)[0][0],
15736 clip(80, 0, 40, 0),
15737 "twenty frames longer, and still read from the source's first frame"
15738 );
15739 // Past the cap is clamped, exactly as the tail is -- not refused.
15740 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
15741 assert_eq!(
15742 shape(&p)[0][0],
15743 clip(60, 0, 60, 0),
15744 "a cap's worth, no more"
15745 );
15746 // ...and the clip in front is the nearer wall of the two: no head trim
15747 // may open an overlap.
15748 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
15749 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
15750 assert_eq!(
15751 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
15752 Some((85, 119)),
15753 "up to the neighbour's last frame and not over it"
15754 );
15755 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
15756 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
15757 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
15758 }
15759
15760 /// An end edge that runs out of source names the source's tail as its
15761 /// wall, and the same edge stopped by the clip after it does not -- and the
15762 /// walls are the ones `trim_room` gives, not a second computation.
15763 #[test]
15764 fn trim_walls_name_the_source_tail_or_the_neighbour() {
15765 let mut p = Project::single(FILE, 9);
15766 assert_eq!(
15767 p.trim_walls(Lane::V1, 0, Edge::End, SRC),
15768 Some(TrimWalls {
15769 lo: 1,
15770 hi: 9,
15771 lo_media: false,
15772 hi_media: true,
15773 }),
15774 "the whole source, and it runs out at its tail"
15775 );
15776 assert_eq!(
15777 p.trim_walls(Lane::V1, 0, Edge::End, SRC)
15778 .map(|w| (w.lo, w.hi)),
15779 p.trim_room(Lane::V1, 0, Edge::End, SRC),
15780 );
15781
15782 assert!(p.split(5));
15783 assert_eq!(
15784 p.trim_walls(Lane::V1, 0, Edge::End, SRC),
15785 Some(TrimWalls {
15786 lo: 1,
15787 hi: 5,
15788 lo_media: false,
15789 hi_media: false,
15790 }),
15791 "the source has more, but the next piece is nearer"
15792 );
15793 assert_eq!(
15794 p.trim_walls(Lane::V1, 1, Edge::End, SRC),
15795 Some(TrimWalls {
15796 lo: 6,
15797 hi: 9,
15798 lo_media: false,
15799 hi_media: true,
15800 }),
15801 "the last piece runs to the source's tail"
15802 );
15803 assert_eq!(
15804 p.trim_walls(Lane::V1, 2, Edge::End, SRC),
15805 None,
15806 "no such clip"
15807 );
15808 }
15809
15810 /// A start edge that drags back to the source's first frame names that
15811 /// head as its wall; one stopped by the piece in front of it does not.
15812 #[test]
15813 fn trim_walls_name_the_source_head_or_the_neighbour() {
15814 let mut p = Project::single(FILE, 9);
15815 assert!(p.split(5));
15816 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
15817 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
15818 assert_eq!(
15819 p.trim_walls(Lane::V1, 0, Edge::Start, SRC),
15820 Some(TrimWalls {
15821 lo: 0,
15822 hi: 3,
15823 lo_media: true,
15824 hi_media: false,
15825 }),
15826 "frame 0 is the head's first frame, and the clip's own minimum is the other wall"
15827 );
15828
15829 let mut p = Project::single(FILE, 9);
15830 assert!(p.split(5));
15831 assert_eq!(
15832 p.trim_walls(Lane::V1, 1, Edge::Start, SRC),
15833 Some(TrimWalls {
15834 lo: 5,
15835 hi: 8,
15836 lo_media: false,
15837 hi_media: false,
15838 }),
15839 "the head has room back to 0, but the piece in front stops it at 5"
15840 );
15841 }
15842
15843 /// A still has no media limit: its head and tail reach as far as the cap
15844 /// says, and that reach is never reported as the source's end.
15845 #[test]
15846 fn a_still_never_reports_media() {
15847 const STILL: &str = "/nonexistent/card.png";
15848 const CAP: &[u32] = &[60];
15849
15850 let mut p = Project::single(STILL, 20);
15851 assert!(p.lift(Lane::A1, 0), "a picture is silent");
15852 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
15853 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
15854
15855 assert_eq!(
15856 p.trim_walls(Lane::V1, 0, Edge::Start, CAP),
15857 Some(TrimWalls {
15858 lo: 60,
15859 hi: 119,
15860 lo_media: false,
15861 hi_media: false,
15862 }),
15863 );
15864 assert_eq!(
15865 p.trim_walls(Lane::V1, 0, Edge::End, CAP),
15866 Some(TrimWalls {
15867 lo: 101,
15868 hi: 160,
15869 lo_media: false,
15870 hi_media: false,
15871 }),
15872 );
15873 }
15874
15875 /// Linked halves trim as one: a link is one span on however many lanes, so
15876 /// the sound follows the picture's edge -- and the tightest wall of the two
15877 /// is what stops both.
15878 #[test]
15879 fn linked_halves_trim_together() {
15880 let mut p = three();
15881 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
15882 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
15883
15884 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
15885 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
15886 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
15887 assert!(
15888 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
15889 "either half drags it"
15890 );
15891 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
15892 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15893
15894 // Something in the way on the *audio* lane stops the picture's tail as
15895 // well: the group can only go as far as its tightest member.
15896 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
15897 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
15898 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
15899 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
15900 links_are_consistent(&p.lanes).expect("still one span");
15901 }
15902
15903 /// An overwrite that cuts through a take on both of its lanes leaves the take whole: the head
15904 /// and the tail of the cut each keep one id shared across the lanes, so a trim of either lane
15905 /// still drags the other. A cut that would leave one lane's half without its partner detaches.
15906 #[test]
15907 fn an_overwrite_through_a_take_keeps_the_take_whole() {
15908 let mut p = three();
15909 assert!(p.edit_from_source(SourceEdit::Overwrite, 6, &[(Lane::V1, clip(0, 0, 2, 0)), (Lane::A1, clip(0, 0, 2, 0))]).is_ok());
15910 let head = p.lane(Lane::V1)[2].link;
15911 assert!(head.is_some(), "the head of the cut is still one take");
15912 assert_eq!(p.lane(Lane::A1)[2].link, head, "and so is the sound's head");
15913 assert_eq!(p.lane(Lane::V1)[4].link, p.lane(Lane::A1)[4].link, "the tail is one take too");
15914 assert!(p.lane(Lane::V1)[4].link.is_some());
15915 assert_ne!(p.lane(Lane::V1)[4].link, head, "the tail is a take of its own");
15916 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15917
15918 // The head's sound follows the picture's trim, as it does everywhere else.
15919 assert!(p.trim(Lane::V1, 0, Edge::End, 2, SRC));
15920 assert_eq!(p.lane(Lane::A1)[0].end(), 2, "the sound followed the picture");
15921 links_are_consistent(&p.lanes).expect("still one span");
15922 }
15923
15924 /// A take that loses its last partner is detached: the survivor keeps an id
15925 /// that no other placement shares (a lone id, which the front-ends draw as
15926 /// detached), whichever edit took the partner away -- a lift, a split on some
15927 /// lanes -- and one undo puts the take back exactly.
15928 #[test]
15929 fn a_take_down_to_one_member_is_detached() {
15930 let mut p = three();
15931 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
15932 assert_eq!(p.lane(Lane::A1)[2].link, Some(link));
15933
15934 assert!(p.lift(Lane::V1, 2));
15935 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "the survivor keeps its id");
15936 assert!(p.undo());
15937 assert_eq!(p.lane(Lane::V1)[2].link, Some(link), "undo restores the picture's link");
15938 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "and the sound's");
15939
15940 // A split on the picture lane only: every half of the take is detached
15941 // (a fresh id of its own), in one snapshot.
15942 let history = p.history.len();
15943 assert!(p.split_on(7, &[Lane::V1]));
15944 assert_eq!(p.history.len(), history + 1, "one snapshot for the whole split");
15945 let ids: Vec<Option<u32>> = vec![
15946 p.lane(Lane::V1)[2].link,
15947 p.lane(Lane::V1)[3].link,
15948 p.lane(Lane::A1)[2].link,
15949 ];
15950 assert!(ids.iter().all(Option::is_some), "each half is detached: {ids:?}");
15951 assert!(ids[0] != ids[1] && ids[0] != ids[2] && ids[1] != ids[2], "{ids:?}");
15952 links_are_consistent(&p.lanes).expect("no two members share an id");
15953 assert!(p.undo());
15954 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "undo restores the take");
15955 assert_eq!(p.lane(Lane::V1)[2].link, Some(link));
15956 }
15957
15958 /// `swap` trades two placements of one lane: the first takes the second's
15959 /// start, the one between them ripples by the length difference, and the
15960 /// second lands where the first was (moved by that difference). The span
15961 /// keeps its length; a grouped placement refuses; one undo puts it back.
15962 #[test]
15963 fn swap_trades_two_clips_and_ripples_the_difference() {
15964 let mut p = Project::single(FILE, 1);
15965 let v = p.add_lane(LaneKind::Video);
15966 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
15967 assert!(p.place(v, 3, clip(3, 3, 5, 0)));
15968 assert!(p.place(v, 5, clip(5, 5, 9, 0)));
15969 // [0,3) len 3 and [5,9) len 4 trade places; the middle [3,5) moves by +1.
15970 assert!(p.swap(v, 0, 2));
15971 let got: Vec<(u32, u32, u32)> = p
15972 .lane(v)
15973 .iter()
15974 .map(|c| (c.start, c.frames(), c.in_frame))
15975 .collect();
15976 assert_eq!(got, vec![(0, 4, 5), (4, 2, 3), (6, 3, 0)]);
15977 assert!(p.undo());
15978 assert_eq!(p.lane(v)[0].start, 0);
15979 assert_eq!(p.lane(v)[0].frames(), 3, "one undo puts the order back");
15980
15981 // A grouped placement is not swapped apart.
15982 let mut t = three();
15983 assert!(!t.swap(Lane::V1, 0, 2), "the take is moved as a take");
15984 assert!(!t.swap(Lane::V1, 1, 1), "same clip");
15985 }
15986
15987 /// A clip whose link no other clip shares (what `ungroup` leaves) swaps like any other.
15988 #[test]
15989 fn swap_moves_a_detached_clip_but_not_a_take() {
15990 let mut p = three();
15991 assert!(p.ungroup(Lane::V1, 0) && p.ungroup(Lane::V1, 2), "both ends are detached first");
15992 assert!(p.lane(Lane::V1)[0].link.is_some(), "the lone link stays");
15993 assert!(p.swap(Lane::V1, 0, 2), "a lone link is not a take");
15994 assert_eq!(p.lane(Lane::V1)[0].in_frame, 5, "the later clip took the head");
15995 assert!(p.undo());
15996 // Clip 1 on V1 is still in its take with A1, so a swap that includes it is refused.
15997 let mut t = three();
15998 assert!(t.ungroup(Lane::V1, 0));
15999 assert!(!t.swap(Lane::V1, 0, 1), "a take still moves as a take");
16000 assert!(t.swap_in_place(Lane::V1, 0, 1).is_err(), "a take still moves as a take");
16001 }
16002
16003 /// The non-rippling swap: the two clips trade heads, the shorter leaves a gap
16004 /// where it was, and nothing between them moves. A clip moving into the slot
16005 /// the other vacates is allowed -- the check is on the finished positions.
16006 #[test]
16007 fn swap_in_place_exchanges_heads_and_moves_nothing_else() {
16008 let mut p = Project::single(FILE, 1);
16009 let v = p.add_lane(LaneKind::Video);
16010 assert!(p.place(v, 0, clip(0, 0, 2, 0)));
16011 assert!(p.place(v, 4, clip(4, 4, 5, 0)));
16012 assert!(p.place(v, 9, clip(9, 9, 12, 0)));
16013 p.swap_in_place(v, 0, 2).expect("the longer clip fits the 0..4 space");
16014 let got: Vec<(u32, u32, u32)> = p
16015 .lane(v)
16016 .iter()
16017 .map(|c| (c.start, c.frames(), c.in_frame))
16018 .collect();
16019 assert_eq!(got, vec![(0, 3, 9), (4, 1, 4), (9, 2, 0)]);
16020 assert!(p.undo());
16021 assert_eq!(p.lane(v)[0].in_frame, 0, "one undo restores the lane");
16022 assert_eq!(p.lane(v)[2].start, 9);
16023 }
16024
16025 /// A longer clip that cannot fit its new head is refused by name, and the lane
16026 /// is untouched -- nothing is half-swapped.
16027 #[test]
16028 fn swap_in_place_refuses_a_clip_that_would_overlap_by_name() {
16029 let mut p = Project::single(FILE, 1);
16030 let v = p.add_lane(LaneKind::Video);
16031 assert!(p.place(v, 0, clip(0, 0, 2, 0)));
16032 assert!(p.place(v, 2, clip(2, 2, 3, 0)));
16033 assert!(p.place(v, 4, clip(4, 4, 8, 0)));
16034 let before: Vec<(u32, u32)> = p.lane(v).iter().map(|c| (c.start, c.frames())).collect();
16035 let err = p.swap_in_place(v, 0, 2).expect_err("the 4-frame clip does not fit 0..2");
16036 assert!(err.to_string().contains("clip 1"), "names the clip in the way: {err}");
16037 let after: Vec<(u32, u32)> = p.lane(v).iter().map(|c| (c.start, c.frames())).collect();
16038 assert_eq!(before, after, "a refusal changes nothing");
16039 assert!(p.swap_in_place(v, 1, 1).is_err(), "the same clip twice");
16040 }
16041
16042 /// `ungroup` takes a whole take apart: each member gets an id of its own,
16043 /// so the take is no longer a group, and one undo puts it back.
16044 #[test]
16045 fn ungroup_gives_each_member_its_own_id() {
16046 let mut p = three();
16047 assert!(p.ungroup(Lane::A1, 2));
16048 assert_ne!(p.lane(Lane::A1)[2].link, p.lane(Lane::V1)[2].link);
16049 assert!(p.undo());
16050 assert!(p.lane(Lane::V1)[2].link.is_some(), "undo puts the take back");
16051 }
16052
16053 /// The bug this guards: grouping a take's picture with a clip from another
16054 /// take merges all four into one id, and ungrouping the picture must hand
16055 /// each take back whole -- not detach both halves of the first take too.
16056 #[test]
16057 fn ungroup_of_a_member_of_a_merged_group_keeps_its_take() {
16058 let v2 = Lane::new(LaneKind::Video, 1);
16059 let a2 = Lane::new(LaneKind::Audio, 1);
16060 let mut p = Project::single(FILE, 9);
16061 p.add_lane(LaneKind::Video);
16062 let other = p.lane(Lane::V1)[0].clone();
16063 assert!(p.place_take(v2, 20, other));
16064 let all = |p: &Project| -> Vec<Vec<Clip>> { p.lanes().iter().map(|&l| p.lane(l).to_vec()).collect() };
16065 let before = all(&p);
16066
16067 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16068 assert_eq!(p.lane(Lane::A1)[0].link, p.lane(v2)[0].link, "one group of four");
16069 assert!(p.ungroup(Lane::V1, 0));
16070 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the first take is still linked");
16071 assert_eq!(p.lane(v2)[0].link, p.lane(a2)[0].link, "the second take is still linked");
16072 assert_ne!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "and the two takes are apart");
16073
16074 // One undo is the merged group, and a second one the state before it.
16075 assert!(p.undo());
16076 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "the merge is back");
16077 assert!(p.undo());
16078 assert_eq!(all(&p), before, "undo is exact");
16079 }
16080
16081 /// A caption grouped onto a whole take: ungrouping the caption takes the
16082 /// caption off and leaves the take linked, the same as a loose clip would.
16083 #[test]
16084 fn ungroup_of_a_caption_on_a_take_keeps_the_take() {
16085 let mut p = Project::single(FILE, 9).with_subtitles(vec![subtitle_track()]);
16086 let subs = p.add_lane(LaneKind::Subtitle);
16087 let caption = SubClip { start: 0, frames: 9, track: 0, in_us: 0, out_us: 300_000, link: None };
16088 p.place_sub(subs, 0, caption).expect("the caption goes down");
16089 p.group_all(&[(Lane::V1, 0), (subs, 0)]).expect("a clip and a caption are a group");
16090 assert!(p.ungroup(subs, 0));
16091 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the take is still linked");
16092 let cap = p.sub_lane(subs)[0].link;
16093 assert!(cap.is_some() && cap != p.lane(Lane::V1)[0].link, "the caption is a half of its own");
16094 }
16095
16096 /// A take grouped with one loose clip: ungrouping the take's picture
16097 /// detaches the loose clip and leaves the take linked, and ungrouping the
16098 /// loose clip does the same from the other side.
16099 #[test]
16100 fn ungroup_of_a_take_with_a_loose_clip_detaches_only_the_loose_clip() {
16101 let v2 = Lane::new(LaneKind::Video, 1);
16102 let loose = |p: &Project| Clip { link: None, ..p.lane(Lane::V1)[0].clone() };
16103 let mut p = Project::single(FILE, 9);
16104 p.add_lane(LaneKind::Video);
16105 let mut clip = loose(&p);
16106 clip.start = 20;
16107 assert!(p.place(v2, 20, clip.clone()));
16108
16109 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16110 assert!(p.ungroup(v2, 0));
16111 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the take is still linked");
16112 assert!(p.lane(v2)[0].link.is_some() && p.lane(v2)[0].link != p.lane(Lane::V1)[0].link);
16113 assert!(p.undo());
16114
16115 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16116 assert!(p.ungroup(Lane::V1, 0));
16117 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "from the picture too");
16118 assert_ne!(p.lane(v2)[0].link, p.lane(Lane::V1)[0].link);
16119 assert!(links_are_consistent(&p.lanes).is_ok());
16120 }
16121
16122 /// A whole drag is one undo step -- the front-end commits once, at the
16123 /// release -- and an edge asked to stay where it is costs none at all.
16124 #[test]
16125 fn a_trim_is_one_undo_step() {
16126 let mut p = three();
16127 let before = shape(&p);
16128 let history = p.history.len();
16129
16130 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
16131 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
16132 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
16133 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
16134 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
16135 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
16136
16137 assert!(p.undo());
16138 assert_eq!(shape(&p), before, "both halves back, in one step");
16139 }
16140
16141 /// A moved half stays in its group: a link names a span, not a lane, so the
16142 /// picture on `V2` is still the same take as the sound under it on `A1`.
16143 #[test]
16144 fn move_clip_keeps_the_group() {
16145 let v2 = Lane::new(LaneKind::Video, 1);
16146 let mut p = three();
16147 p.add_lane(LaneKind::Video);
16148 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
16149 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
16150 assert!(p.move_clip(Lane::V1, 1, v2, 3));
16151 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
16152 links_are_consistent(&p.lanes).expect("one id per lane, one span");
16153 assert_eq!(
16154 p.lane(v2)[0].start,
16155 p.lane(Lane::A1)[1].start,
16156 "and still covers the same span as its sound"
16157 );
16158 }
16159
16160 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
16161 /// head of a lane, between two clips, inside a clip, past the last one,
16162 /// and on a lane holding nothing at all.
16163 #[test]
16164 fn gap_at_finds_the_hole_a_frame_sits_in() {
16165 let mut p = Project::single(FILE, 1);
16166 let v = p.add_lane(LaneKind::Video);
16167 // Empty lane: nothing before and nothing after -- not a gap, since
16168 // there is nothing to ripple toward.
16169 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
16170
16171 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
16172 // Before the only clip: the gap runs from the timeline's own head.
16173 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
16174 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
16175 // Inside the clip: not a gap.
16176 assert_eq!(p.gap_at(v, 5), None);
16177 assert_eq!(p.gap_at(v, 7), None);
16178 // Past the only clip: the open end of the lane, not a gap -- there is
16179 // nothing after it to slide back.
16180 assert_eq!(p.gap_at(v, 8), None);
16181 assert_eq!(p.gap_at(v, 100), None);
16182
16183 assert!(
16184 p.place(v, 12, clip(12, 0, 2, 0)),
16185 "a second clip at [12,14)"
16186 );
16187 // Between the two: the gap [8,12).
16188 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
16189 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
16190 assert_eq!(p.gap_at(v, 14), None, "still the open end");
16191
16192 assert!(
16193 p.place(v, 8, clip(8, 0, 4, 0)),
16194 "fills [8,12) exactly, meeting both neighbours"
16195 );
16196 assert_eq!(
16197 p.gap_at(v, 8),
16198 None,
16199 "adjacent clips leave no frame to name a gap"
16200 );
16201 assert_eq!(p.gap_at(v, 11), None);
16202 }
16203
16204 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
16205 /// menu named: the clip after the gap slides back on that lane, a clip on
16206 /// another lane at the very same frame range does not move, and the whole
16207 /// close is one press of undo.
16208 #[test]
16209 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
16210 let mut p = Project::single(FILE, 1);
16211 let v = p.add_lane(LaneKind::Video);
16212 let a = p.add_lane(LaneKind::Audio);
16213 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
16214 assert!(
16215 p.place(a, 0, clip(0, 0, 3, 0)),
16216 "A clip at [0,3) -- outside the video lane's gap and this scope"
16217 );
16218 let before = shape(&p);
16219 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
16220 assert_eq!((start, len), (0, 5));
16221 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
16222 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
16223 assert_eq!(
16224 p.lane(a)[0].start,
16225 0,
16226 "the untouched lane's clip did not move"
16227 );
16228 assert!(p.undo(), "one press undoes the whole close");
16229 assert_eq!(shape(&p), before, "back to exactly where it was");
16230 }
16231
16232 /// A clip carrying an explicit link id -- what a
16233 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
16234 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
16235 /// already builds inline.
16236 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
16237 Clip {
16238 speed_keys: Vec::new(),
16239 reversed: false,
16240 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
16241 angle: Default::default(),
16242 fade_in: 0,
16243 fade_out: 0,
16244 transition_out: 0,
16245 transition_kind: Default::default(),
16246 visualizer: 0,
16247 viz_paint: 0,
16248 gain_db: 0.0,
16249 gain_keys: Vec::new(),
16250 pan: 0,
16251 pitch: 0,
16252 transform_keys: Vec::new(),
16253 opacity_keys: Vec::new(),
16254 color_keys: Vec::new(),
16255 effects: Vec::new(),
16256 start,
16257 in_frame,
16258 out_frame,
16259 source: 0,
16260 link: Some(link),
16261 eq: None,
16262 color: None,
16263 transform: None,
16264 fit: FitPolicy::default(),
16265 speed: Speed::NORMAL,
16266 }
16267 }
16268
16269 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
16270 /// bordered by a linked take whose `A1` half is empty across the very
16271 /// same stretch widens the scope to both lanes, so the ripple carries the
16272 /// take rather than tearing it -- and one undo puts both halves back.
16273 #[test]
16274 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
16275 let sources = vec![Source::new(FILE, 0)];
16276 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16277 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16278 let mut p = Project::from_parts(
16279 sources,
16280 two(video, audio),
16281 Vec::new(),
16282 Vec::new(),
16283 Vec::new(),
16284 )
16285 .expect("valid parts");
16286 let before = shape(&p);
16287 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16288 assert_eq!(
16289 p.gap_at(Lane::A1, 3),
16290 Some((3, 2)),
16291 "the same stretch is empty on A1 too"
16292 );
16293
16294 let scope = p
16295 .gap_take_scope(Lane::V1, 3, 2)
16296 .expect("a matching gap on both halves widens the scope");
16297 assert_eq!(scope.len(), 2, "the take's other lane joins");
16298 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
16299
16300 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
16301 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
16302 assert_eq!(
16303 p.lane(Lane::A1)[1].start,
16304 3,
16305 "A1's far half rode along, in sync"
16306 );
16307 assert!(p.undo(), "one press undoes the whole close");
16308 assert_eq!(shape(&p), before, "back to exactly where it was");
16309 }
16310
16311 /// The real design question: a take whose gap is not the *same size* on
16312 /// both lanes cannot ripple by one number without pulling a lane's clip
16313 /// out from under the other's sync -- refused by name, with the frame
16314 /// naming which lane is out of step, rather than silently taking real
16315 /// media off the shorter side.
16316 #[test]
16317 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
16318 let sources = vec![Source::new(FILE, 0)];
16319 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16320 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
16321 // shorter than V1's [3,5) -- a legal offset-preserving group, and
16322 // still one take.
16323 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
16324 let p = Project::from_parts(
16325 sources,
16326 two(video, audio),
16327 Vec::new(),
16328 Vec::new(),
16329 Vec::new(),
16330 )
16331 .expect("valid parts");
16332 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16333 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
16334
16335 let err = p
16336 .gap_take_scope(Lane::V1, 3, 2)
16337 .expect_err("a mismatched gap cannot ripple by one number")
16338 .to_string();
16339 assert!(err.contains("A1"), "{err}");
16340 assert!(err.contains("out of sync"), "{err}");
16341 }
16342
16343 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
16344 /// there -- cannot close without cutting that audio out from under
16345 /// nothing asked to touch it: refused, not widened silently past.
16346 #[test]
16347 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
16348 let sources = vec![Source::new(FILE, 0)];
16349 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16350 // A1 plays through the whole span as one continuous clip, sharing
16351 // V1's first-half link: nothing empty at frame 3 there at all.
16352 let audio = vec![linked(0, 0, 9, 1)];
16353 let p = Project::from_parts(
16354 sources,
16355 two(video, audio),
16356 Vec::new(),
16357 Vec::new(),
16358 Vec::new(),
16359 )
16360 .expect("valid parts");
16361 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16362 assert_eq!(
16363 p.gap_at(Lane::A1, 3),
16364 None,
16365 "A1 plays through, no gap there"
16366 );
16367
16368 let err = p
16369 .gap_take_scope(Lane::V1, 3, 2)
16370 .expect_err("a solid partner cannot ripple with the gap")
16371 .to_string();
16372 assert!(err.contains("A1"), "{err}");
16373 assert!(err.contains("out of sync"), "{err}");
16374 }
16375
16376 /// The sweep is the single-gap close repeated on one lane, but measured once
16377 /// and applied from the right. The differing gap lengths here expose a
16378 /// front-to-back bug: the last clip would be cut against a stale frame after
16379 /// the first gap shifted it.
16380 #[test]
16381 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
16382 let mut p = Project::single(FILE, 1);
16383 let v = p.add_lane(LaneKind::Video);
16384 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
16385 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
16386 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
16387 let before = shape(&p);
16388
16389 assert_eq!(p.gap_count(v), 3);
16390 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
16391 assert_eq!(report.closed, 3);
16392 assert!(report.skipped.is_empty());
16393 assert_eq!(
16394 p.lane(v),
16395 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
16396 "all gaps closed without eating source frames"
16397 );
16398 assert!(p.undo(), "one undo for the whole sweep");
16399 assert_eq!(shape(&p), before);
16400 }
16401
16402 /// Empty, already-contiguous and tail-only lanes are not controls that do
16403 /// work. A single clip with a head gap does close, because there is a real
16404 /// placement to ripple back.
16405 #[test]
16406 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
16407 let mut p = Project::single(FILE, 9);
16408 let v = p.add_lane(LaneKind::Video);
16409 let history = p.history.len();
16410 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
16411 assert_eq!(
16412 report,
16413 GapSweep::default(),
16414 "an empty lane has no bounded gap"
16415 );
16416 assert_eq!(p.history.len(), history, "no undo step for a no-op");
16417
16418 let mut p = Project::single(FILE, 9);
16419 let v = p.add_lane(LaneKind::Video);
16420 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
16421 let before = shape(&p);
16422 let report = p
16423 .close_all_gaps_on_lane(v)
16424 .expect("single clip lane exists");
16425 assert_eq!(report.closed, 1, "the head gap closes");
16426 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
16427 assert!(p.undo());
16428 assert_eq!(shape(&p), before);
16429
16430 let mut p = Project::single(FILE, 9);
16431 let history = p.history.len();
16432 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
16433 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
16434 assert_eq!(p.history.len(), history);
16435
16436 let mut p = Project::single(FILE, 9);
16437 let v = p.add_lane(LaneKind::Video);
16438 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
16439 let history = p.history.len();
16440 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
16441 assert_eq!(
16442 report,
16443 GapSweep::default(),
16444 "the open-ended tail is not closed"
16445 );
16446 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
16447 assert_eq!(p.history.len(), history);
16448 }
16449
16450 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
16451 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
16452 /// while V1's [6,9) has only [6,8) empty on A1.
16453 #[test]
16454 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
16455 let sources = vec![Source::new(FILE, 0)];
16456 let video = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(9, 9, 11, 0)];
16457 let audio = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(8, 8, 11, 0)];
16458 let mut p = Project::from_parts(
16459 sources,
16460 two(video, audio),
16461 Vec::new(),
16462 Vec::new(),
16463 Vec::new(),
16464 )
16465 .expect("valid parts");
16466 let before = shape(&p);
16467
16468 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
16469 assert_eq!(report.closed, 1);
16470 assert_eq!(report.skipped.len(), 1);
16471 assert_eq!(report.skipped[0].start, 6);
16472 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
16473 assert!(
16474 report.skipped[0].reason.contains("out of sync"),
16475 "{report:?}"
16476 );
16477
16478 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
16479 assert_eq!(
16480 p.lane(Lane::A1)[1].start,
16481 2,
16482 "and its other half stayed in sync"
16483 );
16484 assert_eq!(
16485 p.lane(Lane::V1)[2].start,
16486 7,
16487 "the skipped later gap remains"
16488 );
16489 assert_eq!(
16490 p.lane(Lane::A1)[2].start,
16491 6,
16492 "A1's shorter gap remains shorter"
16493 );
16494 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
16495 assert!(p.undo(), "one undo restores every closed gap");
16496 assert_eq!(shape(&p), before);
16497 }
16498
16499 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
16500 /// their own caption storage: head gaps and gaps between cues count, an
16501 /// empty lane and the tail after the last cue do not.
16502 #[test]
16503 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
16504 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
16505 let s = p.add_lane(LaneKind::Subtitle);
16506 assert_eq!(
16507 p.gap_at(s, 0),
16508 None,
16509 "an empty subtitle lane has nothing to close"
16510 );
16511
16512 p.place_sub(s, 5, caption(0, 3))
16513 .expect("single cue at [5,8)");
16514 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
16515 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
16516 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
16517 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
16518
16519 p.place_sub(s, 12, caption(0, 2))
16520 .expect("second cue at [12,14)");
16521 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
16522 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
16523 assert_eq!(
16524 p.gap_at(s, 14),
16525 None,
16526 "tail after the last cue is still open-ended"
16527 );
16528 }
16529
16530 /// Closing a caption gap ripples the subtitle lane only. It is not a media
16531 /// take close, so the video and audio lanes keep their frame positions.
16532 #[test]
16533 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
16534 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
16535 let s = p.add_lane(LaneKind::Subtitle);
16536 p.place_sub(s, 5, caption(0, 3))
16537 .expect("single cue at [5,8)");
16538 let before_clips = shape(&p);
16539 let before_subs = p.sub_lane(s).to_vec();
16540
16541 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
16542 assert_eq!((start, len), (0, 5));
16543 p.cut_regions(&[(start, len)], &[s])
16544 .expect("caption lane gap closes");
16545
16546 assert_eq!(shape(&p), before_clips, "media lanes did not move");
16547 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
16548 assert!(p.undo(), "one undo restores the caption close");
16549 assert_eq!(shape(&p), before_clips);
16550 assert_eq!(p.sub_lane(s), before_subs);
16551 }
16552
16553 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
16554 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
16555 /// history entry for empty or already-contiguous lanes.
16556 #[test]
16557 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
16558 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
16559 let s = p.add_lane(LaneKind::Subtitle);
16560 let history = p.history.len();
16561 let report = p
16562 .close_all_gaps_on_lane(s)
16563 .expect("empty subtitle lane exists");
16564 assert_eq!(
16565 report,
16566 GapSweep::default(),
16567 "empty subtitle lane has no bounded gap"
16568 );
16569 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
16570
16571 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
16572 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
16573 p.place_sub(s, 14, caption(0, 1))
16574 .expect("middle gap [9,14), tail after 15");
16575 let before = p.sub_lane(s).to_vec();
16576
16577 assert_eq!(p.gap_count(s), 3);
16578 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
16579 assert_eq!(report.closed, 3);
16580 assert!(report.skipped.is_empty());
16581 assert_eq!(
16582 p.sub_lane(s),
16583 &[caption(0, 2), caption(2, 2), caption(4, 1)],
16584 "all bounded caption gaps closed without touching windows"
16585 );
16586 assert!(p.undo(), "one undo restores every caption gap");
16587 assert_eq!(p.sub_lane(s), before);
16588
16589 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
16590 let s = p.add_lane(LaneKind::Subtitle);
16591 p.place_sub(s, 0, caption(0, 3))
16592 .expect("contiguous at the head");
16593 let history = p.history.len();
16594 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
16595 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
16596 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
16597 assert_eq!(p.history.len(), history);
16598 }
16599
16600 #[test]
16601 fn ripple_delete_spans_partial_clips() {
16602 let mut p = three();
16603 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
16604 assert!(p.ripple_delete(2, 4));
16605 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
16606 assert_eq!(shape(&p)[1], shape(&p)[0]);
16607 assert_eq!(p.timeline_frames(), 5);
16608 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
16609 assert!(p.undo());
16610 assert_eq!(shape(&p), shape(&three()));
16611 // One that takes everything is a delete like any other: the timeline
16612 // empties, and the undo it cost brings it back whole.
16613 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
16614 assert_eq!(p.timeline_frames(), 0);
16615 assert!(
16616 !p.ripple_delete(0, 100),
16617 "and a delete with nothing left to take is not an undo step"
16618 );
16619 assert!(p.undo());
16620 assert_eq!(shape(&p), shape(&three()));
16621 }
16622
16623 /// A ripple trim closes the hole its trim leaves: the head cut from the middle clip goes, the
16624 /// clip keeps its start, and the last clip moves up by as much; an end edge moves what follows.
16625 #[test]
16626 fn ripple_trim_closes_the_hole_it_leaves() {
16627 let mut p = three();
16628 assert!(p.ripple_trim(Lane::V1, 1, Edge::Start, 4, &[9]));
16629 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 4, 5, 0), clip(4, 5, 9, 0)]);
16630 assert_eq!(shape(&p)[1], shape(&p)[0], "the linked audio moves with it");
16631 assert!(p.undo());
16632 assert_eq!(shape(&p), shape(&three()));
16633 assert!(p.ripple_trim(Lane::V1, 1, Edge::End, 4, &[9]));
16634 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(4, 5, 9, 0)]);
16635 }
16636
16637 /// Undo says the newest step's name and Redo the one it took back, and the names
16638 /// walk back and forth with the steps they belong to.
16639 #[test]
16640 fn labels_follow_undo_and_redo() {
16641 let mut p = Project::single(FILE, 270);
16642 let mark = p.step_mark();
16643 assert!(p.split(100));
16644 p.name_step(mark, "Split");
16645 let mark = p.step_mark();
16646 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16647 p.name_step(mark, "Volume");
16648 assert_eq!(p.undo_label(), Some("Volume"));
16649 assert_eq!(p.redo_label(), None);
16650
16651 assert!(p.undo());
16652 assert_eq!(p.undo_label(), Some("Split"));
16653 assert_eq!(p.redo_label(), Some("Volume"));
16654 assert!(p.undo());
16655 assert_eq!(p.undo_label(), None, "nothing left to take back");
16656 assert_eq!(p.redo_label(), Some("Split"));
16657
16658 assert!(p.redo());
16659 assert_eq!(p.redo_label(), Some("Volume"));
16660 assert!(p.redo());
16661 assert_eq!(p.redo_label(), None);
16662 assert_eq!(p.undo_label(), Some("Volume"));
16663 }
16664
16665 /// A name goes only on a step the named action pushed: an action that changed
16666 /// nothing, and one that pushed nothing at all, leave the step under them alone.
16667 #[test]
16668 fn a_no_op_takes_no_name_and_drops_none() {
16669 let mut p = Project::single(FILE, 270);
16670 assert!(p.split(100));
16671 let mark = p.step_mark();
16672 assert!(!p.set_lane_gain_db(Lane::A1, 0.0), "already at 0 dB");
16673 assert_eq!(p.undo_label(), None, "the unnamed split is still the newest step");
16674 p.name_step(mark, "Volume");
16675 assert_eq!(p.undo_label(), None, "the no-op pushed nothing to name");
16676
16677 let mark = p.step_mark();
16678 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16679 assert!(!p.set_lane_gain_db(Lane::A1, -3.0), "a repeat is a no-op");
16680 assert_eq!(p.undo_label(), None, "the real edit is unnamed so far");
16681 p.name_step(mark, "Volume");
16682 assert_eq!(p.undo_label(), Some("Volume"));
16683 assert_eq!(p.history_len(), 2);
16684 }
16685
16686 /// A step that names itself and then gets settled as a no-op carries its name away
16687 /// with it: the step under it keeps its own.
16688 #[test]
16689 fn a_settled_no_op_drops_its_name_with_its_step() {
16690 let mut p = Project::single(FILE, 270);
16691 let mark = p.step_mark();
16692 assert!(p.split(100));
16693 p.name_step(mark, "Split");
16694 let mark = p.step_mark();
16695 assert!(!p.set_lane_gain_db(Lane::A1, 0.0));
16696 assert_eq!(p.undo_label(), Some("Split"), "the no-op on top is not the step");
16697 p.name_step(mark, "Volume");
16698 assert_eq!(p.undo_label(), Some("Split"));
16699 assert_eq!(p.history_len(), 1);
16700 assert_eq!(p.redo_len(), 0);
16701 }
16702
16703 /// Names ride with their steps through the cap: the oldest step goes, every step kept
16704 /// still says what it did, and the one taken back stays named after a redo.
16705 #[test]
16706 fn labels_survive_the_cap_eviction() {
16707 let mut p = Project::single(FILE, 400);
16708 let frames = HISTORY_CAP as u32 + 5;
16709 for frame in 1..=frames {
16710 let mark = p.step_mark();
16711 assert!(p.split(frame));
16712 let name = if frame <= 3 { "Old" } else { "Split" };
16713 p.name_step(mark, name);
16714 }
16715 assert_eq!(p.history_len(), HISTORY_CAP);
16716 let mut taken = 0;
16717 while let Some(label) = p.undo_label().map(str::to_string) {
16718 assert_eq!(label, "Split", "a kept step keeps its own name");
16719 assert!(p.undo());
16720 taken += 1;
16721 }
16722 assert_eq!(taken, HISTORY_CAP);
16723 assert!(p.redo());
16724 assert_eq!(p.undo_label(), Some("Split"));
16725 assert_eq!(p.redo_label(), Some("Split"));
16726 }
16727
16728 /// A batch is one step and so one name: whatever the batch did, Undo names it once.
16729 #[test]
16730 fn a_batch_carries_one_label() {
16731 let mut p = Project::single(FILE, 270);
16732 let mark = p.step_mark();
16733 p.begin_batch();
16734 assert!(p.split(100));
16735 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16736 p.end_batch();
16737 p.name_step(mark, "Split, volume");
16738 assert_eq!(p.history_len(), 1, "the batch is one step");
16739 assert_eq!(p.undo_label(), Some("Split, volume"));
16740 assert!(p.undo());
16741 assert_eq!(p.redo_label(), Some("Split, volume"));
16742 }
16743
16744 #[test]
16745 fn undo_restores_exactly() {
16746 let mut p = three();
16747 let after_splits = shape(&p);
16748 assert!(p.delete(1));
16749 assert!(p.undo());
16750 assert_eq!(shape(&p), after_splits);
16751
16752 // walk all the way back through both splits, then run dry
16753 assert!(p.undo());
16754 assert_eq!(p.clips().len(), 2);
16755 assert!(p.undo());
16756 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
16757 assert!(!p.undo(), "empty history");
16758 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
16759 }
16760
16761 #[test]
16762 fn redo_restores_exactly() {
16763 let mut p = three();
16764 assert!(p.delete(1));
16765 let after_delete = p.parts();
16766 assert!(p.undo());
16767 assert!(p.redo());
16768 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
16769 assert!(!p.redo(), "empty redo stack");
16770 }
16771
16772 #[test]
16773 fn edit_after_undo_empties_redo() {
16774 let mut p = three();
16775 assert!(p.delete(1));
16776 assert!(p.undo());
16777 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
16778 assert!(p.split(1), "a fresh edit");
16779 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
16780 assert!(!p.redo(), "so redo has nothing left");
16781 }
16782
16783 #[test]
16784 fn redo_on_empty_stack_is_false() {
16785 let mut p = three();
16786 assert!(!p.redo(), "nothing has been undone yet");
16787 }
16788
16789 #[test]
16790 fn take_and_restore_redo_round_trips() {
16791 let mut p = three();
16792 assert!(p.delete(1));
16793 let after_delete = p.parts();
16794 assert!(p.undo());
16795 let cp = p.take_redo();
16796 assert_eq!(p.redo_len(), 0, "taken out with no step");
16797 assert!(p.split(1), "a trial edit, which clears what is left");
16798 p.restore_redo(cp);
16799 assert_eq!(p.redo_len(), 1, "the stack the trial found is back");
16800 assert!(p.redo());
16801 assert_eq!(p.parts(), after_delete, "and it still redoes to the same state");
16802 }
16803
16804 #[test]
16805 fn held_history_evicts_nothing_until_released() {
16806 let mut p = Project::single(FILE, 400);
16807 for frame in 1..=HISTORY_CAP as u32 {
16808 assert!(p.split(frame));
16809 }
16810 p.hold_history(true);
16811 for frame in 101..=103 {
16812 assert!(p.split(frame));
16813 }
16814 assert_eq!(p.history.len(), HISTORY_CAP + 3, "a held trial evicts nothing");
16815 for _ in 0..3 {
16816 assert!(p.undo());
16817 }
16818 assert_eq!(p.history.len(), HISTORY_CAP, "the trial rolled back, the cap is still the same");
16819 p.hold_history(false);
16820 assert_eq!(p.history.len(), HISTORY_CAP);
16821 for frame in 101..=103 {
16822 assert!(p.split(frame));
16823 }
16824 p.hold_history(true);
16825 for frame in 110..=112 {
16826 assert!(p.split(frame));
16827 }
16828 assert_eq!(p.history.len(), HISTORY_CAP + 3);
16829 p.hold_history(false);
16830 assert_eq!(p.history.len(), HISTORY_CAP, "releasing trims back to the cap");
16831 }
16832
16833 /// Past the cap the *oldest* step goes, so a long session undoes exactly
16834 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
16835 #[test]
16836 fn history_stops_at_the_cap() {
16837 let mut p = Project::single(FILE, 400);
16838 for frame in 1..=150 {
16839 assert!(p.split(frame), "split {frame} is an edit");
16840 }
16841 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
16842 for step in 0..HISTORY_CAP {
16843 assert!(p.undo(), "undo {step} is inside the cap");
16844 }
16845 assert!(!p.undo(), "and the 101st has nothing left to take");
16846 // 100 undos off 150 splits is the timeline after the 50th: the older
16847 // steps were dropped, not the newer ones.
16848 assert_eq!(p.clips().len(), 51);
16849 }
16850
16851 /// The push count keeps rising past the cap, where `history_len` stops, so a
16852 /// caller can tell how many snapshots a batch pushed even at the cap.
16853 #[test]
16854 fn undo_pushes_counter_keeps_counting_past_the_cap() {
16855 let mut p = Project::single(FILE, 400);
16856 let start = p.history_pushes();
16857 for frame in 1..=HISTORY_CAP as u32 + 5 {
16858 assert!(p.split(frame));
16859 }
16860 assert_eq!(p.history.len(), HISTORY_CAP, "the length has saturated");
16861 assert_eq!(p.history_pushes() - start, HISTORY_CAP as u64 + 5);
16862 assert!(p.undo());
16863 assert_eq!(
16864 p.history_pushes() - start,
16865 HISTORY_CAP as u64 + 5,
16866 "an undo pushes nothing"
16867 );
16868 }
16869
16870 /// Undo/redo by hand across a split must never merge two takes into one
16871 /// group by reusing an id.
16872 #[test]
16873 fn group_ids_are_never_reused() {
16874 let mut p = Project::single(FILE, 9);
16875 assert!(p.split(3));
16876 let first = p.clips()[1].link;
16877 assert!(p.undo());
16878 assert!(p.split(5));
16879 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
16880 }
16881
16882 #[test]
16883 fn segments_from_reads_the_audio_lane() {
16884 let p = three();
16885 // mid-clip: partial first segment, whole clips after it
16886 assert_eq!(
16887 p.segments_from(4, FPS),
16888 vec![
16889 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
16890 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
16891 ]
16892 );
16893 // on a boundary: nothing partial
16894 assert_eq!(
16895 p.segments_from(3, FPS),
16896 vec![
16897 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
16898 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
16899 ]
16900 );
16901 // from the top: one entry per clip
16902 assert_eq!(p.segments_from(0, FPS).len(), 3);
16903 // last clip only
16904 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
16905 // past the end / unusable fps
16906 assert!(p.segments_from(9, FPS).is_empty());
16907 assert!(p.segments_from(0, 0.0).is_empty());
16908 assert!(p.segments_from(0, f64::NAN).is_empty());
16909 }
16910
16911 #[test]
16912 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
16913 let mut p = three();
16914 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
16915 assert_eq!(
16916 p.segments_from(0, FPS),
16917 vec![
16918 (Some(0), 0.0, 3.0 / 30.0),
16919 (None, 0.0, 2.0 / 30.0),
16920 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
16921 ]
16922 );
16923 // The list still covers exactly the timeline: that is what stops the
16924 // master clock stalling at the hole.
16925 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
16926 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
16927 // Starting inside the gap trims the silence, not the clip after it.
16928 assert_eq!(
16929 p.segments_from(4, FPS),
16930 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
16931 );
16932 // ...and a lane that is nothing but gap is a run of silence.
16933 assert!(p.lift(Lane::A1, 0));
16934 assert!(p.lift(Lane::A1, 0));
16935 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
16936 }
16937
16938 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
16939 /// of source 0 then [0,4) of source 1.
16940 fn two_sources() -> Project {
16941 let mut p = three();
16942 let s = p.import(FILE2, 0);
16943 assert_eq!(s, 1);
16944 assert!(p.append_clip(s, 4));
16945 p
16946 }
16947
16948 #[test]
16949 fn import_dedups_and_appends() {
16950 let mut p = Project::single(FILE, 9);
16951 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
16952 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
16953 assert_eq!(p.import(FILE2, 0), 1);
16954 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
16955 // ...but the same file on another audio stream is another source: it is
16956 // what a clip names, and a clip plays exactly one stream.
16957 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
16958 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
16959 assert_eq!(p.sources()[2].audio_stream, 1);
16960 assert!(p.append_clip(2, 4), "a stream entry is placeable");
16961 assert!(p.undo());
16962 assert_eq!(p.sources().len(), 3);
16963 assert!(!p.append_clip(3, 5), "unknown source index");
16964 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
16965
16966 // Two spellings of one real file are one source: this is the case the
16967 // raw-path comparison above would get wrong.
16968 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
16969 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
16970 let mut p = Project::single(here, 9);
16971 assert_eq!(p.import(detour, 0), 0);
16972 assert_eq!(p.sources().len(), 1);
16973 }
16974
16975 #[test]
16976 fn append_clip_is_one_undo_step() {
16977 let mut p = two_sources();
16978 assert_eq!(p.timeline_frames(), 13);
16979 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
16980 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
16981 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
16982 assert!(p.undo());
16983 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
16984 assert_eq!(
16985 p.sources().len(),
16986 2,
16987 "the orphan source entry stays -- indexes are forever"
16988 );
16989 // ...and it is still usable, so a redo-by-hand costs no reimport.
16990 assert!(p.append_clip(1, 0));
16991 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
16992 }
16993
16994 #[test]
16995 fn edits_carry_the_source_along() {
16996 let mut p = two_sources();
16997 // A split inside the second source splits into two source-1 clips.
16998 assert!(p.split(11));
16999 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
17000 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
17001
17002 // A source-1 clip pasted into source-0 territory keeps its file, and so
17003 // does the source-0 half that got split off around it.
17004 let copied = p.clips()[4].clone();
17005 assert!(p.paste(1, copied));
17006 assert_eq!(p.clips()[1].source, 1);
17007 assert_eq!(p.clips()[1].in_frame, 2);
17008 assert_eq!(p.clips()[2].source, 0);
17009 assert!(p.undo());
17010 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
17011 }
17012
17013 #[test]
17014 fn segments_from_names_the_source() {
17015 let p = two_sources();
17016 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
17017 assert_eq!(
17018 p.segments_from(4, FPS),
17019 vec![
17020 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
17021 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
17022 (Some(1), 0.0, 4.0 / 30.0),
17023 ]
17024 );
17025 // Mid-clip in source 1: only that source is left.
17026 assert_eq!(
17027 p.segments_from(10, FPS),
17028 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
17029 );
17030 assert!(p.segments_from(13, FPS).is_empty());
17031 // Segments still cover exactly the timeline across the join.
17032 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
17033 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
17034 }
17035
17036 #[test]
17037 fn segments_follow_deletes_and_fps() {
17038 let mut p = three();
17039 assert!(p.delete(0));
17040 // source seconds, not timeline: deleting the head does not shift them
17041 let segs = p.segments_from(0, 25.0);
17042 assert_eq!(
17043 segs,
17044 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
17045 );
17046 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
17047 assert!(
17048 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
17049 "segments must cover exactly the timeline: {played}"
17050 );
17051 }
17052
17053 #[test]
17054 fn every_source_is_saved_in_session_order_and_the_clips_keep_theirs() {
17055 // Import a second file, undo it: source 1 is now an orphan. It is kept
17056 // anyway -- an import is not an undo step, so the library entry stays
17057 // at the index a reload will look for it at.
17058 let mut p = two_sources();
17059 assert!(p.undo());
17060 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17061 assert_eq!(
17062 sources,
17063 vec![Source::new(FILE, 0), Source::new(FILE2, 0)],
17064 "the orphan is kept, in session order"
17065 );
17066 assert!(eq.is_empty(), "and a project with no equalizer writes none");
17067 assert!(color.is_empty(), "nor a colour it never graded with");
17068 assert_eq!(
17069 lanes,
17070 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
17071 "the clips are untouched"
17072 );
17073
17074 // Three sources where only the middle one is unused: all three are
17075 // saved, in order, and the clip keeps the index it was given -- 2 here,
17076 // not renumbered down to 1. (The clip from `single` is still source 0.)
17077 let mut p = Project::single(FILE, 9);
17078 assert_eq!(p.import(FILE2, 0), 1);
17079 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
17080 assert!(p.append_clip(2, 4));
17081 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17082 assert_eq!(
17083 sources,
17084 vec![
17085 Source::new(FILE, 0),
17086 Source::new(FILE2, 0),
17087 Source::new("/nonexistent/c.mp4", 0)
17088 ]
17089 );
17090 assert_eq!(
17091 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
17092 [0, 2]
17093 );
17094 // ...and what comes out is loadable, with the same timeline.
17095 let reloaded =
17096 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
17097 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
17098 assert_eq!(reloaded.sources().len(), 3);
17099 }
17100
17101 /// Taking a file out of the library: refused by name -- lanes and counts --
17102 /// while a clip still plays from it, and once nothing does, the entry goes
17103 /// and every clip that indexed past it is renumbered onto the short list.
17104 /// A project rebuilt from parts keeps each source's bin and star (the loader's own door).
17105 #[test]
17106 fn from_parts_keeps_a_sources_bin_and_star() {
17107 let mut one = Source::new(FILE, 0);
17108 one.fav = true;
17109 one.bin = 7;
17110 let lanes = vec![(LaneKind::Video, vec![clip(0, 0, 10, 0)]), (LaneKind::Audio, vec![clip(0, 0, 10, 0)])];
17111 let p = Project::from_parts(vec![one], lanes, vec![], vec![], Vec::new()).expect("valid parts");
17112 assert!(p.sources()[0].fav);
17113 assert_eq!(p.sources()[0].bin, 7);
17114 }
17115
17116 #[test]
17117 fn bins_and_favourites_follow_the_usual_edit_rules() {
17118 let mut p = two_sources();
17119 let a = p.create_bin(" Interviews ", 0).expect("makes a bin");
17120 assert_eq!(p.bins()[0].name, "Interviews");
17121 assert!(p.create_bin("interviews", 0).is_err(), "no twin at one place");
17122 let b = p.create_bin("Day 1", a).expect("one level of nesting");
17123 assert!(p.create_bin("deeper", b).is_err(), "no third level");
17124 assert!(p.create_bin(" ", 0).is_err() && p.create_bin("a\nb", 0).is_err() && p.create_bin("x", 99).is_err());
17125 assert_eq!(p.move_to_bin(&[0, 1, 1], b), Ok(2));
17126 assert_eq!(p.move_to_bin(&[0], b), Ok(0), "no change, no history");
17127 assert!(p.move_to_bin(&[7], b).is_err() && p.move_to_bin(&[0], 42).is_err());
17128 assert_eq!(p.set_favourite(&[1], true), Ok(1));
17129 assert_eq!(p.set_favourite(&[1], true), Ok(0));
17130 assert!(p.sources()[1].fav && p.sources()[1].bin == b);
17131 assert_eq!(p.rename_bin(b, "Day one"), Ok(true));
17132 assert_eq!(p.rename_bin(b, "Day one"), Ok(false));
17133 // Undo walks back one step at a time: rename, star, move, then the bins themselves.
17134 assert!(p.undo() && p.bins()[1].name == "Day 1");
17135 assert!(p.undo() && !p.sources()[1].fav);
17136 assert!(p.undo() && p.sources()[0].bin == 0);
17137 assert!(p.redo() && p.sources()[0].bin == b);
17138 // Removing the outer bin keeps what it held: sources go up, inner bins to the top.
17139 assert_eq!(p.remove_bin(a), Ok(0));
17140 assert_eq!(p.bins().len(), 1);
17141 assert_eq!(p.bins()[0].parent, 0);
17142 assert_eq!(p.remove_bin(b), Ok(2));
17143 assert!(p.sources().iter().all(|s| s.bin == 0));
17144 assert!(p.undo() && p.sources()[0].bin == b && p.bins().len() == 1);
17145 assert!(p.undo() && p.bins().len() == 2 && p.bins()[1].parent == a);
17146 // A source's identity is its file and stream, not its star.
17147 assert_eq!(p.sources()[0], Source::new(&p.sources()[0].path, 0));
17148 }
17149
17150 #[test]
17151 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
17152 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
17153 // plus a second stream of FILE as source 2 with a take of its own.
17154 let mut p = two_sources();
17155 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
17156 assert!(p.append_clip(2, 4));
17157
17158 let refusal = p
17159 .remove_source(1)
17160 .expect_err("a source with clips on it cannot go")
17161 .to_string();
17162 assert!(refusal.contains(FILE2), "names the file: {refusal}");
17163 assert!(
17164 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
17165 "names the lanes holding it: {refusal}"
17166 );
17167 assert!(refusal.contains("still plays"), "{refusal}");
17168 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
17169 assert_eq!(shape(&p)[0][3].source, 1);
17170
17171 // Delete FILE2's take -- the whole span, on every lane -- and the entry
17172 // is free to go. Source 2's clips become source 1's.
17173 assert!(p.delete_in(Lane::V1, 3));
17174 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
17175 p.remove_source(1).expect("nothing plays FILE2 any more");
17176 assert_eq!(
17177 p.sources(),
17178 [Source::new(FILE, 0), Source::new(FILE, 1)],
17179 "the middle entry is gone"
17180 );
17181 assert_eq!(
17182 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
17183 [0, 0, 0, 1],
17184 "the clips past it renumbered"
17185 );
17186 assert_eq!(
17187 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
17188 [0, 0, 0, 1],
17189 "on every lane"
17190 );
17191 // What is left is a project that still loads, which is the whole point
17192 // of renumbering rather than leaving a hole.
17193 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17194 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
17195 }
17196
17197 /// The two edges of a removal: it retires the undo stack (the corner-cut on
17198 /// [`Project::remove_source`]), and the last entry goes like any other
17199 /// once nothing plays it -- a project may name no file at all.
17200 #[test]
17201 fn relink_is_one_undo_step_and_undo_puts_the_old_path_back() {
17202 let mut p = two_sources();
17203 let old = p.sources()[1].path.clone();
17204 let new = Source::new(FILE, 0).path;
17205 let depth = p.history_len();
17206 p.relink_source(1, Path::new(FILE)).expect("relinks");
17207 assert_eq!(p.sources()[1].path, new);
17208 assert_eq!(p.history_len(), depth + 1, "one step");
17209 assert!(p.undo());
17210 assert_eq!(p.sources()[1].path, old, "undo points back at the old file");
17211 assert!(p.redo());
17212 assert_eq!(p.sources()[1].path, new, "redo re-points it");
17213 p.relink_source(1, Path::new(FILE)).expect("the path it has");
17214 assert_eq!(p.history_len(), depth + 1, "a relink to the same path is no step");
17215 assert!(p.relink_source(9, Path::new(FILE)).is_err(), "no source 9");
17216 }
17217
17218 #[test]
17219 fn undo_keeps_a_source_imported_after_the_step() {
17220 let mut p = three();
17221 assert_eq!(p.import(FILE2, 0), 1);
17222 assert!(p.undo(), "the last split");
17223 assert_eq!(p.sources().len(), 2, "the import outlives the undo, as an import does");
17224 assert_eq!(p.sources()[1].path, Source::new(FILE2, 0).path);
17225 assert!(p.redo());
17226 assert_eq!(p.sources().len(), 2);
17227 }
17228
17229 #[test]
17230 fn adopt_as_step_takes_the_other_timeline_and_undo_gives_this_one_back() {
17231 let geometry = |p: &Project| -> Vec<Vec<(u32, u32, u32, usize)>> {
17232 p.lanes()
17233 .into_iter()
17234 .map(|l| p.lane(l).iter().map(|c| (c.start, c.in_frame, c.out_frame, c.source)).collect())
17235 .collect()
17236 };
17237 let mut p = three();
17238 assert!(p.set_eq(Lane::A1, 0, Some(band_at(7))), "this project's own table entry");
17239 let mut other = two_sources();
17240 assert!(other.set_eq(Lane::A1, 0, Some(band_at(2))));
17241 let (want, want_eq) = (geometry(&other), other.eq_of(Lane::A1, 0).cloned());
17242 let saved = geometry(&p);
17243 let depth = p.history_len();
17244 assert!(p.adopt_as_step(&other));
17245 assert_eq!(p.history_len(), depth + 1, "one step");
17246 assert_eq!(geometry(&p), want, "the other timeline");
17247 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), want_eq, "its effects read from the appended table");
17248 assert!(p.undo());
17249 assert_eq!(geometry(&p), saved);
17250 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), Some(band_at(7)), "and this project's own table is still there");
17251 assert!(p.redo());
17252 assert_eq!(geometry(&p), want);
17253 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), want_eq);
17254 assert_eq!(p.sources()[1].path, other.sources()[1].path, "the other sources come with it");
17255 }
17256
17257 /// A recovery takes the autosave's markers with its timeline, and undo gives back the
17258 /// markers this project had: the marker list is part of what a step restores.
17259 #[test]
17260 fn adopt_as_step_carries_the_markers_of_the_other_timeline() {
17261 let marker = |frame: u32, name: &str| Marker {
17262 frame,
17263 length: 0,
17264 name: name.into(),
17265 note: String::new(),
17266 color: MarkerColor::Red,
17267 };
17268 let mut p = three();
17269 assert!(p.add_marker(marker(4, "mine")).is_ok());
17270 let mut other = two_sources();
17271 assert!(other.add_marker(marker(9, "theirs")).is_ok());
17272 assert!(p.adopt_as_step(&other));
17273 let names: Vec<&str> = p.markers().iter().map(|m| m.name.as_str()).collect();
17274 assert_eq!(names, ["theirs"], "the other timeline's markers");
17275 assert!(p.undo());
17276 let names: Vec<&str> = p.markers().iter().map(|m| m.name.as_str()).collect();
17277 assert_eq!(names, ["mine"], "undo gives this project's markers back");
17278 }
17279
17280 #[test]
17281 fn revision_walks_back_with_undo_and_never_repeats() {
17282 let mut p = three();
17283 let saved = p.revision();
17284 assert!(p.delete_in(Lane::V1, 2));
17285 let edited = p.revision();
17286 assert_ne!(edited, saved, "an edit moves the timeline off the saved state");
17287 assert!(p.undo());
17288 assert_eq!(p.revision(), saved, "undo back to the saved timeline gives its id back");
17289 assert!(p.redo());
17290 assert_eq!(p.revision(), edited, "redo walks forward to the same id");
17291 // A new edit after an undo is a state of its own: it must not read as the saved one.
17292 assert!(p.undo());
17293 assert!(p.delete_in(Lane::V1, 0));
17294 assert_ne!(p.revision(), saved, "a branch off the saved timeline is not the saved one");
17295 assert_ne!(p.revision(), edited);
17296 assert!(!p.redo(), "the branch cleared the redo stack");
17297 assert_eq!(p.revision(), p.revision(), "reading is not an edit");
17298 }
17299
17300 #[test]
17301 fn revision_moves_once_per_batch_step_and_undo_takes_the_whole_batch_back() {
17302 let mut p = three();
17303 let saved = p.revision();
17304 p.begin_batch();
17305 assert!(p.delete_in(Lane::V1, 2));
17306 let first = p.revision();
17307 assert!(p.delete_in(Lane::V1, 1));
17308 assert_ne!(p.revision(), first, "each edit in a batch is a new state");
17309 p.end_batch();
17310 assert!(p.undo());
17311 assert_eq!(p.revision(), saved, "one undo takes the whole batch back to the saved id");
17312 }
17313
17314 #[test]
17315 fn revision_of_a_recovery_step_is_undone_back_to_the_timeline_it_replaced() {
17316 let mut current = three();
17317 assert!(current.delete_in(Lane::V1, 2));
17318 let edited = current.revision();
17319 let other = two_sources();
17320 assert!(current.adopt_as_step(&other));
17321 assert_ne!(current.revision(), edited, "the other timeline is a new state");
17322 assert!(current.undo());
17323 assert_eq!(current.revision(), edited, "undo gives back the timeline it replaced, by its id");
17324 }
17325
17326 #[test]
17327 fn remove_source_retires_undo_and_empties_the_library() {
17328 let mut p = two_sources();
17329 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
17330 assert!(!p.history.is_empty(), "there is something to undo");
17331 p.remove_source(1).expect("nothing plays FILE2");
17332 assert!(
17333 p.history.is_empty(),
17334 "a snapshot naming the removed source must not survive it"
17335 );
17336 assert!(!p.undo(), "and so there is nothing left to undo");
17337
17338 // The last file standing is held to the one rule every row is -- what
17339 // plays cannot go -- and to no other.
17340 assert_eq!(p.sources().len(), 1);
17341 let refusal = p
17342 .remove_source(0)
17343 .expect_err("its clips are still on the lanes")
17344 .to_string();
17345 assert!(refusal.contains("still plays"), "{refusal}");
17346 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
17347 while p.delete_in(Lane::V1, 0) {}
17348 p.remove_source(0)
17349 .expect("the last row goes like any other");
17350 assert!(
17351 p.sources().is_empty(),
17352 "a project may name no file at all: an empty library over an empty timeline"
17353 );
17354 assert_eq!(p.timeline_frames(), 0);
17355 assert!(
17356 p.remove_source(0).is_err(),
17357 "and an index that is not there is refused, not panicked on"
17358 );
17359 }
17360
17361 /// A clip's equalizer is the clip's: it survives every edit that copies a
17362 /// placement, and it comes back with an undo.
17363 #[test]
17364 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
17365 let mut p = three();
17366 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
17367 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
17368 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17369 assert!(
17370 p.eq_of(Lane::V1, 0).is_none(),
17371 "one clip, not the lane above"
17372 );
17373
17374 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
17375 assert!(p.split(1));
17376 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17377 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
17378 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
17379
17380 // A clipboard copy carries it -- onto another lane, at that.
17381 let copied = p.lane(Lane::A1)[1].clone();
17382 assert!(p.place(Lane::V1, 20, copied));
17383 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
17384 assert!(p.undo());
17385 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
17386
17387 // ...and a change to one is one undo step, in both directions.
17388 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
17389 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
17390 assert!(p.undo());
17391 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17392 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
17393 assert!(p.eq_of(Lane::A1, 0).is_none());
17394 assert!(p.undo());
17395 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17396
17397 // Two refusals, neither of which costs an undo step.
17398 let mut nan = band_at(1);
17399 nan.bands[0].q = f32::INFINITY;
17400 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
17401 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
17402 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17403 assert!(p.undo());
17404 assert_eq!(
17405 p.lane(Lane::A1).len(),
17406 3,
17407 "one step back is before the split"
17408 );
17409 assert!(p.undo());
17410 assert!(
17411 p.eq_of(Lane::A1, 0).is_none(),
17412 "and the next is before the setting: the refusals pushed none"
17413 );
17414 }
17415
17416 /// The table is append-only within a session, exactly as the sources are, so
17417 /// an undone setting is still in it -- and a save is where it goes.
17418 #[test]
17419 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
17420 let mut p = three();
17421 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
17422 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
17423 assert!(p.undo(), "back to the first setting");
17424 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
17425
17426 let (_, lanes, eq, _, _) = p.without_orphan_sources();
17427 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
17428 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
17429 assert_eq!(lanes[0].1[1].eq, None);
17430
17431 // One curve on three clips is one entry: settings that are equal share.
17432 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
17433 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
17434 let (_, lanes, eq, _, _) = p.without_orphan_sources();
17435 assert_eq!(eq.len(), 1, "equal settings share their entry");
17436 assert_eq!(lanes[1].1[2].eq, Some(0));
17437 reloads(&p, "an equalizer that outlived an undo");
17438 }
17439
17440 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
17441 /// grade is the clip's, through every edit that copies a placement.
17442 #[test]
17443 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
17444 let mut p = three();
17445 assert!(
17446 p.color_of(Lane::V1, 0).is_none(),
17447 "a fresh clip is ungraded"
17448 );
17449 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
17450 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17451 assert!(
17452 p.color_of(Lane::A1, 0).is_none(),
17453 "one clip, not the lane below"
17454 );
17455 assert!(
17456 p.eq_of(Lane::V1, 0).is_none(),
17457 "and a grade is not an equalizer"
17458 );
17459
17460 // Cutting a graded clip must not grade half of it: both halves inherit.
17461 assert!(p.split(1));
17462 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17463 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
17464 assert!(
17465 p.color_of(Lane::V1, 2).is_none(),
17466 "the clip after it is ungraded"
17467 );
17468
17469 // A clipboard copy carries it -- onto another lane, at that.
17470 let copied = p.lane(Lane::V1)[1].clone();
17471 assert!(p.place(Lane::A1, 20, copied));
17472 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
17473 assert!(p.undo());
17474 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
17475
17476 // ...and a change to one is one undo step, in both directions.
17477 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
17478 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
17479 assert!(p.undo());
17480 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17481 assert!(
17482 p.set_color(Lane::V1, 0, None),
17483 "and taking it off is an edit"
17484 );
17485 assert!(p.color_of(Lane::V1, 0).is_none());
17486 assert!(p.undo());
17487 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17488
17489 // Two refusals, neither of which costs an undo step.
17490 let nan = ColorParams {
17491 contrast: f32::NAN,
17492 ..grade_at(1)
17493 };
17494 assert!(
17495 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
17496 "no clip there"
17497 );
17498 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
17499 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17500 assert!(p.undo());
17501 assert_eq!(
17502 p.lane(Lane::V1).len(),
17503 3,
17504 "one step back is before the split"
17505 );
17506 assert!(p.undo());
17507 assert!(
17508 p.color_of(Lane::V1, 0).is_none(),
17509 "and the next is before the grade: the refusals pushed none"
17510 );
17511 }
17512
17513 /// A slider drag is one gesture: the press snapshots, every sample after it
17514 /// only regrades, and the single undo lands on what the clip was *before*
17515 /// the hand touched it -- not one step back down the drag.
17516 #[test]
17517 fn a_whole_colour_drag_undoes_in_one_step() {
17518 let mut p = three();
17519 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
17520 for n in 2..=8 {
17521 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
17522 }
17523 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
17524 assert!(p.undo());
17525 assert!(
17526 p.color_of(Lane::V1, 0).is_none(),
17527 "one undo is the whole gesture, back to ungraded"
17528 );
17529
17530 // The live write refuses what the snapshotting one refuses, and a
17531 // refusal still costs no history either way.
17532 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
17533 assert!(!p.set_color_live(
17534 Lane::V1,
17535 0,
17536 Some(ColorParams {
17537 contrast: f32::NAN,
17538 ..grade_at(1)
17539 })
17540 ));
17541 assert!(p.undo());
17542 assert_eq!(
17543 p.lane(Lane::V1).len(),
17544 2,
17545 "the next step back is the split before the drag: no sample pushed one"
17546 );
17547 }
17548
17549 /// A drag across the colour wheel is one gesture -- the look's twin of
17550 /// [`a_whole_colour_drag_undoes_in_one_step`]: the press snapshots, every
17551 /// sample after it only repaints, and the single undo lands on the look
17552 /// the clip had *before* the hand touched it. The committing setter is
17553 /// still exactly one step, refusals included.
17554 /// A LUT is relinked like media: every clip naming the old path moves to the
17555 /// new one in one undo step, a missing file is a named problem rather than an
17556 /// error, and keys leave the look alone.
17557 #[test]
17558 fn a_lut_relinks_in_one_step_and_a_missing_one_is_named() {
17559 let dir = std::env::temp_dir().join(format!("edith-relink-lut-{}", std::process::id()));
17560 std::fs::create_dir_all(&dir).unwrap();
17561 let good = dir.join("good.cube");
17562 std::fs::write(&good, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap();
17563 let gone = dir.join("gone.cube");
17564 let mut p = three();
17565 let with = |path: &Path| ColorParams {
17566 look: crate::color::Look { lut: Some(crate::cube::LutRef::open(path)), ..Default::default() },
17567 ..Default::default()
17568 };
17569 assert!(p.set_color(Lane::V1, 0, Some(with(&gone))));
17570 assert!(p.set_color(Lane::V1, 1, Some(with(&gone))));
17571 let problems = p.lut_problems();
17572 assert_eq!(problems.len(), 1, "one file, named once");
17573 assert!(problems[0].0 == gone && problems[0].1.contains("cannot read"));
17574 assert_eq!(p.relink_lut(&dir.join("other.cube"), &good), 0, "nothing names it");
17575 assert_eq!(p.relink_lut(&gone, &good), 2);
17576 assert!(p.lut_problems().is_empty());
17577 assert_eq!(p.color_of(Lane::V1, 1).and_then(|c| c.look.lut).map(|r| r.path()), Some(good.clone()));
17578 assert!(p.undo());
17579 assert_eq!(p.lut_problems().len(), 1, "one undo puts both back");
17580 std::fs::remove_dir_all(&dir).ok();
17581 }
17582
17583 #[test]
17584 fn a_whole_look_drag_undoes_in_one_step() {
17585 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
17586 let mut p = three();
17587 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "the press");
17588 for hue in 2..=8u8 {
17589 assert!(p.set_viz_paint_live(Lane::V1, 0, look(hue)), "a sample");
17590 }
17591 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(8));
17592 assert!(p.undo());
17593 assert_eq!(
17594 p.lane(Lane::V1)[0].viz_paint,
17595 0,
17596 "one undo is the whole gesture, back to the default look"
17597 );
17598
17599 // The live write refuses an index that is not there -- and a refusal
17600 // costs no history -- while one committing write is one step back.
17601 assert!(!p.set_viz_paint_live(Lane::V1, 99, look(1)));
17602 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "a click, not a drag");
17603 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(1));
17604 assert!(p.undo());
17605 assert_eq!(
17606 p.lane(Lane::V1)[0].viz_paint,
17607 0,
17608 "the committing setter is one undo step, no more"
17609 );
17610 }
17611
17612 /// The colour table is append-only within a session, exactly as the eq one
17613 /// is -- and a save is where an undone grade goes.
17614 #[test]
17615 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
17616 let mut p = three();
17617 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
17618 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
17619 assert!(p.undo(), "back to the first grade");
17620 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
17621
17622 let (_, lanes, _, color, _) = p.without_orphan_sources();
17623 assert_eq!(
17624 color,
17625 vec![grade_at(1)],
17626 "what nothing plays is not written"
17627 );
17628 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
17629 assert_eq!(lanes[0].1[1].color, None);
17630
17631 // One grade on three clips is one entry: settings that are equal share.
17632 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
17633 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
17634 let (_, lanes, _, color, _) = p.without_orphan_sources();
17635 assert_eq!(color.len(), 1, "equal grades share their entry");
17636 assert_eq!(lanes[1].1[2].color, Some(0));
17637 reloads(&p, "a colour that outlived an undo");
17638
17639 // An equalizer and a grade on one clip are two independent tables.
17640 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
17641 let (_, lanes, eq, color, _) = p.without_orphan_sources();
17642 assert_eq!((eq.len(), color.len()), (1, 1));
17643 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
17644 }
17645
17646 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
17647 /// placement is the clip's, through every edit that copies one.
17648 #[test]
17649 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
17650 let mut p = three();
17651 assert!(
17652 p.transform_of(Lane::V1, 0).is_none(),
17653 "a fresh clip is untransformed"
17654 );
17655 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
17656 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17657 assert!(
17658 p.transform_of(Lane::A1, 0).is_none(),
17659 "one clip, not the lane below"
17660 );
17661 assert!(
17662 p.color_of(Lane::V1, 0).is_none(),
17663 "and a placement is not a grade"
17664 );
17665
17666 // Cutting a transformed clip must not transform half of it: both
17667 // halves inherit.
17668 assert!(p.split(1));
17669 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17670 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
17671 assert!(
17672 p.transform_of(Lane::V1, 2).is_none(),
17673 "the clip after it is untransformed"
17674 );
17675
17676 // A clipboard copy carries it -- onto another lane, at that.
17677 let copied = p.lane(Lane::V1)[1].clone();
17678 assert!(p.place(Lane::A1, 20, copied));
17679 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
17680 assert!(p.undo());
17681 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
17682
17683 // ...and a change to one is one undo step, in both directions.
17684 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
17685 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
17686 assert!(p.undo());
17687 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17688 assert!(
17689 p.set_transform(Lane::V1, 0, None),
17690 "and taking it off is an edit"
17691 );
17692 assert!(p.transform_of(Lane::V1, 0).is_none());
17693 assert!(p.undo());
17694 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17695
17696 // Two refusals, neither of which costs an undo step.
17697 let nan = TransformParams {
17698 scale: f32::NAN,
17699 ..transform_at(1)
17700 };
17701 assert!(
17702 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
17703 "no clip there"
17704 );
17705 assert!(
17706 !p.set_transform(Lane::V1, 0, Some(nan)),
17707 "not a finite value"
17708 );
17709 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17710 assert!(p.undo());
17711 assert_eq!(
17712 p.lane(Lane::V1).len(),
17713 3,
17714 "one step back is before the split"
17715 );
17716 assert!(p.undo());
17717 assert!(
17718 p.transform_of(Lane::V1, 0).is_none(),
17719 "and the next is before the placement: the refusals pushed none"
17720 );
17721 }
17722
17723 /// The transform table is append-only within a session, exactly as the eq
17724 /// and colour ones are -- and a save is where an undone placement goes.
17725 #[test]
17726 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
17727 let mut p = three();
17728 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
17729 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
17730 assert!(p.undo(), "back to the first placement");
17731 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
17732
17733 let (_, lanes, _, _, transform) = p.without_orphan_sources();
17734 assert_eq!(
17735 transform,
17736 vec![transform_at(1)],
17737 "what nothing plays is not written"
17738 );
17739 assert_eq!(
17740 lanes[0].1[0].transform,
17741 Some(0),
17742 "and the survivor renumbers"
17743 );
17744 assert_eq!(lanes[0].1[1].transform, None);
17745
17746 // One placement on three clips is one entry: settings that are equal
17747 // share.
17748 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
17749 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
17750 let (_, lanes, _, _, transform) = p.without_orphan_sources();
17751 assert_eq!(transform.len(), 1, "equal placements share their entry");
17752 assert_eq!(lanes[1].1[2].transform, Some(0));
17753 reloads(&p, "a transform that outlived an undo");
17754
17755 // A grade and a placement on one clip are two independent tables.
17756 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
17757 let (_, lanes, _, color, transform) = p.without_orphan_sources();
17758 assert_eq!((color.len(), transform.len()), (1, 1));
17759 assert_eq!(
17760 (lanes[0].1[0].color, lanes[0].1[0].transform),
17761 (Some(0), Some(0))
17762 );
17763 }
17764
17765 /// Not a claim about correctness but about cost: a clip is cloned on every
17766 /// paste, every undo snapshot and every lane clone, so its size is worth
17767 /// bounding. A clip is no longer `Copy` by design -- the keyframed gain
17768 /// envelope (`gain_keys`) owns a `Vec` -- so a clone is a heap allocation
17769 /// too, and the bound that matters is the inline size: 224 bytes today (the
17770 /// deinterlace choice, one byte, took it from 216 as there was no padding left)
17771 /// (the visualizer `u64` and six `Vec`s, the volume, placement, speed
17772 /// ramp, opacity and colour keys and the effects stack, are the wide fields; the placement keys raised it from 96 by one
17773 /// `Vec`, the speed ramp raised it from 120 by another, the opacity and
17774 /// colour keys took it from 144 to 192, and the effects stack to 216, the multicam angle to 224). The
17775 /// bound is `<=` rather than `==` so a field that shrinks the clip does not
17776 /// trip it; growing past it is the thing to notice.
17777 #[test]
17778 fn a_clip_stays_within_224_bytes() {
17779 assert!(
17780 std::mem::size_of::<Clip>() <= 224,
17781 "Clip grew to {} bytes -- every undo snapshot and clone pays for it",
17782 std::mem::size_of::<Clip>()
17783 );
17784 }
17785
17786 #[test]
17787 fn from_parts_has_no_history_and_checks_the_invariants() {
17788 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
17789 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
17790 let mut p = Project::from_parts(
17791 sources.clone(),
17792 lanes.clone(),
17793 eq.clone(),
17794 color.clone(),
17795 Vec::new(),
17796 )
17797 .expect("valid parts");
17798 assert_eq!(p.clips(), three().clips());
17799 assert!(!p.undo(), "a loaded project has nothing to undo");
17800 assert!(p.split(4), "...and is editable from there");
17801 assert!(p.undo());
17802
17803 // A lane may be empty, and so may every lane -- an emptied timeline is a
17804 // project. No lane at all is not one: there would be nothing to place on.
17805 assert!(
17806 Project::from_parts(
17807 sources.clone(),
17808 two(video.clone(), Vec::new()),
17809 Vec::new(),
17810 Vec::new(),
17811 Vec::new(),
17812 )
17813 .is_ok()
17814 );
17815 assert!(
17816 Project::from_parts(
17817 sources.clone(),
17818 two(Vec::new(), Vec::new()),
17819 Vec::new(),
17820 Vec::new(),
17821 Vec::new(),
17822 )
17823 .is_ok()
17824 );
17825 assert!(
17826 Project::from_parts(
17827 sources.clone(),
17828 Vec::new(),
17829 Vec::new(),
17830 Vec::new(),
17831 Vec::new()
17832 )
17833 .is_err()
17834 );
17835 let bad: [Vec<Clip>; 5] = [
17836 vec![clip(0, 0, 3, 1)], // source that is not there
17837 vec![clip(0, 3, 3, 0)], // empty clip
17838 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
17839 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
17840 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
17841 ];
17842 for clips in bad {
17843 assert!(
17844 Project::from_parts(
17845 sources.clone(),
17846 two(clips.clone(), Vec::new()),
17847 Vec::new(),
17848 Vec::new(),
17849 Vec::new(),
17850 )
17851 .is_err(),
17852 "{clips:?}"
17853 );
17854 assert!(
17855 Project::from_parts(
17856 sources.clone(),
17857 two(video.clone(), clips.clone()),
17858 Vec::new(),
17859 Vec::new(),
17860 Vec::new(),
17861 )
17862 .is_err()
17863 );
17864 // ...and on a third lane, which is checked by the same walk.
17865 assert!(
17866 Project::from_parts(
17867 sources.clone(),
17868 vec![
17869 (LaneKind::Video, video.clone()),
17870 (LaneKind::Audio, audio.clone()),
17871 (LaneKind::Video, clips),
17872 ],
17873 Vec::new(),
17874 Vec::new(),
17875 Vec::new(),
17876 )
17877 .is_err()
17878 );
17879 }
17880 // An equalizer index no table entry answers, and a table entry the file
17881 // format could not have written, are refused at this door too.
17882 let eqd = |i: u16| {
17883 vec![Clip {
17884 fade_in: 0,
17885 fade_out: 0,
17886 transition_out: 0,
17887 transition_kind: Default::default(),
17888 visualizer: 0,
17889 viz_paint: 0,
17890 gain_db: 0.0,
17891 eq: Some(i),
17892 ..video[0].clone()
17893 }]
17894 };
17895 assert!(
17896 Project::from_parts(
17897 sources.clone(),
17898 two(eqd(0), Vec::new()),
17899 Vec::new(),
17900 Vec::new(),
17901 Vec::new(),
17902 )
17903 .is_err()
17904 );
17905 let mut nan = band_at(1);
17906 nan.bands[0].freq_hz = f32::NAN;
17907 assert!(
17908 Project::from_parts(
17909 sources.clone(),
17910 two(eqd(0), Vec::new()),
17911 vec![nan],
17912 Vec::new(),
17913 Vec::new(),
17914 )
17915 .is_err()
17916 );
17917 let loaded = Project::from_parts(
17918 sources.clone(),
17919 two(eqd(0), Vec::new()),
17920 vec![band_at(1)],
17921 Vec::new(),
17922 Vec::new(),
17923 )
17924 .expect("an eq the table holds");
17925 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
17926
17927 // The same two refusals for a colour, at the same door.
17928 let graded = |i: u16| {
17929 vec![Clip {
17930 fade_in: 0,
17931 fade_out: 0,
17932 transition_out: 0,
17933 transition_kind: Default::default(),
17934 visualizer: 0,
17935 viz_paint: 0,
17936 gain_db: 0.0,
17937 color: Some(i),
17938 fit: FitPolicy::default(),
17939 speed: Speed::NORMAL,
17940 ..video[0].clone()
17941 }]
17942 };
17943 assert!(
17944 Project::from_parts(
17945 sources.clone(),
17946 two(graded(0), Vec::new()),
17947 Vec::new(),
17948 Vec::new(),
17949 Vec::new(),
17950 )
17951 .is_err(),
17952 "a colour index no entry answers"
17953 );
17954 assert!(
17955 Project::from_parts(
17956 sources.clone(),
17957 two(graded(0), Vec::new()),
17958 Vec::new(),
17959 vec![ColorParams {
17960 tint: f32::NAN,
17961 ..grade_at(1)
17962 }],
17963 Vec::new(),
17964 )
17965 .is_err(),
17966 "a value the file format could not have written"
17967 );
17968 let loaded = Project::from_parts(
17969 sources.clone(),
17970 two(graded(0), Vec::new()),
17971 Vec::new(),
17972 vec![grade_at(1)],
17973 Vec::new(),
17974 )
17975 .expect("a colour the table holds");
17976 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
17977
17978 // Group ids survive a load, and the next split gets a fresh one.
17979 let mut p =
17980 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
17981 assert!(p.split(4));
17982 assert!(p.clips().iter().all(|c| c.link.is_some()));
17983 }
17984
17985 /// The grouping rules, at the untrusted door and after every edit that can
17986 /// touch a link. A link id is at most one placement per lane -- a clip or a
17987 /// caption, whichever carries it -- and no sequence of edits may produce
17988 /// otherwise, because what an edit produces is what a save writes and a load
17989 /// reads.
17990 ///
17991 /// Amended for the offset-preserving group: the members keep their own
17992 /// spans, so two placements of one id covering different frames is *legal*
17993 /// -- it is what a hand-built group is -- and the only refusal left is the
17994 /// doubled id inside one lane.
17995 #[test]
17996 fn a_link_id_is_never_two_clips_of_one_lane() {
17997 let sources = vec![Source::new(FILE, 0)];
17998 let linked = |start, in_frame, out_frame, link| Clip {
17999 speed_keys: Vec::new(),
18000 reversed: false,
18001 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
18002 angle: Default::default(),
18003 fade_in: 0,
18004 fade_out: 0,
18005 transition_out: 0,
18006 transition_kind: Default::default(),
18007 visualizer: 0,
18008 viz_paint: 0,
18009 gain_db: 0.0,
18010 gain_keys: Vec::new(),
18011 pan: 0,
18012 pitch: 0,
18013 transform_keys: Vec::new(),
18014 opacity_keys: Vec::new(),
18015 color_keys: Vec::new(),
18016 effects: Vec::new(),
18017 start,
18018 in_frame,
18019 out_frame,
18020 source: 0,
18021 link: Some(link),
18022 eq: None,
18023 color: None,
18024 transform: None,
18025 fit: FitPolicy::default(),
18026 speed: Speed::NORMAL,
18027 };
18028
18029 // The door: a doubled id inside one lane, refused by name.
18030 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
18031 Project::from_parts(
18032 sources.clone(),
18033 two(video, audio),
18034 Vec::new(),
18035 Vec::new(),
18036 Vec::new(),
18037 )
18038 .expect_err("refused")
18039 .to_string()
18040 };
18041 assert!(
18042 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
18043 .contains("link 7 names two clips in the V1 lane"),
18044 "a duplicate id inside one lane is refused by name"
18045 );
18046 // ...and the same doubling on a subtitle lane, in its own words: a
18047 // caption is the other placement an id may name.
18048 let caption = |start: u32, frames: u32, link| SubClip {
18049 start,
18050 frames,
18051 track: 0,
18052 in_us: 0,
18053 out_us: i64::from(frames) * 1_000_000,
18054 link: Some(link),
18055 };
18056 let subs = LaneData {
18057 clips: Vec::new(),
18058 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
18059 ..LaneData::new(LaneKind::Subtitle, Vec::new())
18060 };
18061 assert_eq!(
18062 links_are_consistent(&[subs]).unwrap_err().to_string(),
18063 "link 7 names two captions in the S1 lane"
18064 );
18065 // A pair covering *different* frames is legal now: the members of a
18066 // hand-built group keep their own spans, and what binds them is the id.
18067 let apart = Project::from_parts(
18068 sources.clone(),
18069 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
18070 Vec::new(),
18071 Vec::new(),
18072 Vec::new(),
18073 );
18074 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
18075 // A one-sided link is *not* an error: it is what a lift leaves behind.
18076 let mut p = Project::single(FILE, 9);
18077 assert!(p.lift(Lane::A1, 0));
18078 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
18079 assert!(
18080 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
18081 "a lifted lane's project has to load again"
18082 );
18083
18084 // The edits: nothing below may break either rule.
18085 let consistent = |p: &Project, what: &str| {
18086 assert!(
18087 links_are_consistent(&p.lanes).is_ok(),
18088 "{what}: {:?}",
18089 p.lanes
18090 );
18091 };
18092 let mut p = three();
18093 let copied = p.clips()[0].clone();
18094 assert!(
18095 copied.link.is_some(),
18096 "the clipboard clip carries its group"
18097 );
18098 assert!(p.lift(Lane::V1, 0));
18099 assert!(p.place(Lane::V1, 0, copied.clone()));
18100 assert!(
18101 p.place(Lane::V1, 20, copied.clone()),
18102 "and again, further out"
18103 );
18104 assert_eq!(
18105 p.clips().iter().filter(|c| c.link == copied.link).count(),
18106 0,
18107 "a placement belongs to no group, so it cannot duplicate one"
18108 );
18109 consistent(&p, "lift + place twice");
18110 assert!(
18111 p.place(Lane::A1, 4, copied.clone()),
18112 "over a linked clip's middle"
18113 );
18114 consistent(&p, "place through a grouped clip");
18115 assert!(
18116 p.paste(6, copied.clone()),
18117 "a rippling paste through another"
18118 );
18119 consistent(&p, "paste");
18120 assert!(p.split(2));
18121 consistent(&p, "split");
18122 assert!(p.ripple_delete(1, 3));
18123 consistent(&p, "ripple_delete");
18124 assert!(p.undo());
18125 consistent(&p, "undo");
18126 }
18127
18128 /// What an edit produces is what a save writes, so *every* state the public
18129 /// API can reach has to load again. The two the verifier panel found where
18130 /// it did not: a split and a regroup handed one group id to two clips that
18131 /// were not the same span, because the lanes had been edited apart.
18132 #[test]
18133 fn every_reachable_state_reloads() {
18134 let mut p = Project::single(FILE, 150);
18135 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
18136 assert!(p.split(10), "the lanes are cut apart at 10");
18137 reloads(&p, "place on one lane, then split");
18138
18139 let mut p = Project::single(FILE, 150);
18140 assert!(p.split(30));
18141 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
18142 assert!(p.regroup(30), "only the audio lane can rejoin");
18143 assert!(p.split(60));
18144 reloads(&p, "lift, regroup one lane, split");
18145
18146 // Two audio streams of one file, both placed: two source entries with
18147 // one path between them, which is the state a stream picked out of the
18148 // library reaches -- and the state a save has to write and read back.
18149 let mut p = Project::single(FILE, 150);
18150 let second = p.import(FILE, 1);
18151 assert_eq!(second, 1, "the same file on another stream is a new source");
18152 assert!(p.append_clip(second, 150));
18153 assert!(p.split(200));
18154 reloads(
18155 &p,
18156 "a second audio stream of the same file, placed and split",
18157 );
18158 let (sources, ..) = p.without_orphan_sources();
18159 assert_eq!(
18160 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
18161 [0, 1],
18162 "both entries survive the orphan prune: both are played"
18163 );
18164 }
18165
18166 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
18167 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
18168 /// is the stamp playback puts on a decoded source frame -- and the *last*
18169 /// source frame the pump is still holding at a timeline frame has to be
18170 /// exactly the one the export encoded there, at every rate. Anything else is
18171 /// A/V drift that grows with the clip, and no test of either side alone
18172 /// would see it.
18173 ///
18174 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
18175 /// is a better answer than the floor/floor this had: floor/floor put the
18176 /// preview a whole held frame off the export at slow rates.)
18177 #[test]
18178 fn speed_maps_both_ways() {
18179 for permille in (250..=4000).step_by(1) {
18180 let speed = Speed::from_permille(permille);
18181 assert_eq!(speed.permille(), permille, "no clamping in range");
18182 for d in 0..200u32 {
18183 let want = speed.source_at(d);
18184 // What the pump shows at `d` is the last frame whose stamp has
18185 // come due -- and it is `want`, the frame the export encodes
18186 // there. Slowed, that is the frame it is still holding; sped up,
18187 // it is the newest of the several that arrived.
18188 let held = (0..=want + 8).rev().find(|&s| speed.timeline_at(s) <= d);
18189 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
18190 }
18191 for n in 1..300u32 {
18192 // A footprint is never zero: a clip occupying no timeline frame
18193 // is a placement the lane invariants cannot hold.
18194 let frames = speed.frames(n);
18195 assert!(frames >= 1, "{speed} of {n} frames");
18196 // ...and its last timeline frame never reads past the clip.
18197 assert!(
18198 speed.source_at(frames - 1) < n,
18199 "{speed}: the last timeline frame of {n} reads past the clip"
18200 );
18201 // The trim inverse never overshoots the room it was given, and
18202 // answers for every room a footprint can be.
18203 let fit = speed.fit(frames).expect("a clip fits its own footprint");
18204 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
18205 // A room narrower than one source frame's own footprint holds
18206 // nothing, and says so rather than rounding something into it.
18207 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
18208 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
18209 }
18210 }
18211 // Real time is the identity map, byte for byte.
18212 for d in 0..1000 {
18213 assert_eq!(Speed::NORMAL.source_at(d), d);
18214 assert_eq!(Speed::NORMAL.timeline_at(d), d);
18215 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
18216 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
18217 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
18218 }
18219 // The one door: no zero, no reverse, nothing past the ends.
18220 assert_eq!(Speed::from_permille(0), Speed::MIN);
18221 assert_eq!(Speed::from_permille(249), Speed::MIN);
18222 assert_eq!(Speed::from_permille(4001), Speed::MAX);
18223 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
18224 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
18225 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
18226 }
18227
18228 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
18229 /// export encodes at a timeline frame is the one playback is holding there,
18230 /// a file is as long in timeline frames as the seconds it lasts, and the two
18231 /// compose so a speeded clip at another rate is exactly both.
18232 #[test]
18233 fn rate_composes_with_speed() {
18234 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
18235 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
18236 // the identity map or a single-rate project would move.
18237 for (source_fps, timeline_fps) in [
18238 (24000. / 1001., 30.),
18239 (30., 24000. / 1001.),
18240 (60., 30.),
18241 (25., 30.),
18242 (30., 30.),
18243 ] {
18244 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
18245 for n in 0..2000u32 {
18246 let source = rate.source_at(n);
18247 // The stamp is the *first* timeline-rate frame that shows it, so
18248 // the picture on screen at `n` is the picture encoded at `n`.
18249 let held = (0..=source + 4).rev().find(|&s| rate.timeline_at(s) <= n);
18250 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
18251 }
18252 // A file of `count` frames is `timeline_at(count)` frames long here,
18253 // and its last one still reads a frame the file has.
18254 for count in 1..500u32 {
18255 let frames = rate.timeline_at(count);
18256 assert!(frames >= 1, "a file is never zero frames long");
18257 assert!(
18258 rate.source_at(frames - 1) < count,
18259 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
18260 );
18261 }
18262 // No drift: the mapping is one exact division of the *rate itself*,
18263 // not an accumulation and not a rounded rate, so an hour in is as
18264 // true as the first second. (Held to the real ratio of the two rates
18265 // the caller asked for -- `as_f64` would be true of a wrong rate.)
18266 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
18267 let want = f64::from(n) * source_fps / timeline_fps;
18268 assert!(
18269 (f64::from(rate.source_at(n)) - want).abs() < 1.,
18270 "{source_fps} on {timeline_fps}: frame {n} drifted"
18271 );
18272 }
18273 }
18274 // The timeline's own rate is the identity, whichever way it is written.
18275 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
18276 assert!(
18277 Rate::from_fps(30.0004, 30.)
18278 .expect("30.0004 over 30")
18279 .is_real_time(),
18280 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
18281 );
18282 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
18283 // one thing `matches_timeline` refuses a file for now that the rate gate
18284 // is gone.
18285 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
18286 assert!(Rate::from_fps(30., f64::NAN).is_err());
18287 for n in 0..1000 {
18288 assert_eq!(Rate::REAL_TIME.source_at(n), n);
18289 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
18290 }
18291 // ...and the composition, in the order the decoder's door applies it:
18292 // the speed picks the clip's (timeline-rate) frame, the rate picks the
18293 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
18294 // timeline frames per frame shown, each of them exactly 800/1001 of a
18295 // file frame.
18296 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
18297 let speed = Speed::from_permille(2000);
18298 for d in 0..100u32 {
18299 assert_eq!(
18300 rate.source_at(speed.source_at(d)),
18301 (u64::from(d) * 2 * 800 / 1001) as u32,
18302 "2x of a 23.976 fps file at timeline frame {d}"
18303 );
18304 }
18305 }
18306
18307 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
18308 /// source frames per timeline frame and still starts at its own in-point,
18309 /// and a half-speed one shows every source frame twice.
18310 #[test]
18311 fn a_rate_maps_timeline_frames_onto_source_frames() {
18312 let mut p = Project::single(FILE, 40);
18313 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
18314 .expect("room enough");
18315 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
18316 assert_eq!(
18317 p.map(Lane::V1, 0),
18318 Some((0, 0)),
18319 "and it starts where it did"
18320 );
18321 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
18322 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
18323 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
18324 // The span a decoder is handed: as many source frames as it will read,
18325 // which is the last shown frame's own and not one more -- timeline frame
18326 // 19 shows source frame 38, so 39 frames are read and the 40th is a
18327 // picture nothing would display.
18328 let span = p.span_at(Lane::V1, 0).expect("a span");
18329 assert_eq!((span.len, span.source_len()), (20, 39));
18330 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
18331 // ...and the same clip the other way round.
18332 let mut p = Project::single(FILE, 40);
18333 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
18334 .expect("room enough");
18335 assert_eq!(p.timeline_frames(), 80);
18336 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
18337 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
18338 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
18339 assert_eq!(
18340 p.map(Lane::V1, 79),
18341 Some((0, 39)),
18342 "and the last timeline frame is still inside the source range"
18343 );
18344 }
18345
18346 /// A trim of a speeded clip is still a trim of its *source*, and the edge
18347 /// still stops at the wall: the room a rate leaves is measured in timeline
18348 /// frames and the range it commits in source ones.
18349 #[test]
18350 fn trimming_a_speeded_clip_stays_inside_its_room() {
18351 let mut p = Project::single(FILE, 40);
18352 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
18353 .expect("room enough");
18354 // A second clip butted against the first, so the wall is a real one.
18355 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
18356 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
18357 assert_eq!(room, (1, 20), "out to the neighbour and no further");
18358 assert!(
18359 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
18360 "clamped to the wall, which is where the edge already is"
18361 );
18362 let c = p.clips()[0].clone();
18363 assert_eq!(c.end(), 20, "so nothing moved");
18364 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
18365 // ...and in: half the timeline frames is half the source range.
18366 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
18367 let c = p.clips()[0].clone();
18368 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
18369 assert_eq!(c.end(), 10, "and ten timeline frames of them");
18370 assert!(sorted_disjoint(p.clips()));
18371 }
18372
18373 /// The frames a rate cannot address: at half speed each source frame is on
18374 /// screen twice, and the cut between the two showings is not a cut in the
18375 /// file. Refused, so the two halves always add up to the clip that was cut.
18376 #[test]
18377 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
18378 let mut p = Project::single(FILE, 10);
18379 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
18380 .expect("room enough");
18381 assert_eq!(p.timeline_frames(), 20);
18382 assert!(
18383 !p.split(3),
18384 "an odd frame is between two showings of one frame"
18385 );
18386 assert_eq!(p.clips().len(), 1, "and nothing was cut");
18387 assert!(p.split(4), "an even one is a frame boundary");
18388 let halves = p.clips().to_vec();
18389 assert_eq!(
18390 (halves[0].end(), halves[1].start, halves[1].end()),
18391 (4, 4, 20),
18392 "the halves meet, and still end where the clip did"
18393 );
18394 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
18395 assert!(p.regroup(4), "and the inverse puts it back");
18396 assert_eq!(p.clips().len(), 1);
18397 }
18398
18399 /// The same claim, swept: random op sequences off the public surface, the
18400 /// project reloaded after every one of them. A failure prints its seed, and
18401 /// the seed replays the whole sequence.
18402 #[test]
18403 fn random_edit_sequences_reload() {
18404 // Two thousand, not two hundred: the overlap a hole punched into a slow
18405 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
18406 // sequences, and a 200-seed sweep walked straight past it (it took a
18407 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
18408 // has no business being the narrow one.
18409 for seed in 0..2000u64 {
18410 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
18411 let mut next = move |n: u32| {
18412 // xorshift64*: no dependency, and the seed replays it exactly.
18413 rng ^= rng << 13;
18414 rng ^= rng >> 7;
18415 rng ^= rng << 17;
18416 (rng >> 33) as u32 % n
18417 };
18418 let mut p = Project::single(FILE, 40);
18419 for step in 0..24 {
18420 let frame = next(44);
18421 // A clipboard copy carries the group id of the take it came from
18422 // -- the input that made a placement duplicate an id -- and, one
18423 // time in three, a rate of its own: a *speeded clip placed over
18424 // a speeded clip* is the shape whose remainders have to be run
18425 // through `Speed::fit`, and it is not a shape the lanes hand out
18426 // on their own often enough to be sure of.
18427 let mut copied = p
18428 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
18429 .get(next(4) as usize)
18430 .cloned()
18431 .unwrap_or_else(|| clip(0, 0, 5, 0));
18432 if next(3) == 0 {
18433 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
18434 }
18435 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
18436 let idx = next(4) as usize;
18437 let _ = match next(16) {
18438 // A clip dragged along its own lane to wherever the pointer
18439 // let it go: the op that moves a placement without changing
18440 // what it plays, so what it may not do is land on top of the
18441 // neighbour it was dragged at.
18442 15 => p.move_clip(lane, idx, lane, frame),
18443 // ...and a second `place`, so a punch lands inside a clip
18444 // far more often than one op in fourteen would put it there.
18445 14 => p.place(lane, frame, copied.clone()),
18446 0 => p.split(frame),
18447 1 => p.regroup(frame),
18448 2 => p.lift(lane, idx),
18449 3 => p.place(lane, frame, copied.clone()),
18450 4 => p.paste(frame, copied.clone()),
18451 5 => p.ripple_delete(frame, next(9)),
18452 6 => p.delete(idx),
18453 7 => p.undo(),
18454 // An equalizer put on and taken off in the mix: what a clip
18455 // carries has to reload with it, and the entries an undo
18456 // orphans must not come back out of the prune.
18457 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
18458 9 => p.set_eq(lane, idx, None),
18459 // ...and a colour grade in the same mix, for the same
18460 // reason: it rides on the clip and its orphans must go.
18461 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
18462 11 => p.set_color(lane, idx, None),
18463 // ...and a rate in with them, which is the one of the three
18464 // that moves *placements*: a clip that grew has to be
18465 // refused rather than overlap, and one that shrank leaves a
18466 // lane that still loads. Both are what `reloads` asks.
18467 12 => p
18468 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
18469 .is_ok(),
18470 _ => p.append_clip(0, 1 + next(9)),
18471 };
18472 reloads(&p, &format!("seed {seed}, step {step}"));
18473 }
18474 }
18475 }
18476
18477 /// The save/load round trip a project must survive: the parts a save writes,
18478 /// handed back to the constructor a load goes through -- every lane of them,
18479 /// and the reloaded timeline has to be the same lanes in the same order.
18480 fn reloads(p: &Project, what: &str) {
18481 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
18482 match Project::from_parts(sources, lanes, eq, color, transform) {
18483 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
18484 Ok(back) => {
18485 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
18486 // Placements, not whole clips: an orphan prune renumbers the
18487 // sources a clip names, which is the point of it.
18488 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
18489 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
18490 };
18491 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
18492 // The prune renumbers the eq table too, so what has to survive
18493 // is the settings themselves, clip by clip.
18494 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
18495 p.lanes()
18496 .into_iter()
18497 .map(|l| {
18498 (0..p.lane(l).len())
18499 .map(|i| p.eq_of(l, i).cloned())
18500 .collect()
18501 })
18502 .collect()
18503 };
18504 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
18505 // The colour table renumbers in the same prune, so the same
18506 // claim: the params a clip names, not the index it names them by.
18507 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
18508 p.lanes()
18509 .into_iter()
18510 .map(|l| {
18511 (0..p.lane(l).len())
18512 .map(|i| p.color_of(l, i).copied())
18513 .collect()
18514 })
18515 .collect()
18516 };
18517 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
18518 // ...and the transform table, by the same claim again.
18519 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
18520 p.lanes()
18521 .into_iter()
18522 .map(|l| {
18523 (0..p.lane(l).len())
18524 .map(|i| p.transform_of(l, i).copied())
18525 .collect()
18526 })
18527 .collect()
18528 };
18529 assert_eq!(
18530 transforms(&back),
18531 transforms(p),
18532 "{what}: the transforms changed"
18533 );
18534 }
18535 }
18536 }
18537
18538 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
18539 /// -- each one sorted and disjoint, and one span per group id -- asserted
18540 /// directly, where the point is the invariant rather than the round trip.
18541 fn invariants_hold(p: &Project, what: &str) {
18542 for lane in p.lanes() {
18543 assert!(
18544 sorted_disjoint(p.lane(lane)),
18545 "{what}: {} is out of order or overlaps itself: {:?}",
18546 lane.label(),
18547 p.lane(lane)
18548 );
18549 }
18550 if let Err(e) = links_are_consistent(&p.lanes) {
18551 panic!("{what}: {e}\n{:?}", p.lanes);
18552 }
18553 }
18554
18555 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
18556 /// edited without any other lane hearing about it. A handle naming a lane
18557 /// that is not there reads as empty and refuses to mutate.
18558 #[test]
18559 fn a_third_lane_is_a_peer() {
18560 let mut p = three();
18561 assert_eq!(p.lane_count(LaneKind::Video), 1);
18562 assert_eq!(p.lane_count(LaneKind::Audio), 1);
18563 let v2 = p.add_lane(LaneKind::Video);
18564 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
18565 assert_eq!(v2.label(), "V2");
18566 assert_eq!(p.lane_count(LaneKind::Video), 2);
18567 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
18568 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
18569
18570 // A handle for a lane that is not there: empty, and no mutation takes.
18571 let v3 = Lane::new(LaneKind::Video, 2);
18572 assert!(p.lane(v3).is_empty());
18573 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
18574 assert!(!p.lift(v3, 0));
18575 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
18576
18577 // Placing on V2 moves nothing else, and the lane can outrun the rest.
18578 let before = shape(&p);
18579 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
18580 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
18581 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
18582 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
18583 assert_eq!(
18584 p.timeline_frames(),
18585 16,
18586 "the last lane to end sets the length"
18587 );
18588 assert_eq!(p.map(v2, 5), Some((0, 21)));
18589 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
18590 assert_eq!(
18591 p.span_at(v2, 0),
18592 Some(Span {
18593 reverse: false,
18594 ramp: None,
18595 start: 0,
18596 len: 4,
18597 from: None,
18598 speed: Speed::NORMAL,
18599 pitch: 0,
18600 })
18601 );
18602 // Every lane still covers the whole timeline, gaps included.
18603 for l in p.lanes() {
18604 let spans = p.spans_from(l, 0);
18605 assert_eq!(
18606 spans.iter().map(|s| s.len).sum::<u32>(),
18607 16,
18608 "{}",
18609 l.label()
18610 );
18611 }
18612 // ...and playback still reads V1 and A1, whatever else is there.
18613 assert_eq!(p.clips(), p.lane(Lane::V1));
18614 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
18615 let segments = p.segments_from(0, FPS);
18616 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
18617 assert_eq!(
18618 segments[3],
18619 (None, 0.0, 7.0 / FPS),
18620 "A1 keeps the clock counting over the picture V2 added"
18621 );
18622 invariants_hold(&p, "place on V2");
18623
18624 // A lift is that lane's business too, and the lane list undoes.
18625 assert!(p.lift(v2, 0));
18626 assert!(p.lane(v2).is_empty());
18627 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
18628 assert!(p.undo());
18629 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
18630 assert!(p.undo());
18631 assert!(p.lane(v2).is_empty(), "the placement came off V2");
18632 assert!(p.undo(), "and one more step takes the lane itself back");
18633 assert_eq!(p.lane_count(LaneKind::Video), 1);
18634 assert_eq!(shape(&p), shape(&three()));
18635 }
18636
18637 /// The add taken back: an empty lane comes off, a lane holding clips never
18638 /// does (and says which clips), the last lane of a kind never does, the
18639 /// lanes below the one that went move up an `ord`, and one undo puts it
18640 /// back where it stood.
18641 #[test]
18642 fn an_empty_lane_comes_off_again() {
18643 let mut p = three();
18644 let v2 = p.add_lane(LaneKind::Video);
18645 let v3 = p.add_lane(LaneKind::Video);
18646 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
18647 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
18648 let history = p.history.len();
18649
18650 // The last lane of its kind stays: `V1`/`A1` are where an import and a
18651 // paste land, and a project missing one would swallow half of a file
18652 // dropped on it.
18653 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
18654 assert_eq!(
18655 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
18656 "there is no V10 to remove"
18657 );
18658
18659 // A lane with clips on it refuses and names them: a track removal never
18660 // deletes a take.
18661 let refusal = why(p.remove_lane(v3));
18662 assert!(refusal.contains("V3 still holds"), "{refusal}");
18663 assert!(refusal.contains(FILE), "{refusal}");
18664 assert!(refusal.contains("at frame 0"), "{refusal}");
18665 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
18666 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
18667
18668 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
18669 // all.
18670 p.remove_lane(v2).expect("V2 is empty");
18671 assert_eq!(p.lane_count(LaneKind::Video), 2);
18672 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
18673 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
18674 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
18675 invariants_hold(&p, "remove V2");
18676
18677 // ...and one stroke puts the empty lane back above it.
18678 assert!(p.undo());
18679 assert_eq!(p.lane_count(LaneKind::Video), 3);
18680 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
18681 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
18682 }
18683
18684 /// A duck is the audio lane's own setting: it names another audio lane as
18685 /// its key, refuses itself and video lanes as a key or a target, is one undo
18686 /// step, and reaches the mix only for a key that is in the mix.
18687 #[test]
18688 fn a_duck_keys_off_another_audio_lane_and_is_one_undo_step() {
18689 use crate::duck::Duck;
18690 let mut p = Project::single(FILE, 9);
18691 let a2 = p.add_lane(LaneKind::Audio);
18692 let duck = Duck::new(0, -12.0);
18693 let history = p.history.len();
18694 assert!(
18695 !p.set_lane_duck(Lane::A1, Some(duck)),
18696 "a lane is not its own key"
18697 );
18698 assert!(
18699 !p.set_lane_duck(Lane::V1, Some(duck)),
18700 "a video lane does not duck"
18701 );
18702 assert!(
18703 !p.set_lane_duck(a2, Some(Duck::new(5, -12.0))),
18704 "no such key"
18705 );
18706 assert!(!p.set_lane_duck(
18707 a2,
18708 Some(Duck {
18709 depth_db: f32::NAN,
18710 ..duck
18711 })
18712 ));
18713 assert_eq!(p.history.len(), history, "a refusal writes no history");
18714 assert!(p.set_lane_duck(a2, Some(duck)));
18715 assert_eq!(p.lane_duck(a2), Some(duck));
18716 assert_eq!(p.history.len(), history + 1, "one undo step");
18717 // A2 is empty, so it is not in the mix and cannot be a key in it.
18718 assert_eq!(p.audio_ducks(), vec![Vec::<Duck>::new()], "one mixed lane, unducked");
18719 assert_eq!(p.lane_ducks()[2], vec![duck], "saved by its own lane");
18720 assert!(p.undo());
18721 assert_eq!(p.lane_duck(a2), None, "undone");
18722 }
18723
18724 /// A lane is ducked under several keys at once, each set on its own: a duck
18725 /// under a key the lane already has replaces that one, a clear takes one key
18726 /// away, and the mix reads them all in the order they were set.
18727 #[test]
18728 fn a_lane_ducks_under_several_keys_and_each_can_be_cleared() {
18729 use crate::duck::Duck;
18730 let mut p = Project::single(FILE, 9);
18731 let a2 = p.add_lane(LaneKind::Audio);
18732 let a3 = p.add_lane(LaneKind::Audio);
18733 // A1 and A2 are the keys that A3 is ducked under.
18734 assert!(p.set_lane_duck(a3, Some(Duck::new(0, -12.0))), "A3 under A1");
18735 assert!(p.set_lane_duck(a3, Some(Duck::new(1, -6.0))), "A3 under A2 too");
18736 assert_eq!(p.lane_duck_list(a3).len(), 2, "both kept");
18737 assert_eq!(p.lane_duck(a3), Some(Duck::new(0, -12.0)), "the first set");
18738 // The same key again replaces its duck and keeps the other.
18739 assert!(p.set_lane_duck(a3, Some(Duck::new(1, -20.0))));
18740 let list = p.lane_duck_list(a3);
18741 assert_eq!(list.len(), 2);
18742 assert_eq!(list[1].depth_db, -20.0, "the A2 key's depth changed in place");
18743 assert_eq!(list[0].depth_db, -12.0, "the A1 key untouched");
18744 // A key that is the lane itself is still refused, whatever else it holds.
18745 assert!(!p.set_lane_duck(a3, Some(Duck::new(2, -6.0))));
18746 // Clearing one key leaves the other; clearing a key it lacks is a refusal.
18747 assert!(p.clear_lane_duck(a3, 0));
18748 assert_eq!(p.lane_duck_list(a3), vec![Duck { depth_db: -20.0, ..Duck::new(1, -20.0) }]);
18749 assert!(!p.clear_lane_duck(a3, 0), "no duck under A1 now");
18750 // None clears them all.
18751 assert!(p.set_lane_duck(a3, None));
18752 assert!(p.lane_duck_list(a3).is_empty());
18753 assert!(!p.set_lane_duck(a2, None), "nothing to clear is no change");
18754 }
18755
18756 /// Mute is the audio lane's switch and nothing else: it zeroes the lane's
18757 /// amplitude in the mix, leaves the lane's volume and clips where they were,
18758 /// is one undo step each way, and refuses the lanes it cannot mean anything
18759 /// for.
18760 #[test]
18761 fn a_muted_audio_lane_is_silent_in_the_mix_and_unmuting_restores_it() {
18762 let mut p = Project::single(FILE, 9);
18763 assert_eq!(p.audio_gains(), vec![1.0], "one lane at unity");
18764 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
18765 let loud = p.audio_gains()[0];
18766 let history = p.history.len();
18767
18768 assert!(p.set_lane_muted(Lane::A1, true));
18769 assert_eq!(p.audio_gains(), vec![0.0], "muted is silence in the sum");
18770 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "the volume is kept");
18771 assert_eq!(p.lane(Lane::A1).len(), 1, "and so are the clips");
18772 assert_eq!(p.history.len(), history + 1, "one undo step");
18773 assert!(
18774 !p.set_lane_muted(Lane::A1, true),
18775 "already muted is a no-op"
18776 );
18777 assert_eq!(p.history.len(), history + 1, "and no undo step for it");
18778
18779 assert!(p.set_lane_muted(Lane::A1, false));
18780 assert_eq!(p.audio_gains(), vec![loud], "unmuted is what it was");
18781
18782 // One undo per switch: the flag comes back through the lane list.
18783 assert!(p.undo());
18784 assert!(p.lane_muted(Lane::A1), "undo restores the muted flag");
18785 assert!(p.undo());
18786 assert!(!p.lane_muted(Lane::A1), "and the one before it");
18787
18788 assert!(
18789 !p.set_lane_muted(Lane::V1, true),
18790 "a video lane is never mixed"
18791 );
18792 assert!(
18793 !p.set_lane_hidden(Lane::A1, true),
18794 "an audio lane has no picture to hide"
18795 );
18796 assert!(
18797 !p.set_lane_hidden(Lane::new(LaneKind::Video, 7), true),
18798 "a lane that is not there"
18799 );
18800 }
18801
18802 /// Hiding a video lane takes it out of the composite: the picture is what
18803 /// the visible lanes cover, the lane under a hidden one shows through, and
18804 /// hiding the last covering lane leaves black. One undo step, and the flag
18805 /// is in the lane list, so a save and an undo both carry it.
18806 #[test]
18807 fn a_hidden_video_lane_leaves_the_composite() {
18808 let mut p = Project::single(FILE, 9);
18809 let v2 = p.add_lane(LaneKind::Video);
18810 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
18811 assert_eq!(p.composite_clip_at(3), Some((v2, 0)), "V2 is on top");
18812
18813 let history = p.history.len();
18814 assert!(p.set_lane_hidden(v2, true));
18815 assert_eq!(p.history.len(), history + 1, "one undo step");
18816 assert!(p.lane_hidden(v2));
18817 assert_eq!(
18818 p.composite_clip_at(3),
18819 Some((Lane::V1, 0)),
18820 "V1 shows through"
18821 );
18822 assert_eq!(
18823 p.composite_spans_from(0).len(),
18824 1,
18825 "one span, from V1 alone"
18826 );
18827
18828 assert!(p.set_lane_hidden(Lane::V1, true));
18829 assert_eq!(p.composite_clip_at(3), None, "nothing visible, so black");
18830 assert!(p.undo());
18831 assert!(!p.lane_hidden(Lane::V1), "undo restores the flag");
18832 assert!(p.lane_hidden(v2));
18833 assert!(p.undo());
18834 assert!(!p.lane_hidden(v2));
18835 assert_eq!(p.composite_clip_at(3), Some((v2, 0)));
18836
18837 // Lock is state only: it refuses nothing in the engine.
18838 assert!(p.set_lane_locked(v2, true));
18839 assert!(p.lane_locked(v2));
18840 assert!(
18841 p.place(v2, 0, clip(0, 0, 3, 0)),
18842 "a locked lane still takes edits"
18843 );
18844 assert!(p.undo());
18845 assert!(p.lane_locked(v2), "undoing the edit leaves the lock");
18846 assert!(p.undo());
18847 assert!(!p.lane_locked(v2), "and the lock is one step of its own");
18848 }
18849
18850 /// A hidden subtitle lane has no cues, so the screen draws none and the
18851 /// export writes no track for it; showing it again brings them back.
18852 #[test]
18853 fn a_hidden_subtitle_lane_yields_no_cues_until_shown_again() {
18854 let track = SubtitleTrack {
18855 path: FILE.into(),
18856 track: None,
18857 language: "eng".into(),
18858 name: String::new(),
18859 label: "eng".into(),
18860 cues: vec![crate::subtitle::Cue {
18861 start_us: 8_000_000,
18862 end_us: 9_000_000,
18863 text: "a line".into(),
18864 image: None,
18865 words: Vec::new(),
18866 karaoke: Vec::new(),
18867 }],
18868 bitmap: false,
18869 refused: None,
18870 };
18871 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
18872 let s1 = p.add_lane(LaneKind::Subtitle);
18873 p.place_sub(
18874 s1,
18875 0,
18876 SubClip {
18877 start: 0,
18878 frames: 300,
18879 track: 0,
18880 in_us: 0,
18881 out_us: 10_000_000,
18882 link: None,
18883 },
18884 )
18885 .expect("placed");
18886 assert_eq!(p.sub_lane_cues(s1, FPS).len(), 1, "shown, the cue is there");
18887
18888 assert!(p.set_lane_hidden(s1, true));
18889 assert!(
18890 p.sub_lane_cues(s1, FPS).is_empty(),
18891 "hidden, the lane gives no cues"
18892 );
18893
18894 assert!(p.set_lane_hidden(s1, false));
18895 assert_eq!(
18896 p.sub_lane_cues(s1, FPS).len(),
18897 1,
18898 "shown again, the cue comes back"
18899 );
18900 }
18901
18902 /// The switches live in the lane list, so a snapshot carries them with the
18903 /// rest; and [`Project::with_lane_flags`] puts them back on load with no undo
18904 /// step, as [`Project::with_mix`] does for the volumes.
18905 #[test]
18906 fn lane_switches_come_back_on_load_without_an_undo_step() {
18907 let mut p = Project::single(FILE, 9);
18908 assert!(p.set_lane_locked(Lane::V1, true));
18909 assert!(p.set_lane_hidden(Lane::V1, true));
18910 let flags = p.lane_flags();
18911 assert_eq!(
18912 flags[0],
18913 LaneFlags {
18914 hidden: true,
18915 muted: false,
18916 locked: true,
18917 pan: 0.0,
18918 }
18919 );
18920 let back = Project::from_parts(
18921 p.sources().to_vec(),
18922 p.lanes()
18923 .into_iter()
18924 .map(|l| (l.kind, p.lane(l).to_vec()))
18925 .collect(),
18926 Vec::new(),
18927 Vec::new(),
18928 Vec::new(),
18929 )
18930 .expect("the same lanes load")
18931 .with_lane_flags(&flags);
18932 assert!(back.lane_hidden(Lane::V1) && back.lane_locked(Lane::V1));
18933 assert!(!back.lane_muted(Lane::A1));
18934 let mut back = back;
18935 assert!(!back.undo(), "a loaded switch is not an undo step");
18936 }
18937
18938 /// A track dragged to another place in the stack: the whole lane travels --
18939 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
18940 /// a video one, a lane that crosses one of its own kind swaps names with it
18941 /// (and swaps the composite with it), one undo puts the order back, and a
18942 /// save carries it.
18943 #[test]
18944 fn a_track_is_dragged_to_another_place_in_the_stack() {
18945 let mut p = three();
18946 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
18947 let before = shape(&p);
18948 let history = p.history.len();
18949
18950 // A1 over V1: the screen is rearranged and nothing else is. Both keep
18951 // their names -- neither crossed a lane of its own kind -- so every
18952 // handle a front-end holds still names the track it named before.
18953 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
18954 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
18955 assert_eq!(
18956 shape(&p),
18957 vec![before[1].clone(), before[0].clone()],
18958 "each lane's clips travelled with it, and none was remapped"
18959 );
18960 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
18961 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
18962 invariants_hold(&p, "A1 over V1");
18963
18964 // Nothing moves for a lane that is not there, a slot that is not, or a
18965 // lane already standing in the one it was pointed at.
18966 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
18967 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
18968 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
18969 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
18970
18971 // ...and one stroke puts the order back.
18972 assert!(p.undo());
18973 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
18974 assert_eq!(shape(&p), before);
18975
18976 // A second video lane over the first: display order *is* the stack, so
18977 // the last video lane covering a frame is the picture that shows.
18978 let v2 = p.add_lane(LaneKind::Video);
18979 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
18980 let over = shape(&p)[2].clone();
18981 assert_eq!(
18982 p.composite_span_at(0).map(|s| s.len),
18983 Some(5),
18984 "V2's five frames are what frame 0 shows"
18985 );
18986
18987 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
18988 // a position among the lanes of its kind. The picture that wins changes
18989 // with it: the take that was covering is the covered one now.
18990 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
18991 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
18992 assert_eq!(
18993 shape(&p),
18994 vec![over.clone(), before[0].clone(), before[1].clone()],
18995 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
18996 );
18997 assert_eq!(
18998 p.composite_span_at(0).map(|s| s.len),
18999 Some(3),
19000 "the lower video lane wins, and it is the old V1 now"
19001 );
19002 invariants_hold(&p, "V2 over V1");
19003
19004 // A save writes that order and a load takes it back.
19005 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
19006 assert_eq!(
19007 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
19008 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
19009 );
19010 let back =
19011 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
19012 assert_eq!(back.lanes(), p.lanes());
19013 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
19014
19015 assert!(p.undo(), "and the stack goes back to how it stood");
19016 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
19017 }
19018
19019 /// The grouping rule across more than two lanes, under the offset model: a
19020 /// split *keeps* the group on the left halves and hands the right halves of
19021 /// that group one fresh id of their own -- a clip in no group comes out of
19022 /// the cut in none. So a take cut apart is two takes, one per side, and a
19023 /// lane that was never part of it stays out of both.
19024 #[test]
19025 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
19026 let mut p = Project::single(FILE, 9);
19027 let take = p.clips()[0].link.expect("a fresh project is one take");
19028 let v2 = p.add_lane(LaneKind::Video);
19029 assert!(
19030 p.place(v2, 0, clip(0, 0, 9, 0)),
19031 "a placement joins no group"
19032 );
19033 assert!(p.split(4));
19034 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
19035 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
19036 };
19037 let (left, right) = (side(&p, 0), side(&p, 1));
19038 // The lanes in order are V1, A1, V2: the take's two keep its id on the
19039 // left, and the placed clip never had one for the cut to keep.
19040 assert_eq!(
19041 left,
19042 vec![Some(take), Some(take), None],
19043 "the left halves keep the take"
19044 );
19045 // ...and the right halves of that take are one fresh group.
19046 assert_eq!(right[0], right[1]);
19047 assert_ne!(right[0], Some(take));
19048 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
19049 invariants_hold(&p, "split across three lanes");
19050
19051 // V2 ends early: the left halves still keep what each clip carried --
19052 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
19053 // shared by exactly the take's lanes.
19054 let mut p = Project::single(FILE, 9);
19055 let v2 = p.add_lane(LaneKind::Video);
19056 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
19057 assert!(p.split(3));
19058 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
19059 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
19060 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
19061 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
19062 invariants_hold(&p, "split where one lane ends early");
19063
19064 // The inverse rejoins each lane into the group its left half kept.
19065 assert!(p.regroup(3));
19066 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
19067 assert_eq!(
19068 p.lane(Lane::V1)[0].link,
19069 Some(take),
19070 "the take's id is back, not a fresh one"
19071 );
19072 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
19073 invariants_hold(&p, "regroup across three lanes");
19074 }
19075
19076 /// A group is one placement per lane, on however many lanes carry the id --
19077 /// not a video/audio pair and not a pairing by `ord` -- and the members may
19078 /// cover whatever frames they cover: the offset between them is what a
19079 /// hand-built group keeps. Lanes built by hand, because the rule is checked
19080 /// at the untrusted door and no edit can produce the one thing it refuses.
19081 #[test]
19082 fn a_group_may_span_any_lane() {
19083 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
19084 let one = |start: u32, end: u32, link| Clip {
19085 speed_keys: Vec::new(),
19086 reversed: false,
19087 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
19088 angle: Default::default(),
19089 fade_in: 0,
19090 fade_out: 0,
19091 transition_out: 0,
19092 transition_kind: Default::default(),
19093 visualizer: 0,
19094 viz_paint: 0,
19095 gain_db: 0.0,
19096 gain_keys: Vec::new(),
19097 pan: 0,
19098 pitch: 0,
19099 transform_keys: Vec::new(),
19100 opacity_keys: Vec::new(),
19101 color_keys: Vec::new(),
19102 effects: Vec::new(),
19103 start,
19104 in_frame: start,
19105 out_frame: end,
19106 source: 0,
19107 link: Some(link),
19108 eq: None,
19109 color: None,
19110 transform: None,
19111 fit: FitPolicy::default(),
19112 speed: Speed::NORMAL,
19113 };
19114 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
19115 let kinds = [
19116 LaneKind::Video,
19117 LaneKind::Audio,
19118 LaneKind::Video,
19119 LaneKind::Audio,
19120 ];
19121 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
19122 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
19123 };
19124 let take = || vec![one(0, 4, 7)];
19125 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
19126 // The same take on V1 + A2 only, the lanes between it empty: legal, the
19127 // way a lifted half is legal.
19128 let across = build([take(), Vec::new(), Vec::new(), take()]);
19129 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
19130 // ...and so is a group whose members disagree about their spans: the
19131 // offset between them is the hand's business, not the loader's.
19132 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
19133 assert!(
19134 links_are_consistent(&apart).is_ok(),
19135 "[0, 4) on V1 and [2, 6) on A2 are one group"
19136 );
19137 // One id twice in one lane is still that lane's error, by name.
19138 let twice = build([
19139 Vec::new(),
19140 Vec::new(),
19141 vec![one(0, 4, 7), one(4, 8, 7)],
19142 Vec::new(),
19143 ]);
19144 assert_eq!(
19145 links_are_consistent(&twice).unwrap_err().to_string(),
19146 "link 7 names two clips in the V2 lane"
19147 );
19148 }
19149
19150 /// Every lane a save writes comes out, in display order and with its kind --
19151 /// an empty one included, since it is state a front-end shows -- and a
19152 /// two-lane project still writes exactly the parts it always did.
19153 #[test]
19154 fn a_save_writes_every_lane_it_has() {
19155 let mut p = three();
19156 let before = p.without_orphan_sources();
19157 assert_eq!(before.1.len(), 2, "V1 and A1");
19158 let v2 = p.add_lane(LaneKind::Video);
19159 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
19160 let a2 = p.add_lane(LaneKind::Audio);
19161 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
19162 assert_eq!(
19163 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
19164 [
19165 LaneKind::Video,
19166 LaneKind::Audio,
19167 LaneKind::Video,
19168 LaneKind::Audio
19169 ],
19170 "display order, not video-then-audio"
19171 );
19172 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
19173 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
19174 // ...and all four load again as the same four.
19175 let back =
19176 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
19177 assert_eq!(back.lanes(), p.lanes());
19178 assert_eq!(back.lane(a2), p.lane(a2));
19179
19180 // Taking the lanes back leaves exactly what a two-lane save wrote.
19181 for _ in 0..3 {
19182 assert!(p.undo());
19183 }
19184 assert_eq!(
19185 p.without_orphan_sources(),
19186 before,
19187 "byte for byte the same parts a two-lane save always wrote"
19188 );
19189 }
19190
19191 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
19192 /// three lanes and grows more: every lane's own order and the one
19193 /// span-per-id rule after every op, *and* the reload the v4 format restored
19194 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
19195 /// project of any number of lanes.
19196 #[test]
19197 fn random_edit_sequences_keep_many_lanes_consistent() {
19198 for seed in 0..2000u64 {
19199 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
19200 let mut next = move |n: u32| {
19201 rng ^= rng << 13;
19202 rng ^= rng >> 7;
19203 rng ^= rng << 17;
19204 (rng >> 33) as u32 % n
19205 };
19206 let mut p = Project::single(FILE, 40);
19207 let v2 = p.add_lane(LaneKind::Video);
19208 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
19209 let lanes = [Lane::V1, Lane::A1, v2];
19210 for step in 0..24 {
19211 let frame = next(44);
19212 let copied = p
19213 .lane(lanes[next(3) as usize])
19214 .get(next(4) as usize)
19215 .cloned()
19216 .unwrap_or_else(|| clip(0, 0, 5, 0));
19217 let lane = lanes[next(3) as usize];
19218 let idx = next(4) as usize;
19219 let _ = match next(14) {
19220 // The drag, in the mix: a clip dragged along its own lane
19221 // and onto another one, at a frame the pointer picked --
19222 // which is where the group rule and the sorted+disjoint one
19223 // meet, since every half travels the same distance.
19224 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
19225 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
19226 11 => p.set_eq(lane, idx, None),
19227 // A rate, which on many lanes is the group rule as well:
19228 // every clip carrying the link moves together or none of
19229 // them does, and `invariants_hold` is what says so.
19230 12 => p
19231 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
19232 .is_ok(),
19233 0 => p.split(frame),
19234 1 => p.regroup(frame),
19235 2 => p.lift(lane, idx),
19236 3 => p.place(lane, frame, copied.clone()),
19237 4 => p.paste(frame, copied.clone()),
19238 5 => p.ripple_delete(frame, next(9)),
19239 6 => p.delete(idx),
19240 7 => p.undo(),
19241 8 => {
19242 p.add_lane(if next(2) == 0 {
19243 LaneKind::Video
19244 } else {
19245 LaneKind::Audio
19246 });
19247 true
19248 }
19249 _ => p.append_clip(0, 1 + next(9)),
19250 };
19251 invariants_hold(&p, &format!("seed {seed}, step {step}"));
19252 reloads(&p, &format!("seed {seed}, step {step}"));
19253 }
19254 }
19255 }
19256
19257 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
19258 /// there, `V1` shows again on either side of it, and a frame no video lane
19259 /// covers is a gap however many lanes there are.
19260 #[test]
19261 fn the_composite_is_the_topmost_lane_with_a_clip() {
19262 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19263 let lanes = vec![
19264 // V1: the whole 30 frames of source 0.
19265 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19266 // V2: source 1 over the middle third.
19267 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
19268 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19269 ];
19270 let p =
19271 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
19272 assert_eq!(
19273 p.composite_spans_from(0),
19274 vec![
19275 Span {
19276 reverse: false,
19277 ramp: None,
19278 start: 0,
19279 len: 10,
19280 from: Some((0, 0)),
19281 speed: Speed::NORMAL,
19282 pitch: 0,
19283 },
19284 Span {
19285 reverse: false,
19286 ramp: None,
19287 start: 10,
19288 len: 10,
19289 from: Some((1, 5)),
19290 speed: Speed::NORMAL,
19291 pitch: 0,
19292 },
19293 Span {
19294 reverse: false,
19295 ramp: None,
19296 start: 20,
19297 len: 10,
19298 from: Some((0, 20)),
19299 speed: Speed::NORMAL,
19300 pitch: 0,
19301 },
19302 ],
19303 "V2 takes over for its own span and hands V1 back"
19304 );
19305 // A mid-span ask resolves the same way, which is what a seek does.
19306 assert_eq!(
19307 p.composite_span_at(15),
19308 Some(Span {
19309 reverse: false,
19310 ramp: None,
19311 start: 15,
19312 len: 5,
19313 from: Some((1, 10)),
19314 speed: Speed::NORMAL,
19315 pitch: 0,
19316 })
19317 );
19318 assert_eq!(p.composite_span_at(30), None, "past the end");
19319
19320 // A hole in V1 under V2's clip: black between the two, and black after
19321 // both run out (the audio lane is still holding the timeline open).
19322 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19323 let holed = vec![
19324 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
19325 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
19326 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19327 ];
19328 let p =
19329 Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
19330 assert_eq!(
19331 p.composite_spans_from(0),
19332 vec![
19333 Span {
19334 reverse: false,
19335 ramp: None,
19336 start: 0,
19337 len: 5,
19338 from: Some((0, 0)),
19339 speed: Speed::NORMAL,
19340 pitch: 0,
19341 },
19342 Span {
19343 reverse: false,
19344 ramp: None,
19345 start: 5,
19346 len: 5,
19347 from: None,
19348 speed: Speed::NORMAL,
19349 pitch: 0,
19350 },
19351 Span {
19352 reverse: false,
19353 ramp: None,
19354 start: 10,
19355 len: 10,
19356 from: Some((1, 0)),
19357 speed: Speed::NORMAL,
19358 pitch: 0,
19359 },
19360 Span {
19361 reverse: false,
19362 ramp: None,
19363 start: 20,
19364 len: 10,
19365 from: None,
19366 speed: Speed::NORMAL,
19367 pitch: 0,
19368 },
19369 ]
19370 );
19371
19372 // One video lane: the composite *is* that lane, span for span -- the
19373 // promise every existing two-lane project rests on.
19374 let p = Project::single(FILE, 30);
19375 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
19376 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
19377 }
19378
19379 /// Every audio lane holding something gets a play list, and only those.
19380 #[test]
19381 fn audio_segments_cover_every_lane_that_holds_something() {
19382 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19383 let lanes = vec![
19384 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19385 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19386 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
19387 (LaneKind::Audio, Vec::new()),
19388 ];
19389 let p =
19390 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
19391 let lists = p.audio_segments_from(0, FPS);
19392 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
19393 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
19394 // A2 is a gap up to frame 15, then the whole of source 1.
19395 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
19396
19397 // No audio lane holds anything: one all-gap list, so such a timeline
19398 // still plays silence against a master clock.
19399 let p = Project::from_parts(
19400 vec![Source::new(FILE, 0)],
19401 vec![
19402 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19403 (LaneKind::Audio, Vec::new()),
19404 ],
19405 vec![],
19406 vec![],
19407 Vec::new(),
19408 )
19409 .expect("valid parts");
19410 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
19411 }
19412
19413 /// D4: removing a subtitle column used to clear the whole undo history,
19414 /// because a placement names its track by index into the palette and the
19415 /// reindex left every later entry naming the wrong one. The entry holds the
19416 /// palette beside the lanes now, so the reindex undoes with it.
19417 #[test]
19418 fn removing_a_subtitle_column_undoes_with_its_reindex() {
19419 let track = |label: &str| SubtitleTrack {
19420 path: FILE.into(),
19421 track: None,
19422 language: "eng".into(),
19423 name: String::new(),
19424 label: label.into(),
19425 cues: Vec::new(),
19426 bitmap: false,
19427 refused: None,
19428 };
19429 let mut p = Project::single(FILE, 300).with_subtitles(vec![
19430 track("one"),
19431 track("two"),
19432 track("three"),
19433 ]);
19434 assert_eq!(p.subtitles().len(), 3);
19435 let before = p.parts();
19436 let palette = p.subtitles().to_vec();
19437 // Column 0 goes, which renumbers the two behind it.
19438 p.remove_subtitles(0).expect("a column with nothing on it");
19439 assert_eq!(p.subtitles().len(), 2);
19440 assert_eq!(p.subtitles()[0].label, "two");
19441 assert!(p.undo(), "the removal is a step like any other cut");
19442 // The palette itself, and not only what `parts` happens to compare: this
19443 // is the assertion that cannot go vacuous if the restore below it ever
19444 // leaves a field of it behind.
19445 assert_eq!(
19446 p.subtitles(),
19447 palette.as_slice(),
19448 "the palette itself, back"
19449 );
19450 assert_eq!(p.parts(), before, "the palette and the lanes, both back");
19451 assert!(p.redo(), "and forward again");
19452 assert_eq!(p.subtitles().len(), 2, "the column goes again");
19453 assert_eq!(p.subtitles()[0].label, "two");
19454 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");
19455 }
19456
19457 /// Finds every line that **writes** a caption's clock, in three forms: an
19458 /// assignment through any operator (`.out_us = `, `.out_us += `,
19459 /// `.out_us <<= `), a struct-literal field (`out_us: ...`) and the
19460 /// shorthand form (`out_us,`). A `let` binding is skipped for the literal
19461 /// forms only, so `let x: &mut SubClip = ..; (*x).in_us = 5;` is still
19462 /// caught while `let out_us = s.out_us;` is not.
19463 ///
19464 /// The operator list is `=` plus one assignment operator each, and
19465 /// deliberately excludes `<=`: the first version of this matcher counted
19466 /// `s.out_us <= s.in_us` as a write, which would have flagged every
19467 /// never-empty check in the file.
19468 fn window_writes(text: &str) -> Vec<(usize, String)> {
19469 const FIELDS: [&str; 2] = ["in_us", "out_us"];
19470 const OPS: [&str; 11] = [
19471 "=", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "<<=", ">>=",
19472 ];
19473 let mut found = Vec::new();
19474 for (n, raw) in text.lines().enumerate() {
19475 let line = raw.trim();
19476 if line.starts_with("//") {
19477 continue;
19478 }
19479 let is_binding = line.starts_with("let ");
19480 // `let (a, b) = ..` is a tuple pattern, not a struct literal: the
19481 // commas there bind names. `let half = SubClip { frames: n, in_us,
19482 // out_us, ..s };` is the opposite -- the same commas are shorthand
19483 // fields -- and what separates them is the paren, not the `let`.
19484 let tuple_pattern = line.starts_with("let (");
19485 for field in FIELDS {
19486 let access = format!(".{field}");
19487 if let Some(at) = line.find(&access) {
19488 let after = &line[at + access.len()..];
19489 let after = after.trim_start();
19490 if OPS
19491 .iter()
19492 .any(|op| after.starts_with(op) && !after[op.len()..].starts_with('='))
19493 {
19494 found.push((n + 1, line.to_owned()));
19495 continue;
19496 }
19497 }
19498 // A bare name: a literal field, a shorthand, or a local
19499 // binding. Skipped when a `.` or an identifier character
19500 // precedes it -- that is a read, not a field being set.
19501 //
19502 // The `let` exclusion is per-occurrence and keyed on what
19503 // FOLLOWS, not on the line. `let out_us = s.out_us;` names a
19504 // local, so the `=` form is skipped; but `let tail = SubClip {
19505 // in_us: cut, out_us: s.out_us, ..s };` is a struct literal
19506 // behind a `let`, and an earlier version of this matcher
19507 // skipped the whole line for being a `let` -- so that shape,
19508 // which is exactly what a plausible composer looks like, went
19509 // through green. Keyed on the follower, a `let` hides nothing.
19510 for (at, _) in line.match_indices(field) {
19511 let preceded_by_name = line[..at]
19512 .chars()
19513 .next_back()
19514 .is_some_and(|c| c == '.' || c.is_alphanumeric() || c == '_');
19515 if preceded_by_name {
19516 continue;
19517 }
19518 let after = line[at + field.len()..].trim_start();
19519 let sets_a_field =
19520 after.starts_with(':') || (after.starts_with(',') && !tuple_pattern);
19521 let names_a_local = after.starts_with('=') && !after[1..].starts_with('=');
19522 if sets_a_field || (names_a_local && !is_binding) {
19523 found.push((n + 1, line.to_owned()));
19524 break;
19525 }
19526 }
19527 }
19528 }
19529 found
19530 }
19531
19532 /// A **heuristic guard**, not a proof. The honest reading of a green here
19533 /// is the residual risk in this comment, not the green itself.
19534 ///
19535 /// Three rounds of review each found one more composer a per-arm check had
19536 /// missed -- a tail trim, a head trim, a rejoin that SUMS two legal
19537 /// widths -- and each produced the same failure: the editor wrote a
19538 /// `.edith` its own loader then refused, with no in-app way back. The
19539 /// invariant is now structural in the code (every composer calls
19540 /// [`set_window`]); this is what keeps that structure from quietly losing
19541 /// a caller.
19542 ///
19543 /// **Why this is a scan and not the compiler**, which is the better answer
19544 /// and was priced rather than skipped: making `in_us`/`out_us` private to
19545 /// this module turns every outside write into a compile error, which no
19546 /// one-token edit can defeat. It costs 74 `SubClip` construction sites
19547 /// (31 of them in this crate's own integration tests) plus a public
19548 /// constructor, and it reaches `crates/app`'s `timeline_edit.rs` and
19549 /// `timeline_math.rs`, which other lanes own. That is a refactor of a
19550 /// door's public shape rather than a bound, and the wrong size for this
19551 /// lane -- so the guard stands here with its limits written down instead.
19552 ///
19553 /// **Residual risk, by class, most likely first.** These are not all
19554 /// equally hypothetical; the first is the one a real composer would reach
19555 /// for, and it is the one this matcher cannot see at all:
19556 ///
19557 /// 1. **Field-less writes.** `*a = *b;`, `*a = other;`,
19558 /// `std::mem::swap(a, b)`, `a.clone_from(b)`, and any macro that
19559 /// expands to a field write (`bump!(s.out_us, by)`). None of these ever
19560 /// spell `in_us` or `out_us` on the line, so `window_writes` returns
19561 /// nothing for all of them. A *helper* that writes the field directly IS
19562 /// caught; it is specifically the whole-struct and macro forms that go
19563 /// through. This is the class most likely to be used, and it is
19564 /// unmatched by construction rather than by oversight.
19565 /// 2. **A rename.** The matcher keys on the literal strings `in_us` and
19566 /// `out_us`. Renaming the fields silences it entirely while it stays
19567 /// green -- the sharpest failure here, because the guard is supposed to
19568 /// be the thing that notices a rule drifting.
19569 /// 3. **A writer inside a test.** `/tests/` paths and `mod tests` blocks
19570 /// are cut. A test cannot produce a file a user loses, so the line is
19571 /// drawn there deliberately, not by omission.
19572 /// 4. **A file the walk does not reach**: a path outside `crates/`, or one
19573 /// under a directory named `target`, `.git`, `vendor`, or any
19574 /// dot-directory (`.delta/` holds scratch clones of other checkouts).
19575 ///
19576 /// What the matcher DOES now cover, after four rounds of it not doing so:
19577 /// every assignment operator; struct-literal fields and the shorthand form,
19578 /// including behind a `let`; writes through an indirect `&mut`; and every
19579 /// `.rs` under `crates/` with no filter on what the file contains, so a
19580 /// glob import or a type alias can no longer hide a module.
19581 #[test]
19582 fn every_window_write_outside_set_window_is_named() {
19583 // `CARGO_MANIFEST_DIR`, not `file!()`: a test runs with the WORKSPACE
19584 // root as its working directory, so `file!()`'s crate-relative path
19585 // does not resolve from where the binary actually starts.
19586 let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19587 .parent()
19588 .and_then(std::path::Path::parent)
19589 .expect("crates/engine sits two levels under the workspace root")
19590 .to_path_buf();
19591 // Every line in the workspace that names a clock and is not a
19592 // composer, each with its reason. A new entry is a claim someone has
19593 // to defend in review, which is the point of writing the list out.
19594 let allowed = [
19595 ("pub in_us: i64,", "the field declaration"),
19596 ("pub out_us: i64,", "the field declaration"),
19597 (
19598 "fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {",
19599 "set_window's own signature",
19600 ),
19601 ("s.in_us = in_us;", "set_window"),
19602 ("s.out_us = out_us;", "set_window"),
19603 (
19604 "set_window(&mut data.subs[idx], in_us, out_us);",
19605 "regroup naming the two values it is about to set",
19606 ),
19607 ("in_us: micros(f[3], n)?,", "edith.rs: the parse door"),
19608 ("out_us: micros(f[4], n)?,", "edith.rs: the parse door"),
19609 // Non-test helpers that build a value to hand `place_sub`, which is
19610 // a door. Not composers: nobody was mid-gesture, which is exactly
19611 // why a door refuses where a composer clamps.
19612 (
19613 "in_us: 0,",
19614 "sweep.rs caption helper, and timeline_edit.rs's palette row, -> place_sub",
19615 ),
19616 (
19617 "out_us: i64::from(frames) * 1_000_000,",
19618 "sweep.rs caption helper -> place_sub",
19619 ),
19620 // `SubClip::whole_track`: the one constructor a palette drop uses; its
19621 // window is the frames' own length, and the value goes to place_sub.
19622 (
19623 "SubClip { start: 0, frames, track, in_us: 0, out_us, link: None }",
19624 "SubClip::whole_track: whole-track value -> place_sub",
19625 ),
19626 ];
19627
19628 let mut found: Vec<String> = Vec::new();
19629 let (mut files, mut lines) = (0usize, 0usize);
19630 let mut seen_app = false;
19631 for (file, text) in read_workspace_rust(&workspace) {
19632 // Test code, by path or by module: a test builds `SubClip`s by hand
19633 // and its value is not one the loader ever reads, so the 31 sites in
19634 // `crates/engine/tests/` and three in `crates/app/src/tests/` are
19635 // not composers. A real limit rather than a technicality -- the
19636 // guard does not cover a writer hidden inside a test -- but a test
19637 // cannot produce a file a user loses, so it is where the line goes.
19638 let path = file.to_string_lossy().replace('\\', "/");
19639 if path.contains("/tests/") {
19640 continue;
19641 }
19642 let code = match text.find("\n#[cfg(test)]\nmod tests {") {
19643 Some(at) => &text[..at],
19644 None => text.as_str(),
19645 };
19646 lines += code.lines().count();
19647 files += 1;
19648 seen_app |= path.contains("crates/app/");
19649 for (n, line) in window_writes(code) {
19650 if !allowed.iter().any(|(text, _)| *text == line) {
19651 let at = file.strip_prefix(&workspace).unwrap_or(&file);
19652 found.push(format!("{}:{n}: {line}", at.display()));
19653 }
19654 }
19655 }
19656 // A floor, not a census: the walk now opens EVERY `.rs` under
19657 // `crates/` that is not test code -- 86 files and ~77,600 lines today,
19658 // which is 141 files and ~116,000 before `/tests/` and `mod tests` are
19659 // cut. The point is only to catch a walk rooted in the wrong place,
19660 // which reads a file or two.
19661 // The `seen_app` half is the one that matters: the two-file version of
19662 // this guard read `project.rs` and `edith.rs` and was silently
19663 // certifying a claim about the app it had never opened, and the
19664 // `contains("SubClip")` filter that came next
19665 // was the same mistake wearing a derived hat -- a file that reached
19666 // the type by glob import or alias was never opened either.
19667 assert!(
19668 lines > 70_000 && files >= 80 && seen_app,
19669 "the walk read {lines} lines in {files} files (app reached: \
19670 {seen_app}) -- it is not covering the workspace, and a guard that \
19671 reads nothing is worse than no guard because it reads as one"
19672 );
19673 // The assertion this whole test exists for. It was DELETED by a clumsy
19674 // edit while the coverage floor above was being retuned, and for a
19675 // moment the test reported green while `found` held a real offender --
19676 // the fourth version of this guard failing in the one way that looks
19677 // exactly like success. If you retune anything here, check this line
19678 // still exists.
19679 assert!(
19680 found.is_empty(),
19681 "a caption window is written outside set_window:\n {}",
19682 found.join("\n ")
19683 );
19684 }
19685
19686 /// The blind spot, pinned as cases. Every one of these is a write, and the
19687 /// guard exists because each of its earlier versions caught none of them --
19688 /// `s.out_us += by(...)` being a one-token edit that made it green while a
19689 /// grouped caption really did grow past the ceiling. A matcher that has
19690 /// quietly stopped matching is the failure mode that looks most like a
19691 /// pass, so it gets its own test rather than a comment.
19692 ///
19693 /// The last group is the opposite: the field-less forms that are a write
19694 /// and that this matcher CANNOT see. They are asserted to be missed, on
19695 /// purpose, so that the day someone can match them the test says so --
19696 /// and so nobody reads this file as claiming more than it does.
19697 #[test]
19698 fn the_window_write_matcher_catches_the_ways_a_composer_hides() {
19699 for (what, code) in [
19700 (
19701 "the one-token compound assignment",
19702 " s.out_us += by(s.end(), to);",
19703 ),
19704 ("a plain compound assignment", " s.in_us -= 1;"),
19705 ("a shift-assign", " s.out_us <<= 1;"),
19706 (
19707 "a write through a &mut the matcher cannot see past",
19708 " let x: &mut SubClip = q; (*x).in_us = 5;",
19709 ),
19710 (
19711 "a struct literal",
19712 " out.push(SubClip { in_us: 0, out_us: 1, ..s });",
19713 ),
19714 (
19715 "the shorthand form",
19716 " SubClip { in_us, out_us, ..s }",
19717 ),
19718 (
19719 "a struct literal behind a `let`, which the old line-wide `let` \
19720 exclusion skipped whole",
19721 " let tail = SubClip { in_us: cut, out_us: s.out_us, ..s };",
19722 ),
19723 (
19724 "a struct literal behind a `let` using the shorthand too",
19725 " let half = SubClip { frames: n, in_us, out_us, ..s };",
19726 ),
19727 ] {
19728 assert!(
19729 !window_writes(code).is_empty(),
19730 "the matcher misses {what}: {code:?}"
19731 );
19732 }
19733 // ...and the other side, so the allowlist is not padded with reads.
19734 for quiet in [
19735 " if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {",
19736 " debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);",
19737 " let out_us = s.out_us;",
19738 " (next.start == frame && next.in_us == subs[idx].out_us)",
19739 " let total = s.out_us - s.in_us;",
19740 ] {
19741 assert!(
19742 window_writes(quiet).is_empty(),
19743 "the matcher flags a read as a write: {quiet:?}"
19744 );
19745 }
19746 // The class this matcher CANNOT see, asserted as missed. Each of these
19747 // really does write a caption's window and none of them spell the field
19748 // name, so a field matcher returns nothing -- that is a property of the
19749 // approach, not a bug to be fixed here, and the test exists so the
19750 // doc comment's residual-risk list cannot quietly grow a claim this
19751 // matcher has not earned. If one of these ever starts matching, this
19752 // test fails and asks which side of the line moved.
19753 for unmatchable in [
19754 " *a = *b;",
19755 " *a = other;",
19756 " std::mem::swap(a, b);",
19757 " a.clone_from(b);",
19758 " bump!(s.out_us, by);",
19759 ] {
19760 assert!(
19761 window_writes(unmatchable).is_empty(),
19762 "the matcher now matches a field-less form it documented as \
19763 unmatched -- update the residual-risk list too: {unmatchable:?}"
19764 );
19765 }
19766 }
19767
19768 /// Every `.rs` under the workspace, paired with its text. Recursive
19769 /// because the set of files that can name `SubClip` is a fact about the
19770 /// tree, and a hardcoded pair of names goes stale the moment a lane adds a
19771 /// module -- which is how the two-file version of this guard came to
19772 /// certify a claim about `crates/app` it had never read.
19773 fn read_workspace_rust(root: &std::path::Path) -> Vec<(std::path::PathBuf, String)> {
19774 let mut out = Vec::new();
19775 let mut stack = vec![root.to_path_buf()];
19776 while let Some(dir) = stack.pop() {
19777 let Ok(entries) = std::fs::read_dir(&dir) else {
19778 continue;
19779 };
19780 for entry in entries.flatten() {
19781 let path = entry.path();
19782 if path.is_dir() {
19783 // `target` is not source and `vendor` is not ours to rule on.
19784 //
19785 // Every DOT-directory, for the same reason and one more: a
19786 // dot-dir is by convention not part of the tree we are
19787 // making claims about. This workspace root holds `.delta/`,
19788 // a scratch area of clones and worktrees left by delta/A-B
19789 // tooling, and the walk used to descend into it and report
19790 // the ten window writes inside a checkout that is not this
19791 // one -- so the guard was RED here for a file nobody edits,
19792 // and, worse, VACUOUS about its own tree: the same stale
19793 // clone that produced the noise could have hidden a real
19794 // offender behind it, and the floor below was being met in
19795 // part by lines this guard has no business reading. Skipping
19796 // the whole class rather than naming `.delta` is the point:
19797 // the next scratch dir a tool drops here is skipped too.
19798 let name = path.file_name().unwrap_or_default().to_string_lossy();
19799 let skip = name == "target"
19800 || name == ".git"
19801 || name == "vendor"
19802 || name.starts_with('.');
19803 if !skip {
19804 stack.push(path);
19805 }
19806 // EVERY `.rs`, with no filter on what it contains. The filter
19807 // that was here (`text.contains("SubClip")`) was a name-based
19808 // guess about which files can reach the type, and a glob import
19809 // or a type alias defeats it exactly as it defeats a
19810 // hardcoded file list: a new module holding the struct behind
19811 // `use engine::project::*;` was never opened, and stayed green.
19812 // The scan is text-only and the tree is small, so the honest
19813 // thing costs nothing here.
19814 } else if path.extension().is_some_and(|e| e == "rs")
19815 && let Ok(text) = std::fs::read_to_string(&path)
19816 {
19817 out.push((path, text));
19818 }
19819 }
19820 }
19821 out
19822 }
19823}
19824
19825#[cfg(test)]
19826mod title_tests {
19827 use super::*;
19828 use crate::text::{Outline, Place};
19829
19830 const FILE: &str = "/nonexistent/film.mkv";
19831
19832 fn title(start: u32, frames: u32, text: &str) -> Title {
19833 Title {
19834 start,
19835 frames,
19836 text: text.to_string(),
19837 style: TextStyle::default(),
19838 fade_in: 0,
19839 fade_out: 0,
19840 in_anim: Default::default(),
19841 out_anim: Default::default(),
19842 anim_frames: 0,
19843 keys: Vec::new(),
19844 }
19845 }
19846
19847 /// Going from 30 to 25 fps keeps the seconds: a title that shows for two
19848 /// seconds still shows for two (50 frames, not the 60 it was stored as),
19849 /// and every frame-counted envelope -- title fades, clip fades, the dissolve
19850 /// into the next clip, a volume point -- lands on the same moment of the
19851 /// new grid as the picture it belongs to.
19852 #[test]
19853 fn a_rate_change_rescales_titles_and_frame_envelopes() {
19854 let k = Rate::from_fps(30.0, 25.0).expect("a rate both grids name");
19855 let mut p = Project::single(FILE, 300);
19856 assert!(p.split(150));
19857 assert!(p.set_fade_in(Lane::A1, 0, 30));
19858 assert!(p.set_fade_out(Lane::A1, 0, 30));
19859 assert!(p.set_transition_out(Lane::V1, 0, 30));
19860 assert!(p.set_gain_keys(
19861 Lane::A1,
19862 0,
19863 vec![
19864 GainKey::new(60, -6.0),
19865 GainKey::new(120, -3.0),
19866 ],
19867 ));
19868 assert!(p.add_title(Title { fade_in: 0, fade_out: 12, ..title(0, 60, "Intro") }).is_ok());
19869 assert!(p.add_title(Title { fade_in: 12, fade_out: 0, ..title(90, 60, "Credit") }).is_ok());
19870
19871 p.retime(k, &[250]);
19872
19873 let t = p.titles();
19874 assert_eq!((t[0].start, t[0].frames, t[0].fade_out), (0, 50, 10));
19875 assert_eq!((t[1].start, t[1].frames, t[1].fade_in), (75, 50, 10));
19876 assert_eq!(t[0].frames * 6, 60 * 5, "the two seconds stay two seconds");
19877
19878 let a = p.lane(Lane::A1);
19879 assert_eq!((a[0].fade_in, a[0].fade_out), (25, 25));
19880 assert_eq!(p.lane(Lane::V1)[0].transition_out, 25);
19881 let keys: Vec<u32> = a[0].gain_keys.iter().map(|g| g.at).collect();
19882 assert_eq!(keys, [50, 100], "volume points follow their footage");
19883 }
19884
19885 #[test]
19886 fn title_add_set_remove_and_undo_redo() {
19887 let mut p = Project::single(FILE, 150);
19888 assert_eq!(p.add_title(title(160, 40, "Episode 17")).unwrap(), 0);
19889 assert_eq!(
19890 p.add_title(title(10, 20, "Intro")).unwrap(),
19891 0,
19892 "kept sorted by start"
19893 );
19894 assert_eq!(p.titles()[0].text, "Intro");
19895 assert_eq!(
19896 p.timeline_frames(),
19897 200,
19898 "a title past the clip extends the timeline"
19899 );
19900 assert_eq!(p.media_frames(), 200, "and the picture runs on over black");
19901
19902 assert!(p.undo());
19903 assert_eq!(p.titles().len(), 1);
19904 assert_eq!(p.timeline_frames(), 200);
19905 assert!(p.undo());
19906 assert!(p.titles().is_empty());
19907 assert_eq!(p.timeline_frames(), 150, "the timeline shrinks back");
19908 assert!(p.redo());
19909 assert!(p.redo());
19910 assert_eq!(p.titles().len(), 2);
19911
19912 assert!(p.remove_title(0));
19913 assert_eq!(p.titles().len(), 1);
19914 assert!(p.undo());
19915 assert_eq!(p.titles().len(), 2);
19916 assert!(!p.remove_title(9), "an index that is not there is refused");
19917
19918 let mut edited = p.titles()[1].clone();
19919 edited.text = "Episode 18".into();
19920 assert!(p.set_title(1, edited.clone()));
19921 assert!(!p.set_title(1, edited), "the same title is no edit");
19922 assert_eq!(p.titles()[1].text, "Episode 18");
19923 assert!(p.undo());
19924 assert_eq!(p.titles()[1].text, "Episode 17");
19925 }
19926
19927 #[test]
19928 fn chapter_add_set_move_remove_and_undo() {
19929 let chapter = |frame, title: &str| Chapter { frame, title: title.into() };
19930 let mut p = Project::single(FILE, 300);
19931 assert_eq!(p.add_chapter(chapter(150, "Setup")).unwrap(), 0);
19932 assert_eq!(p.add_chapter(chapter(0, "Intro")).unwrap(), 0, "kept sorted by frame");
19933 assert!(p.add_chapter(chapter(150, "Again")).is_err(), "one chapter per frame");
19934 assert!(p.add_chapter(chapter(20, " ")).is_err(), "a chapter needs a name");
19935 assert_eq!(p.chapters().len(), 2, "a refusal changes nothing");
19936
19937 assert!(p.undo());
19938 assert_eq!(p.chapters(), &[chapter(150, "Setup")], "undo takes back the last add");
19939 assert!(p.undo());
19940 assert!(p.chapters().is_empty());
19941 assert!(p.redo());
19942 assert!(p.redo());
19943
19944 assert_eq!(p.move_chapter(0, 200).unwrap(), 1, "its index follows its frame");
19945 assert_eq!(p.chapters()[1], chapter(200, "Intro"));
19946 assert!(p.move_chapter(0, 200).is_err(), "a frame another chapter holds is refused");
19947 assert!(p.move_chapter(9, 10).is_err(), "an index that is not there is refused");
19948
19949 assert!(p.set_chapter_title(0, "Begin"));
19950 assert!(!p.set_chapter_title(0, "Begin"), "the same name is no edit");
19951 assert!(!p.set_chapter_title(0, ""), "an empty name is refused");
19952 assert!(p.remove_chapter(1));
19953 assert_eq!(p.chapters(), &[chapter(150, "Begin")]);
19954 assert!(!p.remove_chapter(4), "an index that is not there is refused");
19955 assert!(p.undo());
19956 assert_eq!(p.chapters().len(), 2);
19957 assert_eq!(p.chapters()[0], chapter(150, "Begin"), "the rename is still there");
19958 assert_eq!(p.chapters()[1], chapter(200, "Intro"));
19959 }
19960
19961 #[test]
19962 fn the_caption_style_is_an_undoable_project_setting() {
19963 use crate::captionanim::{CaptionAnim, CaptionStyle};
19964 let mut p = Project::single(FILE, 9);
19965 assert_eq!(p.caption_style(), CaptionStyle::default());
19966 assert!(!p.set_caption_style(CaptionStyle::default()), "the style in force is no step");
19967 let karaoke = CaptionStyle { anim: CaptionAnim::Karaoke, words_per_line: 40, ..CaptionStyle::default() };
19968 assert!(p.set_caption_style(karaoke));
19969 assert_eq!(p.caption_style().words_per_line, crate::captionanim::MAX_WORDS_PER_LINE, "clamped");
19970 assert!(p.undo());
19971 assert_eq!(p.caption_style(), CaptionStyle::default());
19972 assert!(p.redo());
19973 assert_eq!(p.caption_style().anim, CaptionAnim::Karaoke);
19974 }
19975
19976 #[test]
19977 fn markers_add_set_remove_remap_and_undo() {
19978 let m = |frame, length, name: &str| Marker { frame, length, name: name.into(), note: String::new(), color: MarkerColor::Red };
19979 let mut p = Project::single(FILE, 9);
19980 assert_eq!(p.add_marker(m(100, 0, "B")).unwrap(), 0);
19981 assert_eq!(p.add_marker(m(10, 40, "A")).unwrap(), 0, "kept sorted by frame");
19982 assert_eq!(p.add_marker(m(100, 0, "B2")).unwrap(), 2, "a second on a frame goes after the first");
19983 assert!(p.add_marker(m(5, 0, " ")).is_err(), "a marker needs a name");
19984 assert_eq!(p.markers().len(), 3);
19985 assert!(p.undo());
19986 assert_eq!(p.markers().len(), 2, "undo takes back the last add");
19987 // A set that moves the frame re-sorts; an identical set is refused.
19988 assert_eq!(p.set_marker(0, m(200, 0, "A")).unwrap(), 1);
19989 assert!(p.set_marker(1, m(200, 0, "A")).is_err());
19990 assert!(p.set_marker(9, m(1, 0, "x")).is_err());
19991 // A remap moves a range's start and end; a ripple inside a range grows it.
19992 assert!(p.remap_markers(|f| if f >= 150 { f + 30 } else { f }));
19993 assert_eq!(p.markers()[0].frame, 100);
19994 assert_eq!(p.markers()[1].frame, 230);
19995 assert!(!p.remap_markers(|f| f), "no frame moves: no step");
19996 assert!(p.undo());
19997 assert_eq!(p.markers()[1].frame, 200, "one undo takes the whole remap back");
19998 let mut q = Project::single(FILE, 9);
19999 q.add_marker(m(10, 40, "R")).unwrap();
20000 assert!(q.remap_markers(|f| if f >= 30 { f + 100 } else { f }));
20001 assert_eq!((q.markers()[0].frame, q.markers()[0].length), (10, 140), "an insert inside a range grows it");
20002 assert!(q.remap_markers(|f| if f >= 20 { 20 } else { f }));
20003 assert_eq!(q.markers()[0].length, 10, "a cut through a range shortens it");
20004 assert!(q.remove_marker(0));
20005 assert!(!q.remove_marker(0));
20006 }
20007
20008 #[test]
20009 fn remap_chapters_is_one_undo_step_and_keeps_the_first_of_a_pair() {
20010 let mut p = Project::single(FILE, 300);
20011 p.add_chapter(Chapter { frame: 0, title: "A".into() }).unwrap();
20012 p.add_chapter(Chapter { frame: 50, title: "B".into() }).unwrap();
20013 p.add_chapter(Chapter { frame: 60, title: "C".into() }).unwrap();
20014 // C moves onto B's frame, so it is the one dropped.
20015 let dropped = p.remap_chapters(|f| if f == 60 { 50 } else { f });
20016 assert_eq!(dropped, 1);
20017 let titles: Vec<&str> = p.chapters().iter().map(|c| c.title.as_str()).collect();
20018 assert_eq!(titles, ["A", "B"]);
20019 assert!(p.undo());
20020 assert_eq!(p.chapters().len(), 3, "one undo brings back every chapter");
20021 assert_eq!(p.remap_chapters(|f| f), 0, "no frame moves: no step");
20022 assert!(p.undo());
20023 assert_eq!(p.chapters().len(), 2, "the step before was the add of C");
20024 }
20025
20026 #[test]
20027 fn title_refusals_change_nothing() {
20028 let mut p = Project::single(FILE, 150);
20029 let before = p.clone();
20030 assert!(p.add_title(title(0, 0, "none")).is_err(), "no frames");
20031 assert!(p.add_title(title(0, 10, " ")).is_err(), "no text");
20032 assert!(
20033 p.add_title(title(0, 10, &"x".repeat(MAX_TITLE_CHARS + 1)))
20034 .is_err()
20035 );
20036 assert!(
20037 p.add_title(title(MAX_TITLE_END, 10, "past")).is_err(),
20038 "past the maximum"
20039 );
20040 let mut big = title(0, 10, "size");
20041 big.style.size = 9;
20042 assert!(p.add_title(big).is_err(), "a size under the range");
20043 let mut fade = title(0, 10, "fade");
20044 fade.fade_in = 11;
20045 assert!(p.add_title(fade).is_err(), "a fade longer than the title");
20046 assert!(p.titles().is_empty());
20047 assert_eq!(p.parts(), before.parts());
20048 assert!(
20049 !p.undo() || p.titles().is_empty(),
20050 "a refusal takes no undo step"
20051 );
20052 }
20053
20054 #[test]
20055 fn title_alpha_ramps_in_and_out() {
20056 let mut t = title(10, 10, "fades");
20057 t.fade_in = 4;
20058 t.fade_out = 4;
20059 assert_eq!(t.alpha_at(9), 0, "before the title");
20060 assert_eq!(t.alpha_at(10), 51, "the first frame is one part in five");
20061 assert_eq!(t.alpha_at(13), 204);
20062 assert_eq!(t.alpha_at(14), 255, "full between the fades");
20063 assert_eq!(t.alpha_at(16), 204, "the fade-out counts off the end");
20064 assert_eq!(t.alpha_at(19), 51);
20065 assert_eq!(t.alpha_at(20), 0, "after the title");
20066 let plain = title(0, 3, "plain");
20067 assert_eq!(
20068 (0..3).map(|f| plain.alpha_at(f)).collect::<Vec<_>>(),
20069 [255, 255, 255]
20070 );
20071 }
20072
20073 #[test]
20074 fn title_style_outline_is_kept_by_the_title() {
20075 let mut t = title(0, 5, "edged");
20076 t.style.outline = Outline::Thick;
20077 t.style.place = Place::Top;
20078 let mut p = Project::single(FILE, 150);
20079 p.add_title(t.clone()).unwrap();
20080 assert_eq!(p.titles()[0], t);
20081 }
20082}
20083
20084#[cfg(test)]
20085mod speed_ramp_tests {
20086 use super::*;
20087
20088 const FILE: &str = "/nonexistent/a.mp4";
20089
20090 fn key(at: u32, permille: u16) -> SpeedKey {
20091 SpeedKey {
20092 at,
20093 speed: Speed::from_permille(permille),
20094 }
20095 }
20096
20097 /// The 1x-to-2x ramp over 60 frames of the brief.
20098 fn ramp() -> Vec<SpeedKey> {
20099 vec![key(0, 1000), key(60, 2000)]
20100 }
20101
20102 #[test]
20103 fn the_integral_of_a_one_to_two_ramp_over_sixty_frames_covers_ninety() {
20104 let keys = ramp();
20105 assert!((ramp_source_at(&keys, 60.) - 90.).abs() < 1e-9);
20106 // The midpoint: 30 frames at ~1.25x average to 37.5 of source.
20107 assert!((ramp_source_at(&keys, 30.) - 37.5).abs() < 1e-9);
20108 // Held at 2x past the last key: 90 + 2 * 10.
20109 assert!((ramp_source_at(&keys, 70.) - 110.).abs() < 1e-9);
20110 // Held at 1x before the first key.
20111 assert!((ramp_source_at(&[key(10, 1000), key(20, 2000)], 5.) - 5.).abs() < 1e-9);
20112 }
20113
20114 #[test]
20115 fn a_ramp_of_ninety_source_frames_is_sixty_timeline_frames() {
20116 assert_eq!(ramp_frames(&ramp(), 90), 60);
20117 // Constant keys are the constant speed, to the frame.
20118 for permille in [250u16, 500, 1000, 1500, 4000] {
20119 let flat = [key(0, permille)];
20120 for len in [1u32, 7, 90, 301] {
20121 assert_eq!(ramp_frames(&flat, len), Speed::from_permille(permille).frames(len), "{permille} over {len}");
20122 }
20123 }
20124 // Never zero, even for a source frame at the fastest speed.
20125 assert_eq!(ramp_frames(&[key(0, 4000), key(1, 4000)], 1), 1);
20126 }
20127
20128 #[test]
20129 fn source_pos_is_the_integral_and_constant_speed_is_bit_identical() {
20130 let mut p = Project::single(FILE, 90);
20131 let lane = Lane::V1;
20132 let clip = p.lane(lane)[0].clone();
20133 // An unramped clip maps exactly as the constant speed always did.
20134 for t in 0..=clip.frames() {
20135 let want = clip.in_frame + clip.speed.source_at(t);
20136 assert_eq!(source_pos(&clip, t).floor() as u32, want, "frame {t}");
20137 assert_eq!(source_pos(&clip, t).fract(), 0.0);
20138 }
20139 p.set_speed_ramp(lane, 0, &ramp()).expect("the ramp sets");
20140 let clip = p.lane(lane)[0].clone();
20141 assert_eq!(clip.frames(), 60, "the ramp's footprint");
20142 assert!((source_pos(&clip, 30) - 37.5).abs() < 1e-9);
20143 assert_eq!(source_frame(&clip, 30), 37, "the midpoint shows source frame 37");
20144 assert_eq!(source_frame(&clip, 59), 88, "the last frame shows the ramp's end");
20145 }
20146
20147 #[test]
20148 fn a_ramp_span_maps_both_ways_and_reads_real_time_for_its_field() {
20149 let mut p = Project::single(FILE, 90);
20150 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20151 let span = p.span_at(Lane::V1, 0).expect("a span");
20152 assert_eq!(span.len, 60);
20153 assert_eq!(span.speed, Speed::NORMAL, "a ramped span has no constant rate");
20154 assert_eq!(span.source_offset(30), 37, "offset 30 is source frame 37");
20155 // The last timeline frame shows source 88, as a constant 2x would stop short
20156 // of the file's last frame: 89 frames are read, the same rule as a constant speed.
20157 assert_eq!(span.source_len(), 89, "the span reads up to its last frame's source");
20158 for s in 0..90 {
20159 let t = span.timeline_at(s);
20160 assert!(span.source_offset(t) >= s, "source {s} is shown by timeline {t}");
20161 assert!(t == 0 || span.source_offset(t - 1) < s, "and not before it: {s}");
20162 }
20163 // A span from the middle of the clip is based there.
20164 let mid = p.span_at(Lane::V1, 30).expect("a span");
20165 assert_eq!(mid.from, Some((0, 37)));
20166 // S(40) - S(30) in floors: 53 - 37.
20167 assert_eq!(mid.source_offset(10), 16, "ten frames on from the midpoint");
20168 }
20169
20170 #[test]
20171 fn a_ramp_is_saved_undone_and_cleared_as_one_step_each() {
20172 let mut p = Project::single(FILE, 90);
20173 let before = p.lane(Lane::V1)[0].clone();
20174 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20175 assert_eq!(p.lane(Lane::V1)[0].speed_keys, ramp());
20176 assert!(p.undo(), "one undo step");
20177 assert_eq!(p.lane(Lane::V1)[0], before, "undo restores the constant clip");
20178 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets again");
20179 p.set_speed_ramp(Lane::V1, 0, &[]).expect("clears");
20180 assert_eq!(p.lane(Lane::V1)[0].frames(), 90, "a cleared ramp is real time");
20181 }
20182
20183 #[test]
20184 fn a_ramp_refuses_a_bad_key_list_and_a_constant_speed_on_top() {
20185 let mut p = Project::single(FILE, 90);
20186 assert!(p.set_speed_ramp(Lane::V1, 0, &[key(5, 1000), key(5, 2000)]).is_err());
20187 assert!(p.set_speed_ramp(Lane::V1, 0, &[key(9, 1000), key(3, 2000)]).is_err());
20188 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20189 assert!(p.set_speed(Lane::V1, 0, Speed::from_permille(2000)).is_err(), "clear the ramp first");
20190 assert!(p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 5).is_none());
20191 // A ramp cuts where it lands on a whole source frame: at 30 the halves are 38 and 52.
20192 assert!(p.split(30), "a ramp cuts at a whole frame");
20193 let clips = p.lane(Lane::V1);
20194 assert_eq!((clips.len(), clips[0].frames(), clips[1].start, clips[1].end()), (2, 30, 30, 60));
20195 assert!(clips.iter().all(|c| !c.speed_keys.is_empty()), "both halves keep the ramp");
20196 }
20197
20198 #[test]
20199 fn a_tail_trim_of_a_ramp_refits_its_keys_and_a_head_trim_is_refused() {
20200 let mut p = Project::single(FILE, 90);
20201 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20202 let clip = p.lane(Lane::V1)[0].clone();
20203 // The largest source length whose ramp footprint is at most 30 frames.
20204 let fit = clip.fit_source(30).expect("some of it fits");
20205 assert!(ramp_frames(&ramp(), fit) <= 30 && ramp_frames(&ramp(), fit + 1) > 30, "fit {fit}");
20206 assert_eq!(clip.fit_source(0), None);
20207 assert!(!p.trim(Lane::V1, 0, Edge::Start, 10, &[90]), "a head trim of a ramp is refused");
20208 assert_eq!(p.lane(Lane::V1)[0], clip, "and changes nothing");
20209 }
20210
20211 #[test]
20212 fn ramp_keys_from_rebases_a_tail_at_the_cut() {
20213 let keys = ramp();
20214 // Cut at 30: the speed there is 1.5x, then the key at 60 is 30 frames on.
20215 let tail = ramp_keys_from(&keys, 30);
20216 assert_eq!(tail, vec![key(0, 1500), key(30, 2000)]);
20217 assert!(valid_speed_keys(&tail));
20218 }
20219
20220 /// A ramp cuts where its own integral lands on a whole source frame, and both halves
20221 /// come back to their own lengths: 1x-to-2x over 60 frames is 90 source frames, and
20222 /// the cut at frame 30 is source 37.5, which rounds to 38.
20223 #[test]
20224 fn a_ramp_splits_into_two_halves_that_add_up() {
20225 let keys = ramp();
20226 let (src, head, tail) = ramp_split(&keys, 90, 30).expect("a whole frame at 30");
20227 assert_eq!(src, 38);
20228 assert!(valid_speed_keys(&head) && valid_speed_keys(&tail));
20229 assert_eq!(ramp_frames(&head, src), 30);
20230 assert_eq!(ramp_frames(&tail, 90 - src), 30);
20231 // Nothing at the ends, and nothing past the clip.
20232 assert!(ramp_split(&keys, 90, 0).is_none());
20233 assert!(ramp_split(&keys, 90, 60).is_none());
20234 }
20235
20236 /// A freeze on a ramp takes the nearest frame every lane can cut at: the frame itself
20237 /// when it is one, else one a few frames off, and the cut there really lands.
20238 #[test]
20239 fn a_freeze_on_a_ramp_finds_a_frame_the_ramp_can_cut_at() {
20240 let mut p = Project::single(FILE, 90);
20241 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20242 assert_eq!(p.cut_frame_near(30, 12), Some(30));
20243 let near = p.cut_frame_near(31, 12).expect("a cut within reach");
20244 assert!(near.abs_diff(31) <= 12, "{near}");
20245 assert!(p.split(near), "the frame it names is one the ramp cuts at");
20246 }
20247
20248 /// The clip-level mappings every source/timeline conversion outside the engine
20249 /// goes through: a ramp's integral and its inverses, and a constant speed's own.
20250 #[test]
20251 fn clip_mappings_follow_the_ramp_and_keep_the_constant_ones() {
20252 let mut c = Clip::source_range(0, 10, 400);
20253 c.speed_keys = vec![key(0, 1000), key(60, 2000)];
20254 // 1x to 2x over 60: source frame t + t^2/120.
20255 assert_eq!(c.source_offset(60), 90);
20256 assert_eq!(c.source_offset(30), 37);
20257 assert!((c.source_offset_f(60.0) - 90.0).abs() < 1e-9);
20258 // The ceil inverse: first timeline frame at or past a source offset.
20259 assert_eq!(c.timeline_offset(30), 25);
20260 assert_eq!(c.timeline_offset_floor(60), 43);
20261 assert!((c.timeline_offset_f(90.0) - 60.0).abs() < 1e-6);
20262 for src in [1, 17, 90, 130, 300] {
20263 let t = c.timeline_offset(src);
20264 assert!(c.source_offset(t) >= src && (t == 0 || c.source_offset(t - 1) < src), "{src}");
20265 }
20266 // A constant speed keeps its own arithmetic, bit for bit.
20267 c.speed_keys.clear();
20268 c.speed = Speed::from_permille(2000);
20269 assert_eq!(c.source_offset(30), 60);
20270 assert_eq!(c.timeline_offset(60), 30);
20271 assert_eq!(c.timeline_offset_floor(61), 30);
20272 assert!((c.timeline_offset_f(60.0) - 30.0).abs() < 1e-12);
20273 }
20274}
20275
20276#[cfg(test)]
20277mod three_point_tests {
20278 use super::*;
20279
20280 const V: &str = "/nonexistent/a.mp4";
20281
20282 /// A clip of source `source`, `in_frame..out_frame`, with the fields the tests do not look at left plain.
20283 fn take(source: usize, in_frame: u32, out_frame: u32) -> Clip {
20284 Project::single(V, 1).lane(Lane::V1)[0].clone().tap(|c| {
20285 c.source = source;
20286 c.in_frame = in_frame;
20287 c.out_frame = out_frame;
20288 c.start = 0;
20289 c.link = None;
20290 })
20291 }
20292
20293 trait Tap: Sized {
20294 fn tap(self, f: impl FnOnce(&mut Self)) -> Self;
20295 }
20296 impl Tap for Clip {
20297 fn tap(mut self, f: impl FnOnce(&mut Self)) -> Self {
20298 f(&mut self);
20299 self
20300 }
20301 }
20302
20303 /// `(start, end, in_frame, source)` of every clip on `lane`.
20304 fn spans(p: &Project, lane: Lane) -> Vec<(u32, u32, u32, usize)> {
20305 p.lane(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.source)).collect()
20306 }
20307
20308 /// A 90-frame take of source 0 on V1+A1, plus a second source (`b.mp4`) to edit in.
20309 fn bed() -> Project {
20310 let mut p = Project::single(V, 90);
20311 p.sources.push(Source::new("/nonexistent/b.mp4", 0));
20312 p
20313 }
20314
20315 fn both(source: usize, a: u32, b: u32) -> Vec<(Lane, Clip)> {
20316 vec![(Lane::V1, take(source, a, b)), (Lane::A1, take(source, a, b))]
20317 }
20318
20319 #[test]
20320 fn insert_into_the_middle_of_a_clip_splits_and_ripples() {
20321 let mut p = bed();
20322 p.edit_from_source(SourceEdit::Insert, 30, &both(1, 10, 25)).unwrap();
20323 let want = vec![(0, 30, 0, 0), (30, 45, 10, 1), (45, 105, 30, 0)];
20324 assert_eq!(spans(&p, Lane::V1), want);
20325 assert_eq!(spans(&p, Lane::A1), want);
20326 assert_eq!(p.timeline_frames(), 105);
20327 // The new take is one link; the halves of the split clip are one link each, and all differ.
20328 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
20329 for i in 0..3 {
20330 assert!(v[i].link.is_some() && v[i].link == a[i].link, "clip {i} stays a take");
20331 }
20332 assert!(v[0].link != v[1].link && v[1].link != v[2].link && v[0].link != v[2].link);
20333 assert!(links_are_consistent(&p.lanes).is_ok());
20334 }
20335
20336 #[test]
20337 fn insert_at_a_cut_and_at_zero_does_not_split() {
20338 let mut p = bed();
20339 p.edit_from_source(SourceEdit::Insert, 0, &both(1, 0, 10)).unwrap();
20340 assert_eq!(spans(&p, Lane::V1), vec![(0, 10, 0, 1), (10, 100, 0, 0)]);
20341 }
20342
20343 #[test]
20344 fn overwrite_across_two_clips_trims_and_splits_nothing_moves() {
20345 let mut p = bed();
20346 assert!(p.split(30));
20347 assert!(p.split(60));
20348 p.edit_from_source(SourceEdit::Overwrite, 20, &both(1, 0, 50)).unwrap();
20349 // 0..20 kept, 20..70 the new take, 70..90 the tail of the last clip; the clip at 30..60 is gone.
20350 let want = vec![(0, 20, 0, 0), (20, 70, 0, 1), (70, 90, 70, 0)];
20351 assert_eq!(spans(&p, Lane::V1), want);
20352 assert_eq!(spans(&p, Lane::A1), want);
20353 assert_eq!(p.timeline_frames(), 90, "nothing moved");
20354 }
20355
20356 #[test]
20357 fn overwrite_inside_one_clip_splits_it_in_three() {
20358 let mut p = bed();
20359 p.edit_from_source(SourceEdit::Overwrite, 40, &both(1, 5, 15)).unwrap();
20360 assert_eq!(spans(&p, Lane::V1), vec![(0, 40, 0, 0), (40, 50, 5, 1), (50, 90, 50, 0)]);
20361 }
20362
20363 #[test]
20364 fn overwrite_past_the_end_keeps_the_gap_and_extends_the_timeline() {
20365 let mut p = bed();
20366 p.edit_from_source(SourceEdit::Overwrite, 100, &both(1, 0, 20)).unwrap();
20367 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0), (100, 120, 0, 1)]);
20368 assert_eq!(p.timeline_frames(), 120);
20369 // An overwrite that starts inside the last clip and runs past its end.
20370 let mut p = bed();
20371 p.edit_from_source(SourceEdit::Overwrite, 80, &both(1, 0, 30)).unwrap();
20372 assert_eq!(spans(&p, Lane::V1), vec![(0, 80, 0, 0), (80, 110, 0, 1)]);
20373 }
20374
20375 #[test]
20376 fn an_insert_past_the_end_just_places() {
20377 let mut p = bed();
20378 p.edit_from_source(SourceEdit::Insert, 95, &both(1, 0, 5)).unwrap();
20379 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0), (95, 100, 0, 1)]);
20380 }
20381
20382 #[test]
20383 fn linked_takes_move_whole_and_an_untargeted_half_refuses() {
20384 let mut p = bed();
20385 // Insert on V1 alone: the take's sound on A1 would be pulled apart.
20386 let before = p.lane(Lane::V1).to_vec();
20387 let history = p.history_len();
20388 let err = p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::V1, take(1, 0, 10))]).unwrap_err();
20389 assert!(err.to_string().contains("one take with the A1 clip"), "{err}");
20390 assert_eq!(p.lane(Lane::V1), &before[..], "nothing changed");
20391 assert_eq!(p.history_len(), history, "and no undo step");
20392 // Detached, the same insert is fine and leaves A1 alone.
20393 assert!(p.ungroup(Lane::V1, 0));
20394 p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::V1, take(1, 0, 10))]).unwrap();
20395 assert_eq!(spans(&p, Lane::V1), vec![(0, 30, 0, 0), (30, 40, 0, 1), (40, 100, 30, 0)]);
20396 assert_eq!(spans(&p, Lane::A1), vec![(0, 90, 0, 0)]);
20397 }
20398
20399 #[test]
20400 fn a_lane_that_is_not_targeted_is_neither_cut_nor_moved() {
20401 let mut p = bed();
20402 let v2 = Lane::new(LaneKind::Video, 1);
20403 p.lanes.push(LaneData::new(LaneKind::Video, Vec::new()));
20404 let a2 = Lane::new(LaneKind::Audio, 1);
20405 p.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
20406 p.edit_from_source(SourceEdit::Overwrite, 20, &[(v2, take(1, 0, 60)), (a2, take(1, 0, 60))]).unwrap();
20407 p.edit_from_source(SourceEdit::Insert, 30, &both(1, 0, 10)).unwrap();
20408 assert_eq!(spans(&p, v2), vec![(20, 80, 0, 1)], "the V2 clip across the insert is untouched");
20409 assert_eq!(spans(&p, a2), vec![(20, 80, 0, 1)]);
20410 assert_eq!(spans(&p, Lane::V1)[1], (30, 40, 0, 1));
20411 }
20412
20413 #[test]
20414 fn a_locked_lane_refuses() {
20415 let mut p = bed();
20416 assert!(p.set_lane_locked(Lane::A1, true));
20417 let before = spans(&p, Lane::V1);
20418 for kind in [SourceEdit::Insert, SourceEdit::Overwrite] {
20419 let err = p.edit_from_source(kind, 10, &both(1, 0, 10)).unwrap_err();
20420 assert!(err.to_string().contains("A1 is locked"), "{err}");
20421 }
20422 assert_eq!(spans(&p, Lane::V1), before);
20423 }
20424
20425 #[test]
20426 fn an_audio_only_source_goes_on_an_audio_lane_only() {
20427 let mut p = bed();
20428 p.sources.push(Source::new("/nonexistent/song.mp3", 0));
20429 let err = p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::V1, take(2, 0, 10))]).unwrap_err();
20430 assert!(err.to_string().contains("no picture"), "{err}");
20431 assert!(p.ungroup(Lane::V1, 0));
20432 p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::A1, take(2, 0, 10))]).unwrap();
20433 assert_eq!(spans(&p, Lane::A1), vec![(0, 30, 0, 0), (30, 40, 0, 2), (40, 100, 30, 0)]);
20434 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0)]);
20435 assert_eq!(p.lane(Lane::A1)[1].link, None, "a lone half belongs to no group");
20436 }
20437
20438 #[test]
20439 fn a_still_goes_on_a_video_lane_only() {
20440 let mut p = bed();
20441 p.sources.push(Source::new("/nonexistent/pic.png", 0));
20442 let err = p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::A1, take(2, 0, 10))]).unwrap_err();
20443 assert!(err.to_string().contains("still"), "{err}");
20444 assert!(p.ungroup(Lane::V1, 0));
20445 p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::V1, take(2, 0, 125))]).unwrap();
20446 assert_eq!(spans(&p, Lane::V1), vec![(0, 10, 0, 0), (10, 135, 0, 2)]);
20447 assert_eq!(spans(&p, Lane::A1), vec![(0, 90, 0, 0)]);
20448 }
20449
20450 #[test]
20451 fn each_edit_is_one_undo_step() {
20452 for kind in [SourceEdit::Insert, SourceEdit::Overwrite] {
20453 let mut p = bed();
20454 let before = (p.lane(Lane::V1).to_vec(), p.lane(Lane::A1).to_vec());
20455 let history = p.history_len();
20456 p.edit_from_source(kind, 30, &both(1, 0, 10)).unwrap();
20457 assert_eq!(p.history_len(), history + 1);
20458 assert!(p.undo());
20459 assert_eq!((p.lane(Lane::V1).to_vec(), p.lane(Lane::A1).to_vec()), before, "{kind:?}");
20460 assert!(p.redo());
20461 assert_eq!(spans(&p, Lane::V1)[1], (30, 40, 0, 1));
20462 }
20463 }
20464
20465 #[test]
20466 fn bad_edits_refuse_and_cost_no_undo_step() {
20467 let mut p = bed();
20468 let history = p.history_len();
20469 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[]).is_err());
20470 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(1, 5, 5))]).is_err());
20471 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(9, 0, 5))]).is_err());
20472 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::new(LaneKind::Video, 4), take(1, 0, 5))]).is_err());
20473 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(1, 0, 5)), (Lane::V1, take(1, 0, 5))]).is_err());
20474 assert!(p.edit_from_source(SourceEdit::Overwrite, u32::MAX, &both(1, 0, 5)).is_err());
20475 assert_eq!(p.history_len(), history);
20476 }
20477}
20478
20479/// Roll, slip and slide: the trims that move two things at once.
20480#[cfg(test)]
20481mod pro_trim_tests {
20482 use super::*;
20483
20484 const FILE: &str = "/nonexistent/a.mp4";
20485
20486 fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip {
20487 Clip {
20488 speed_keys: Vec::new(),
20489 opacity_keys: Vec::new(),
20490 color_keys: Vec::new(),
20491 effects: Vec::new(),
20492 transition_kind: Default::default(),
20493 reversed: false,
20494 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
20495 angle: Default::default(),
20496 fade_in: 0,
20497 fade_out: 0,
20498 transition_out: 0,
20499 visualizer: 0,
20500 viz_paint: 0,
20501 gain_db: 0.0,
20502 gain_keys: Vec::new(),
20503 pan: 0,
20504 pitch: 0,
20505 transform_keys: Vec::new(),
20506 start,
20507 in_frame,
20508 out_frame,
20509 source: 0,
20510 link: None,
20511 eq: None,
20512 color: None,
20513 transform: None,
20514 fit: FitPolicy::default(),
20515 speed: Speed::NORMAL,
20516 }
20517 }
20518
20519 fn fast(start: u32, in_frame: u32, out_frame: u32, permille: u16) -> Clip {
20520 Clip { speed: Speed::from_permille(permille), ..clip(start, in_frame, out_frame) }
20521 }
20522
20523 /// 30 frames of V1+A1 (a linked take) cut into 0..10, 10..20, 20..30.
20524 fn three() -> Project {
20525 let mut p = Project::single(FILE, 30);
20526 assert!(p.split(10));
20527 assert!(p.split(20));
20528 p
20529 }
20530
20531 fn w(t: &[u32]) -> SourceWalls<'_> {
20532 SourceWalls::same(t)
20533 }
20534
20535 /// `(start, end, in, out)` of every clip on the lane.
20536 fn spans(p: &Project, lane: Lane) -> Vec<(u32, u32, u32, u32)> {
20537 p.lane(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.out_frame)).collect()
20538 }
20539
20540 /// A lane with `v2` holding the given clips; no linked partners.
20541 fn lone(clips: &[Clip]) -> (Project, Lane) {
20542 let mut p = Project::single(FILE, 1);
20543 let v = p.add_lane(LaneKind::Video);
20544 for c in clips {
20545 assert!(p.place(v, c.start, c.clone()));
20546 }
20547 (p, v)
20548 }
20549
20550 #[test]
20551 fn roll_moves_the_cut_of_a_take_and_keeps_the_length() {
20552 let mut p = three();
20553 let steps = p.history.len();
20554 assert_eq!(p.roll(Lane::V1, 0, 14, w(&[30])), Some(14));
20555 for lane in [Lane::V1, Lane::A1] {
20556 assert_eq!(
20557 spans(&p, lane),
20558 [(0, 14, 0, 14), (14, 20, 14, 20), (20, 30, 20, 30)],
20559 "{lane:?}: both halves of the take rolled, the far cut stayed"
20560 );
20561 }
20562 assert_eq!(p.history.len(), steps + 1, "one undo step");
20563 assert!(p.undo());
20564 assert_eq!(spans(&p, Lane::V1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20565 assert_eq!(spans(&p, Lane::A1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20566 // Rolled back toward the start, from the other side of the take.
20567 assert_eq!(p.roll(Lane::A1, 1, 25, w(&[30])), Some(25));
20568 assert_eq!(spans(&p, Lane::V1)[1..], [(10, 25, 10, 25), (25, 30, 25, 30)]);
20569 }
20570
20571 #[test]
20572 fn roll_is_clamped_to_a_frame_each_side_and_changes_nothing_in_place() {
20573 let mut p = three();
20574 assert_eq!(p.roll_room(Lane::V1, 0, w(&[30])), Some((1, 19)));
20575 assert_eq!(p.roll(Lane::V1, 0, 500, w(&[30])), Some(19));
20576 assert_eq!(spans(&p, Lane::V1)[..2], [(0, 19, 0, 19), (19, 20, 19, 20)]);
20577 assert_eq!(p.roll(Lane::V1, 0, 0, w(&[30])), Some(1));
20578 let steps = p.history.len();
20579 assert_eq!(p.roll(Lane::V1, 0, 1, w(&[30])), Some(1), "already there");
20580 assert_eq!(p.history.len(), steps, "and a roll that moves nothing costs no step");
20581 }
20582
20583 #[test]
20584 fn roll_stops_at_the_source_media() {
20585 // A plays 5..15 of a source that is 18 frames long; B plays 25..30.
20586 let (mut p, v) = lone(&[clip(0, 5, 15), clip(10, 25, 30)]);
20587 assert_eq!(p.roll_room(v, 0, w(&[18])), Some((1, 13)));
20588 assert_eq!(p.roll(v, 0, 100, w(&[18])), Some(13));
20589 assert_eq!(p.lane(v)[0].out_frame, 18, "the out-point is the source's last frame");
20590 assert_eq!(spans(&p, v)[1], (13, 15, 28, 30), "the next in-point moved by the same frames");
20591 // The other way: B can back up only to its own first frame.
20592 let (mut p, v) = lone(&[clip(0, 5, 15), clip(10, 3, 8)]);
20593 assert_eq!(p.roll(v, 0, 0, w(&[30])), Some(7), "3 frames of head: the cut stops 3 frames back");
20594 assert_eq!(p.lane(v)[1].in_frame, 0);
20595 }
20596
20597 #[test]
20598 fn roll_needs_a_cut() {
20599 let mut p = three();
20600 assert_eq!(p.roll(Lane::V1, 2, 25, w(&[30])), None, "the last clip has no neighbour");
20601 assert_eq!(p.roll(Lane::V1, 9, 25, w(&[30])), None, "no such clip");
20602 let (mut p, v) = lone(&[clip(0, 0, 10), clip(12, 0, 10)]);
20603 let steps = p.history.len();
20604 assert_eq!(p.roll(v, 0, 5, w(&[30])), None, "a gap is not a cut");
20605 assert_eq!(p.history.len(), steps);
20606 }
20607
20608 #[test]
20609 fn roll_at_speed_moves_source_by_the_rate() {
20610 // Two clips at 2x: 10 timeline frames each, twenty source frames each.
20611 let (mut p, v) = lone(&[fast(0, 0, 20, 2000), fast(10, 30, 50, 2000)]);
20612 assert_eq!(p.roll(v, 0, 14, w(&[100])), Some(14));
20613 assert_eq!(spans(&p, v), [(0, 14, 0, 28), (14, 20, 38, 50)], "4 timeline frames are 8 source frames");
20614 assert!(p.undo());
20615 assert_eq!(spans(&p, v), [(0, 10, 0, 20), (10, 20, 30, 50)]);
20616 }
20617
20618 #[test]
20619 fn roll_at_a_slow_rate_never_opens_a_gap_or_changes_the_length() {
20620 // 0.4x: a source range of n frames is round(2.5 n) timeline frames, so most
20621 // timeline lengths are unreachable.
20622 for to in 1..20 {
20623 let (mut p, v) = lone(&[fast(0, 0, 4, 400), fast(10, 10, 14, 400)]);
20624 let end = p.lane(v)[1].end();
20625 let landed = p.roll(v, 0, to, w(&[100])).expect("a cut");
20626 let [a, b] = [&p.lane(v)[0], &p.lane(v)[1]];
20627 assert_eq!((a.end(), b.start, b.end()), (landed, landed, end), "roll to {to}");
20628 assert!(sorted_disjoint(p.lane(v)));
20629 }
20630 }
20631
20632 #[test]
20633 fn roll_pins_at_a_ramped_clip_behind_the_cut() {
20634 let (mut p, v) = lone(&[clip(0, 0, 10), clip(10, 0, 10)]);
20635 p.set_speed_ramp(v, 1, &[SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 8, speed: Speed::from_permille(2000) }])
20636 .expect("ramp");
20637 assert_eq!(p.roll(v, 0, 5, w(&[100])), Some(10), "a ramped in-point cannot move");
20638 // The ramp may be the one before the cut: its tail is the only edge that moves.
20639 let (mut p, v) = lone(&[clip(0, 0, 20)]);
20640 p.set_speed_ramp(v, 0, &[SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 15, speed: Speed::from_permille(2000) }])
20641 .expect("ramp");
20642 let at = p.lane(v)[0].end();
20643 assert!(p.place(v, at, clip(at, 5, 15)));
20644 let end = p.lane(v)[1].end();
20645 let cut = p.lane(v)[0].end();
20646 let landed = p.roll(v, 0, cut - 3, w(&[100])).expect("a cut");
20647 assert!(landed < cut);
20648 assert_eq!((p.lane(v)[0].end(), p.lane(v)[1].start, p.lane(v)[1].end()), (landed, landed, end));
20649 }
20650
20651 #[test]
20652 fn slip_shifts_the_window_and_nothing_else() {
20653 let mut p = three();
20654 let steps = p.history.len();
20655 assert_eq!(p.slip(Lane::V1, 1, 5, w(&[30])), Some(5));
20656 for lane in [Lane::V1, Lane::A1] {
20657 assert_eq!(
20658 spans(&p, lane)[1],
20659 (10, 20, 15, 25),
20660 "{lane:?}: same slot, later footage"
20661 );
20662 assert_eq!(spans(&p, lane)[0], (0, 10, 0, 10), "the neighbours are untouched");
20663 }
20664 assert_eq!(p.history.len(), steps + 1);
20665 assert!(p.undo());
20666 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 10, 20));
20667 assert_eq!(spans(&p, Lane::A1)[1], (10, 20, 10, 20));
20668 }
20669
20670 #[test]
20671 fn slip_is_clamped_to_the_source_and_each_member_to_its_own() {
20672 let mut p = three();
20673 assert_eq!(p.slip_room(Lane::V1, 1, w(&[30])), Some((-10, 10)));
20674 assert_eq!(p.slip(Lane::V1, 1, -99, w(&[30])), Some(-10));
20675 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 0, 10));
20676 assert_eq!(p.slip(Lane::V1, 1, 99, w(&[30])), Some(20));
20677 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 20, 30));
20678 // The sound is 5 frames shorter than the picture: it stops where it stops.
20679 let mut p = three();
20680 let walls = SourceWalls { picture: &[30], sound: &[25] };
20681 assert_eq!(p.slip(Lane::V1, 1, 8, walls), Some(8));
20682 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 18, 28));
20683 assert_eq!(spans(&p, Lane::A1)[1], (10, 20, 15, 25), "the sound ran out of file first");
20684 // Pinned: no change, no step.
20685 let steps = p.history.len();
20686 assert_eq!(p.slip(Lane::V1, 1, 1, w(&[28])), Some(0));
20687 assert_eq!(p.history.len(), steps);
20688 }
20689
20690 #[test]
20691 fn slip_at_speed_keeps_the_slot_and_converts_timeline_frames() {
20692 let (mut p, v) = lone(&[fast(0, 10, 20, 2000)]);
20693 assert_eq!(p.lane(v)[0].end(), 5);
20694 assert_eq!(p.slip_source_delta(v, 0, 3), Some(6), "3 timeline frames at 2x");
20695 assert_eq!(p.slip_source_delta(v, 0, -3), Some(-6));
20696 assert_eq!(p.slip(v, 0, 6, w(&[60])), Some(6));
20697 assert_eq!(spans(&p, v), [(0, 5, 16, 26)]);
20698 assert_eq!(p.slip(v, 0, 1000, w(&[60])), Some(34), "clamped to the 60 frames the source has");
20699 assert_eq!(spans(&p, v), [(0, 5, 50, 60)]);
20700 // Half speed: a timeline frame is half a source frame.
20701 let (p, v) = lone(&[fast(0, 10, 20, 500)]);
20702 assert_eq!(p.slip_source_delta(v, 0, 8), Some(4));
20703 }
20704
20705 #[test]
20706 fn slip_keeps_a_ramped_clip_in_its_slot() {
20707 let (mut p, v) = lone(&[clip(0, 10, 30)]);
20708 let keys = [SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 10, speed: Speed::from_permille(2000) }];
20709 p.set_speed_ramp(v, 0, &keys).expect("ramp");
20710 let before = (p.lane(v)[0].start, p.lane(v)[0].end());
20711 assert_eq!(p.slip(v, 0, 7, w(&[100])), Some(7));
20712 let c = &p.lane(v)[0];
20713 assert_eq!((c.start, c.end(), c.in_frame, c.out_frame), (before.0, before.1, 17, 37));
20714 assert_eq!(c.speed_keys.len(), 2, "the ramp stays on the clip");
20715 }
20716
20717 #[test]
20718 fn slip_has_nothing_to_do_to_a_still_or_a_missing_clip() {
20719 let mut p = Project::single("/nonexistent/pic.png", 100);
20720 let steps = p.history.len();
20721 assert_eq!(p.slip(Lane::V1, 0, 5, w(&[100])), None);
20722 assert_eq!(p.slip(Lane::V1, 3, 5, w(&[100])), None);
20723 assert_eq!(p.history.len(), steps);
20724 }
20725
20726 #[test]
20727 fn slide_moves_the_clip_and_its_neighbours_absorb_it() {
20728 let mut p = three();
20729 let steps = p.history.len();
20730 assert_eq!(p.slide(Lane::V1, 1, 13, w(&[30])), Some(13));
20731 for lane in [Lane::V1, Lane::A1] {
20732 assert_eq!(
20733 spans(&p, lane),
20734 [(0, 13, 0, 13), (13, 23, 10, 20), (23, 30, 23, 30)],
20735 "{lane:?}: same content, same length, neighbours absorb"
20736 );
20737 }
20738 assert_eq!(p.history.len(), steps + 1, "one undo step");
20739 assert!(p.undo());
20740 assert_eq!(spans(&p, Lane::V1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20741 assert_eq!(spans(&p, Lane::A1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20742 assert_eq!(p.slide(Lane::A1, 1, 6, w(&[30])), Some(6), "either half drags the take");
20743 assert_eq!(spans(&p, Lane::V1), [(0, 6, 0, 6), (6, 16, 10, 20), (16, 30, 16, 30)]);
20744 }
20745
20746 #[test]
20747 fn slide_is_clamped_to_a_frame_of_each_neighbour_and_their_media() {
20748 let mut p = three();
20749 assert_eq!(p.slide_room(Lane::V1, 1, w(&[30])), Some((1, 19)));
20750 assert_eq!(p.slide(Lane::V1, 1, 100, w(&[30])), Some(19));
20751 assert_eq!(spans(&p, Lane::V1), [(0, 19, 0, 19), (19, 29, 10, 20), (29, 30, 29, 30)]);
20752 assert_eq!(p.slide(Lane::V1, 1, 0, w(&[30])), Some(1));
20753 // The clip before it only has source up to frame 12; it cannot give more.
20754 let (mut p, v) = lone(&[clip(0, 0, 10), clip(10, 40, 50), clip(20, 60, 70)]);
20755 assert_eq!(p.slide(v, 1, 99, w(&[12])), Some(12));
20756 assert_eq!(p.lane(v)[0].out_frame, 12, "it gave every frame it had");
20757 }
20758
20759 #[test]
20760 fn slide_needs_a_neighbour_on_each_side() {
20761 let mut p = three();
20762 let steps = p.history.len();
20763 assert_eq!(p.slide(Lane::V1, 0, 3, w(&[30])), None, "first clip");
20764 assert_eq!(p.slide(Lane::V1, 2, 3, w(&[30])), None, "last clip");
20765 assert_eq!(p.slide(Lane::V1, 8, 3, w(&[30])), None, "no clip");
20766 assert_eq!(p.history.len(), steps);
20767 let (mut p, v) = lone(&[clip(0, 0, 10)]);
20768 assert_eq!(p.slide(v, 0, 3, w(&[30])), None, "alone on its lane");
20769 }
20770
20771 #[test]
20772 fn slide_beside_a_gap_edits_only_the_cut_side() {
20773 // 0..10 | gap 10..15 | 15..25 | 25..35
20774 let (mut p, v) = lone(&[clip(0, 0, 10), clip(15, 20, 30), clip(25, 40, 50)]);
20775 assert_eq!(p.slide_room(v, 1, w(&[100])), Some((10, 24)));
20776 assert_eq!(p.slide(v, 1, 0, w(&[100])), Some(10), "into the gap, but not over the clip before it");
20777 assert_eq!(spans(&p, v), [(0, 10, 0, 10), (10, 20, 20, 30), (20, 35, 35, 50)]);
20778 }
20779
20780 #[test]
20781 fn slide_at_speed_moves_neighbour_source_by_their_rate() {
20782 // The clip before it plays at 2x: a frame of timeline is two of source.
20783 let (mut p, v) = lone(&[fast(0, 0, 20, 2000), clip(10, 40, 50), clip(20, 60, 70)]);
20784 assert_eq!(p.slide(v, 1, 13, w(&[100])), Some(13));
20785 assert_eq!(spans(&p, v), [(0, 13, 0, 26), (13, 23, 40, 50), (23, 30, 63, 70)]);
20786 assert!(p.undo());
20787 assert_eq!(spans(&p, v), [(0, 10, 0, 20), (10, 20, 40, 50), (20, 30, 60, 70)]);
20788 }
20789
20790 #[test]
20791 fn slide_keeps_the_length_whatever_the_rate() {
20792 for to in 1..40 {
20793 let (mut p, v) = lone(&[fast(0, 0, 4, 400), clip(10, 40, 50), fast(20, 10, 14, 400)]);
20794 let end = p.lane(v)[2].end();
20795 let landed = p.slide(v, 1, to, w(&[100])).expect("neighbours");
20796 let l = p.lane(v);
20797 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}");
20798 }
20799 }
20800}