forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6dae2b4Tahinli3 months ago555 commits

project.rs8810 lines, 384.6 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::eq::EqParams;
81use crate::limiter::{Limiter, db_to_linear};
82use crate::scale::FitPolicy;
83use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
84
85/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
86/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
87/// for every purpose but the honest one, which is that it is still a level and
88/// not a mute.
89pub const MIN_GAIN_DB: f32 = -60.0;
90/// ...and how far up. +12 dB is four times the amplitude, which is as much as
91/// a mix bus can take before the limiter is doing all the work.
92pub const MAX_GAIN_DB: f32 = 12.0;
93
94/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
95/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
96/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
97/// comparable nor exactly writable, and `.edith` has to read back the very
98/// number that was set. A thousandth is finer than any card can drag and coarser
99/// than any rounding anyone can hear.
100///
101/// The rate alone: the audio path time-stretches a speeded clip
102/// (`crate::stretch`), so its pitch stays where it was recorded while its
103/// seconds compress or stretch -- the tape effect this used to be is gone.
104/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
105/// [`Speed::MAX`] four times.
106#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
107pub struct Speed(u16);
108
109/// What [`Project::parts`] hands back: the comparable shape of everything an
110/// edit can change, for the sweep's undo round-trip. Test-only, like every
111/// accessor it exists for: the sweep lives behind `cfg(test)`.
112#[cfg(test)]
113#[derive(Clone, Debug, PartialEq)]
114pub(crate) struct SweepParts(
115 pub(crate) usize,
116 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
117 pub(crate) Vec<Vec<SubClip>>,
118);
119
120impl Speed {
121 /// Real time -- what every clip is until something says otherwise, and the
122 /// value every path in this engine short-circuits on.
123 pub const NORMAL: Speed = Speed(1000);
124 pub const MIN: Speed = Speed(250);
125 pub const MAX: Speed = Speed(4000);
126
127 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
128 /// unrepresentable rather than merely refused: nothing downstream divides
129 /// by a speed that could be nothing.
130 pub fn from_permille(permille: u16) -> Self {
131 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
132 }
133
134 pub fn permille(self) -> u16 {
135 self.0
136 }
137
138 pub fn is_normal(self) -> bool {
139 self == Self::NORMAL
140 }
141
142 /// As a multiplier, for the sound worker and for a label.
143 pub fn as_f64(self) -> f64 {
144 f64::from(self.0) / 1000.
145 }
146
147 /// How many *timeline* frames `source` source frames occupy at this rate --
148 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
149 /// clip that occupied no frames would be an empty placement, which the lane
150 /// invariant forbids and which nothing could ever click on again.
151 pub fn frames(self, source: u32) -> u32 {
152 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
153 n.clamp(1, u64::from(u32::MAX)) as u32
154 }
155
156 /// The mapping itself: which source frame of a clip the `offset`th timeline
157 /// frame of it plays. Floored, so the first timeline frame is the clip's own
158 /// in-point at every rate.
159 pub fn source_at(self, offset: u32) -> u32 {
160 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
161 }
162
163 /// Its inverse, for a decoder's frames on their way back out: which timeline
164 /// frame of the clip the `offset`th *source* frame of it lands on.
165 ///
166 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
167 /// decoded frame with this and shows the newest whose stamp has come due, so
168 /// what is on screen at timeline offset `d` is the last source frame with
169 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
170 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
171 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
172 /// the two the same way would put the preview a frame off the export at some
173 /// speeds and a whole held frame off at slow ones -- drift that no test of
174 /// either side alone would catch.
175 pub fn timeline_at(self, offset: u32) -> u32 {
176 (u64::from(offset) * 1000)
177 .div_ceil(u64::from(self.0))
178 .min(u64::from(u32::MAX)) as u32
179 }
180
181 /// The longest source range that still *fits* in `frames` timeline frames at
182 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
183 /// any room narrower than the four timeline frames one source frame occupies.
184 ///
185 /// What a trim commits and what a hole-punch leaves behind: rounding could
186 /// otherwise hand back a range wider than the room, and a clip that outgrew
187 /// its room would overlap its neighbour -- the one thing a lane may never do.
188 /// `None` is not an error, it is "no remainder": the caller drops that piece
189 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
190 /// is `frames` itself, so nothing about an unspeeded edit changes.
191 pub fn fit(self, frames: u32) -> Option<u32> {
192 if frames == 0 || self.frames(1) > frames {
193 return None;
194 }
195 let mut src = self.source_at(frames).max(1);
196 // At most a step or two: `frames` is monotone in `src` and the rounding
197 // above can only overshoot by one source frame's worth.
198 while src > 1 && self.frames(src) > frames {
199 src -= 1;
200 }
201 Some(src)
202 }
203
204 /// How many timeline frames `source` source frames of head (or tail) are
205 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
206 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
207 /// empty, but the room in front of one may well be.
208 pub fn room(self, source: u32) -> u32 {
209 match source {
210 0 => 0,
211 n => self.frames(n),
212 }
213 }
214
215 /// How many timeline frames from `offset` on show the **same** source frame:
216 /// one at real time and faster, more when the clip is slowed. What an export
217 /// encodes without decoding the same picture twice, and the count that makes
218 /// its frame walk exactly as long as the span.
219 pub fn repeats(self, offset: u32, len: u32) -> u32 {
220 let want = self.source_at(offset);
221 (offset..len)
222 .take_while(|&t| self.source_at(t) == want)
223 .count() as u32
224 }
225
226 /// Where in the source a cut `offset` timeline frames into a clip of `len`
227 /// source frames falls -- and `None` when this rate cannot address that
228 /// frame at all.
229 ///
230 /// At half speed a clip of ten source frames is twenty timeline frames long
231 /// and every source frame is on screen twice, so a cut between the two
232 /// showings of one frame is not a cut in the *file*: taking it would leave
233 /// two halves whose lengths no longer add up to the clip that was cut --
234 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
235 /// the model stays exact and the front-end can say why. At real time every
236 /// interior frame answers, which is the path a project without speeds is on.
237 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
238 let src = self.source_at(offset);
239 (src > 0
240 && src < len
241 && self.frames(src) == offset
242 && self.frames(len - src) == self.frames(len) - offset)
243 .then_some(src)
244 }
245}
246
247impl Default for Speed {
248 fn default() -> Self {
249 Self::NORMAL
250 }
251}
252
253impl std::fmt::Display for Speed {
254 /// `2.00x` -- what a card prints and what a clip box is marked with.
255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256 write!(f, "{:.2}x", self.as_f64())
257 }
258}
259
260/// What a file's own frame rate is against the timeline's, as an exact
261/// rational: how many frames of the *file* one frame of the timeline is worth.
262///
263/// Every frame number in this module counts **timeline** frames -- a clip's
264/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
265/// timeline is as many frames long as the seconds it lasts, and every edit
266/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
267/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
268/// opens a worker with it and [`crate::export`] pulls pictures through it. The
269/// file's own numbering exists nowhere else.
270///
271/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
272/// export encodes at a timeline frame has to be the frame playback is holding
273/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
274/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
275///
276/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
277/// stays `800/1001` however far the timeline runs, where a rate rounded to
278/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
279/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
280///
281/// [`PlaybackSession`]: crate::PlaybackSession
282#[derive(Clone, Copy, PartialEq, Eq, Debug)]
283pub struct Rate {
284 /// Frames of the file...
285 source: u32,
286 /// ...per this many frames of the timeline it plays on. Never zero.
287 timeline: u32,
288}
289
290impl Rate {
291 /// A file shot at the timeline's own rate: every conversion below is the
292 /// identity, which is the path a single-rate project is on.
293 pub const REAL_TIME: Self = Self {
294 source: 1,
295 timeline: 1,
296 };
297
298 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
299 /// exactly.
300 ///
301 /// Both rates come out of a container as a division, so neither is ever the
302 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
303 /// already knows how to name one exactly -- it is the same pair the muxer
304 /// counts an export's frames in -- and this is that pair divided by that
305 /// pair, reduced. A rate no timescale can name is an `Err` in that
306 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
307 /// where a file carrying one is refused by name, beside the codec.
308 ///
309 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
310 /// timeline that had ever opened in this editor before mixed rates.
311 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
312 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
313 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
314 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
315 let num = u64::from(src_scale) * u64::from(tl_ticks);
316 let den = u64::from(src_ticks) * u64::from(tl_scale);
317 Ok(Self::reduced(num, den))
318 }
319
320 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
321 fn reduced(num: u64, den: u64) -> Self {
322 let g = gcd(num, den);
323 let (mut num, mut den) = (num / g, den / g);
324 // A ratio no pair of real frame rates produces, but the fields are `u32`
325 // so that every multiplication below fits a `u64` at any frame count.
326 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
327 (num, den) = (num.div_ceil(2), den.div_ceil(2));
328 }
329 Self {
330 source: num.max(1) as u32,
331 timeline: den.max(1) as u32,
332 }
333 }
334
335 /// The same file against a timeline that has itself been retimed: `self` is
336 /// its frames per frame of the old timeline and `k` is old frames per new
337 /// one, so this is its frames per frame of the *new* one -- exactly, without
338 /// going back through an `f64` fps that names neither rate
339 /// ([`crate::PlaybackSession::set_frame_rate`]).
340 pub fn then(self, k: Rate) -> Self {
341 Self::reduced(
342 u64::from(self.source) * u64::from(k.source),
343 u64::from(self.timeline) * u64::from(k.timeline),
344 )
345 }
346
347 pub fn is_real_time(self) -> bool {
348 self.source == self.timeline
349 }
350
351 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
352 /// is, given the timeline's, for a library row that names it.
353 pub fn as_f64(self) -> f64 {
354 f64::from(self.source) / f64::from(self.timeline)
355 }
356
357 /// Which frame of the file the `frame`th timeline-rate frame of it is:
358 /// floored, [`Speed::source_at`]'s half of the pair.
359 pub fn source_at(self, frame: u32) -> u32 {
360 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
361 .min(u64::from(u32::MAX)) as u32
362 }
363
364 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
365 /// timeline-rate frame that shows source frame `source_frame` -- which is
366 /// the stamp playback puts on a decoded picture, and, applied to a file's
367 /// frame *count*, how long that file is in timeline frames.
368 pub fn timeline_at(self, source_frame: u32) -> u32 {
369 (u64::from(source_frame) * u64::from(self.timeline))
370 .div_ceil(u64::from(self.source))
371 .min(u64::from(u32::MAX)) as u32
372 }
373}
374
375/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
376/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
377fn gcd(a: u64, b: u64) -> u64 {
378 match b {
379 0 => a.max(1),
380 b => gcd(b, a % b),
381 }
382}
383
384/// A half-open `[in_frame, out_frame)` range of frames of source
385/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
386/// Never empty.
387///
388/// Counted at the **timeline's** frame rate, not the file's: a source shot at
389/// another rate is converted at the decoder's door ([`Rate`]), so every edit
390/// here is frames of one clock.
391#[derive(Clone, Copy, PartialEq, Eq, Debug)]
392pub struct Clip {
393 /// Timeline frame the clip's first frame is shown at. Meaningless on a
394 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
395 /// with where the caller asked for.
396 pub start: u32,
397 pub in_frame: u32,
398 pub out_frame: u32,
399 /// Index into [`Project::sources`].
400 pub source: usize,
401 /// Group id: clips sharing one were split from the same take. `None` for a
402 /// clip that belongs to no group.
403 pub link: Option<u32>,
404 /// Index into the project's equalizer table
405 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
406 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
407 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
408 /// plain assignment. The table is append-only within a session, so an index
409 /// on a clipboard clip or inside an undo snapshot can never dangle.
410 pub eq: Option<u16>,
411 /// Index into the project's colour table
412 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
413 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
414 /// promises: `Copy`, append-only within a session, never dangling.
415 pub color: Option<u16>,
416 /// How this clip's picture meets a project canvas of another shape
417 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
418 /// two above: it is one byte with no parameters, so there is nothing for a
419 /// table to share, and a clip that is the project's own size never consults
420 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
421 /// where the aspect does not agree.
422 pub fit: FitPolicy,
423 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
424 /// eq and colour indexes: it is two bytes with nothing to share, and a table
425 /// would put a level of indirection between the mapping and the one number
426 /// every frame of it is divided by.
427 ///
428 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
429 /// the clip plays, so a trim and a split still address the file. What it
430 /// changes is how many *timeline* frames that range is spread over
431 /// ([`Clip::frames`]).
432 pub speed: Speed,
433}
434
435impl Clip {
436 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
437 /// reads out of its file -- not how long it is on the timeline, which is
438 /// [`Clip::frames`] and differs the moment it is speeded.
439 pub fn len(&self) -> u32 {
440 self.out_frame - self.in_frame
441 }
442
443 /// Timeline frames it occupies: its source range at its own speed, never
444 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
445 /// what it overlaps, how wide its box is -- is asked of this and not of
446 /// [`Clip::len`].
447 pub fn frames(&self) -> u32 {
448 self.speed.frames(self.len())
449 }
450
451 /// One past the last timeline frame it covers.
452 pub fn end(&self) -> u32 {
453 self.start + self.frames()
454 }
455}
456
457/// A file the timeline plays from, and *which* of its audio streams it plays:
458/// a file carrying one track per language is several sources, one per stream,
459/// sharing a path. Two entries differing only in the stream are two sources --
460/// they are what a clip names, and a clip plays exactly one stream.
461///
462/// The path is always canonical ([`Source::new`]), so the same file reached by
463/// two paths is one source.
464#[derive(Clone, Debug, PartialEq, Eq)]
465pub struct Source {
466 pub path: PathBuf,
467 /// Position among the file's audio tracks in file order, the numbering
468 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
469 /// single track, and for a silent one.
470 pub audio_stream: usize,
471}
472
473impl Source {
474 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
475 Self {
476 path: canonical(path.as_ref()),
477 audio_stream,
478 }
479 }
480}
481
482/// What a lane carries, which is what a *gap* in it means: black frames on a
483/// video lane, silence on an audio one, nothing over the picture on a subtitle
484/// one.
485#[derive(Clone, Copy, PartialEq, Eq, Debug)]
486pub enum LaneKind {
487 Video,
488 Audio,
489 /// Words over the picture, placed and trimmed like everything else
490 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
491 /// so a caption is dragged, cut, rippled and undone by the machinery every
492 /// other clip already goes through.
493 ///
494 /// It carries no [`Clip`] at all, and that is what keeps the media paths
495 /// free of it: [`Project::lane`] hands back an empty slice, so every
496 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
497 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
498 /// check it already had, [`Project::composite_span_at`] and
499 /// [`Project::audio_lanes`] never look at it, and the three doors that
500 /// could still put a picture on one -- [`Project::from_parts`],
501 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
502 Subtitle,
503}
504
505/// Which lane an operation acts on: a kind plus a 0-based position among the
506/// lanes of that kind, so [`Lane::V1`] is the first video lane and
507/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
508///
509/// A handle, not the lane itself. It stays meaningful while lanes are added,
510/// and one naming a lane that is not there reads as an empty lane and refuses
511/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
512/// bounds check of its own.
513#[derive(Clone, Copy, PartialEq, Eq, Debug)]
514pub struct Lane {
515 pub kind: LaneKind,
516 pub ord: usize,
517}
518
519impl Lane {
520 /// The first video lane: what a decoder plays and what an export renders.
521 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
522 /// The first audio lane: what the audio worker plays.
523 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
524 /// The first subtitle lane -- the one a project has only once something
525 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
526 /// alone.
527 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
528
529 pub const fn new(kind: LaneKind, ord: usize) -> Self {
530 Self { kind, ord }
531 }
532
533 /// `V1`, `A2`: how a lane is written in a header column and named in an
534 /// error about it.
535 pub fn label(self) -> String {
536 let kind = match self.kind {
537 LaneKind::Video => 'V',
538 LaneKind::Audio => 'A',
539 LaneKind::Subtitle => 'S',
540 };
541 format!("{kind}{}", self.ord + 1)
542 }
543}
544
545/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
546/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
547/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
548/// frames. Never empty at either end.
549///
550/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
551/// actually has, and placed by the same one number: the window is in the
552/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
553/// placement is in timeline frames like everything else on a lane. So the lane
554/// invariant is the lane's ([`subs_sorted_disjoint`] is
555/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
556/// else, and only the two calls that change a *duration* -- a trim, and the
557/// mapping out -- ever need the timeline's rate.
558///
559/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
560/// paste and an undo snapshot are a plain assignment and can never dangle.
561#[derive(Clone, Copy, PartialEq, Eq, Debug)]
562pub struct SubClip {
563 /// Timeline frame its first frame is shown at.
564 pub start: u32,
565 /// How many timeline frames it covers; `>= 1`. Held rather than derived
566 /// from the window because a [`Project`] has no frame rate -- the rate
567 /// enters at the door of the two calls that need it -- and every placement
568 /// question (where it ends, what it overlaps) is asked in frames.
569 pub frames: u32,
570 /// Index into [`Project::subtitles`]: *which* track's words these are.
571 pub track: usize,
572 /// The half-open window of that track it shows, in microseconds from the
573 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
574 /// timed in, so no conversion stands between a cue and the window that
575 /// keeps it.
576 pub in_us: i64,
577 pub out_us: i64,
578 /// Group id: `Some` exactly when a hand put this caption in a group with
579 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
580 /// no group, and what a cut cuts apart loses the one it had
581 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
582 /// clip is what makes the caption move, trim and delete with it.
583 pub link: Option<u32>,
584}
585
586impl SubClip {
587 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
588 /// what every overlap question is asked of.
589 pub fn end(&self) -> u32 {
590 self.start + self.frames
591 }
592
593 /// How much of its track it shows, in microseconds; `>= 1` by the
594 /// never-empty invariant.
595 pub fn window_us(&self) -> i64 {
596 self.out_us - self.in_us
597 }
598
599 /// Where in its window the timeline frame `frame` falls, in microseconds --
600 /// the cut a split, a ripple and a trim all land on.
601 ///
602 /// By proportion and not by the timeline's rate: the window and the frame
603 /// count measure the same stretch of time, so the fraction of the frames
604 /// before `frame` is the fraction of the microseconds before it. That is
605 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
606 /// without either of them learning an fps.
607 fn window_at(&self, frame: u32) -> i64 {
608 let into = i64::from(frame.saturating_sub(self.start));
609 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
610 }
611}
612
613/// One lane: what it is and what it holds. A struct rather than a bare
614/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
615/// compositing mode, a name -- and it belongs next to the clips it applies to.
616#[derive(Clone, Debug)]
617struct LaneData {
618 kind: LaneKind,
619 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
620 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
621 /// ever seeing a subtitle: they all read this list.
622 clips: Vec<Clip>,
623 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
624 /// empty on a video or audio one. Beside the clips rather than an enum over
625 /// them so that everything a lane *is* -- its place in the stack, its
626 /// label, its undo snapshot, its removal -- stays one code path for all
627 /// three kinds.
628 subs: Vec<SubClip>,
629 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
630 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
631 /// makes it a different thing from a clip's equalizer: it moves everything
632 /// on the track by the same amount, cuts included. Meaningless on a video
633 /// lane, where it is kept at 0 and asked by nothing.
634 gain_db: f32,
635}
636
637impl LaneData {
638 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
639 Self {
640 kind,
641 clips,
642 subs: Vec::new(),
643 gain_db: 0.0,
644 }
645 }
646
647 /// The two lanes a project starts with: `V1` then `A1`, in display order.
648 /// One place, because a freshly opened file is exactly this pair.
649 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
650 vec![
651 LaneData::new(LaneKind::Video, video),
652 LaneData::new(LaneKind::Audio, audio),
653 ]
654 }
655}
656
657/// The placements one group id names, split by the two lists a lane holds:
658/// what a drag, a trim and a delete each have to walk, now that a group may
659/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
660/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
661/// -- so the pairs are `(lane storage index, index into that lane's list)`.
662#[derive(Default)]
663struct Members {
664 clips: Vec<(usize, usize)>,
665 subs: Vec<(usize, usize)>,
666}
667
668impl Members {
669 /// Whether the group is the one placement and no more: what a lift leaves
670 /// behind, and what every whole-group question answers "not one" for.
671 fn alone(&self) -> bool {
672 self.clips.len() + self.subs.len() < 2
673 }
674}
675
676/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
677#[derive(Clone, Copy, PartialEq, Eq, Debug)]
678pub enum Edge {
679 /// Its first timeline frame; moving it changes where in the source the clip
680 /// starts reading, so the picture behind the edge slides with it.
681 Start,
682 /// One past its last timeline frame; moving it only says how much of the
683 /// source to keep.
684 End,
685}
686
687/// What a lane holds over one stretch of the timeline: either a placed clip or
688/// a gap. Returned already trimmed to the position it was asked about, so a
689/// caller can hand `len` straight to a decoder (or to a black-frame generator).
690#[derive(Clone, Copy, PartialEq, Eq, Debug)]
691pub struct Span {
692 /// Timeline frame the span starts at.
693 pub start: u32,
694 /// Frames it covers; `>= 1`.
695 pub len: u32,
696 /// `(source index, first source frame)`, or `None` for a gap -- which the
697 /// engine renders as black frames and as silence.
698 pub from: Option<(usize, u32)>,
699 /// The rate the clip this came off plays at ([`Clip::speed`]);
700 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
701 /// timeline frames whatever it says -- the speed is how many *source* frames
702 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
703 /// come back to the timeline.
704 pub speed: Speed,
705}
706
707impl Span {
708 /// One past the last timeline frame it covers.
709 pub fn end(&self) -> u32 {
710 self.start + self.len
711 }
712
713 /// How many source frames it reads: what a decoder is asked for and how wide
714 /// an audio window is. `len` at real time, and the one arithmetic both the
715 /// picture and the sound go through, so they cannot disagree about where a
716 /// speeded clip ends.
717 pub fn source_len(&self) -> u32 {
718 match self.from {
719 // The last timeline frame's own source frame is the last one needed
720 // -- never one more, which at a slow rate would read a frame the
721 // next clip owns and at a fast one would decode a picture nothing
722 // shows.
723 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
724 None => self.len,
725 }
726 }
727
728 /// Where a source frame of this span lands on the timeline: the stamp
729 /// playback puts on a decoded frame, through the ceil half of the pair
730 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
731 /// frame, so a frame before it stamps at the span's start.
732 pub fn timeline_at(&self, source_frame: u32) -> u32 {
733 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
734 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
735 }
736}
737
738/// What one speeded audio segment asks of the worker: how many source frames to
739/// consume per output frame, and how many seconds of timeline it has to fill.
740/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
741/// resampling at all.
742#[derive(Clone, Copy, PartialEq, Debug)]
743pub struct Stretch {
744 /// Source frames per output frame -- the speed as a multiplier.
745 pub step: f64,
746 /// What the segment owes the timeline, which is what it is padded or
747 /// trimmed to.
748 pub timeline_secs: f64,
749}
750
751/// What a save writes and a load takes back: the sources, every lane in
752/// display order with its kind, and the equalizer and colour tables their clips
753/// index into -- [`Project::without_orphan_sources`] out,
754/// [`Project::from_parts`] in.
755pub type Parts = (
756 Vec<Source>,
757 Vec<(LaneKind, Vec<Clip>)>,
758 Vec<EqParams>,
759 Vec<ColorParams>,
760);
761
762/// How many undo steps a project keeps. One gesture is one step, so 100 is past
763/// any chain a person walks back by hand, and the oldest step is dropped rather
764/// than the history growing without end: a snapshot is the whole lane list, so
765/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
766/// that grows for as long as the session lasts.
767const HISTORY_CAP: usize = 100;
768
769/// The edit list plus its undo history.
770#[derive(Clone, Debug)]
771pub struct Project {
772 /// Append-only: never popped, never reordered. See the module docs.
773 sources: Vec<Source>,
774 /// In display order, which is the order [`Lane::ord`] counts in: the nth
775 /// lane of a kind here is that kind's `ord` n. Never empty.
776 lanes: Vec<LaneData>,
777 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
778 eq: Vec<EqParams>,
779 /// The same, for [`Clip::color`].
780 color: Vec<ColorParams>,
781 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
782 /// whole lane list, so adding a lane undoes as well. Bounded by
783 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
784 history: Vec<Vec<LaneData>>,
785 /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by
786 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
787 /// the undone steps came from. Not saved to `.edith`, matching `history`.
788 redo: Vec<Vec<LaneData>>,
789 /// Never rolled back by an undo: an id retired by an undone split must not
790 /// come back and group two clips that were never together.
791 next_link: u32,
792 /// The subtitle tracks this timeline shows, in the order they were added.
793 /// Not in the lane list and not in the history snapshots, for the reason
794 /// the limiter is not: which subtitles a project carries is a setting on
795 /// it, and it is saved as a *reference* to the file the cues came out of
796 /// ([`crate::subtitle`]).
797 subtitles: Vec<SubtitleTrack>,
798 /// The master limiter every lane's sound is summed *through*
799 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
800 /// is what the history snapshots hold: it is a setting on the mix, like the
801 /// project's resolution is a setting on the picture, and neither is an undo
802 /// step.
803 limiter: Limiter,
804 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
805 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
806 /// the resolution, and not in the lane snapshots for the same reason.
807 tone: crate::tonemap::Preset,
808}
809
810impl Project {
811 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
812 /// grouped -- the state of a freshly opened video, where the timeline is the
813 /// source. `frame_count` of 0 would break the never-empty invariant, so it
814 /// is clamped to one frame.
815 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
816 let clip = Clip {
817 start: 0,
818 in_frame: 0,
819 out_frame: frame_count.max(1),
820 source: 0,
821 link: Some(0),
822 eq: None,
823 color: None,
824 fit: FitPolicy::default(),
825 speed: Speed::NORMAL,
826 };
827 Self {
828 // A file is opened on its first audio stream: nothing has picked
829 // one yet, and every file with audio at all has that one.
830 sources: vec![Source::new(path, 0)],
831 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
832 eq: Vec::new(),
833 color: Vec::new(),
834 history: Vec::new(),
835 redo: Vec::new(),
836 next_link: 1,
837 subtitles: Vec::new(),
838 limiter: Limiter::default(),
839 tone: crate::tonemap::Preset::default(),
840 }
841 }
842
843 /// A project rebuilt from a saved edit list -- the load half of
844 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
845 /// an `ord` is a lane's position among the lanes of that kind, exactly as
846 /// [`Project::lanes`] hands them back. History is *not* saved, so
847 /// [`Project::undo`] is `false` until the first edit of the new session.
848 /// This is the one door untrusted parts come in through, so every invariant
849 /// every other constructor keeps is checked here, by name and in release:
850 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
851 /// or a colour) that is not there, a clip whose end overflows, a lane that is
852 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
853 /// below.
854 ///
855 /// A project whose lanes are all *empty* is not among them: an emptied
856 /// timeline is a project like any other -- it plays black and silent, it
857 /// saves, and it loads back. What a project cannot be is laneless, because
858 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
859 /// handle indexes into.
860 pub fn from_parts(
861 sources: Vec<Source>,
862 lanes: Vec<(LaneKind, Vec<Clip>)>,
863 eq: Vec<EqParams>,
864 color: Vec<ColorParams>,
865 ) -> crate::Result<Self> {
866 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
867 return Err(format!("eq {bad} holds a band that is not a finite number").into());
868 }
869 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
870 return Err(format!("color {bad} holds a value that is not a finite number").into());
871 }
872 if lanes.is_empty() {
873 return Err("no lanes at all: that is not a project".into());
874 }
875 let lanes: Vec<LaneData> = lanes
876 .into_iter()
877 .map(|(kind, clips)| LaneData::new(kind, clips))
878 .collect();
879 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
880 let name = lane.label();
881 // A subtitle lane carries words and never a picture
882 // ([`LaneKind::Subtitle`]); a file that puts one there names a
883 // source on a lane that has nothing to play it with, and every
884 // media path below would then read a clip off a lane it does not
885 // know about.
886 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
887 return Err(format!(
888 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
889 data.clips.len()
890 )
891 .into());
892 }
893 for c in &data.clips {
894 if c.out_frame <= c.in_frame {
895 return Err(format!(
896 "{name} clip at {} plays the empty range [{}, {})",
897 c.start, c.in_frame, c.out_frame
898 )
899 .into());
900 }
901 if c.source >= sources.len() {
902 return Err(format!(
903 "{name} clip at {} names source {} of {}",
904 c.start,
905 c.source,
906 sources.len()
907 )
908 .into());
909 }
910 if c.start.checked_add(c.frames()).is_none() {
911 return Err(format!(
912 "{name} clip at {} runs past the last frame there is",
913 c.start
914 )
915 .into());
916 }
917 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
918 return Err(format!(
919 "{name} clip at {} names eq {} of {}",
920 c.start,
921 c.eq.unwrap_or_default(),
922 eq.len()
923 )
924 .into());
925 }
926 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
927 return Err(format!(
928 "{name} clip at {} names color {} of {}",
929 c.start,
930 c.color.unwrap_or_default(),
931 color.len()
932 )
933 .into());
934 }
935 }
936 if !sorted_disjoint(&data.clips) {
937 return Err(format!("the {name} lane is out of order or overlaps itself").into());
938 }
939 }
940 links_are_consistent(&lanes)?;
941 // The counter sits past every id the file names, on either of a lane's
942 // lists: a v16 caption may carry the highest link there is, and a
943 // re-issued id would silently group it with the next placement that
944 // asks for one -- the loader refusing a save the editor just wrote.
945 let next_link = lanes
946 .iter()
947 .flat_map(|l| {
948 let clips = l.clips.iter().filter_map(|c| c.link);
949 let subs = l.subs.iter().filter_map(|s| s.link);
950 clips.chain(subs)
951 })
952 .max()
953 // Saturating so a crafted file cannot make the counter wrap: at the
954 // ceiling ids stop being fresh, which loses grouping, not memory.
955 .map_or(0, |m| m.saturating_add(1));
956 Ok(Self {
957 sources: sources
958 .iter()
959 .map(|s| Source::new(&s.path, s.audio_stream))
960 .collect(),
961 lanes,
962 eq,
963 color,
964 history: Vec::new(),
965 redo: Vec::new(),
966 next_link,
967 subtitles: Vec::new(),
968 limiter: Limiter::default(),
969 tone: crate::tonemap::Preset::default(),
970 })
971 }
972
973 /// The first video lane -- what an export renders and what a single-lane
974 /// caller still means by "the clips".
975 pub fn clips(&self) -> &[Clip] {
976 self.lane(Lane::V1)
977 }
978
979 /// The clips of `lane`, or nothing at all for a lane that is not there.
980 pub fn lane(&self, lane: Lane) -> &[Clip] {
981 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
982 }
983
984 /// Every lane's handle, in display order -- what a walk over "all lanes"
985 /// iterates, and what a front-end lays out top to bottom.
986 pub fn lanes(&self) -> Vec<Lane> {
987 handles(&self.lanes)
988 }
989
990 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
991 /// for every `ord` below it, and none at or above it.
992 pub fn lane_count(&self, kind: LaneKind) -> usize {
993 self.lanes.iter().filter(|l| l.kind == kind).count()
994 }
995
996 /// Appends an empty lane of `kind` and hands back its handle. One undo
997 /// step, because the lane list is state a front-end shows: an added lane
998 /// that could not be taken back would be the one edit with no way out.
999 /// Nothing plays differently until something is placed on it.
1000 ///
1001 /// An empty lane is a lane like any other -- so is a whole project of them
1002 /// ([`Project::from_parts`]); nothing plays until something is placed.
1003 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1004 self.snapshot();
1005 self.lanes.push(LaneData::new(kind, Vec::new()));
1006 Lane::new(kind, self.lane_count(kind) - 1)
1007 }
1008
1009 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1010 /// one undo step like it, which restores the lane where it stood.
1011 ///
1012 /// Refused, changing nothing, while the lane holds anything: the refusal
1013 /// names the clips (file and first frame), because a track removal that
1014 /// deleted takes with it would be the one edit nobody sees coming. Refused
1015 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1016 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1017 /// kind and *skips* a kind that is not there), so a project without one
1018 /// would swallow half of every file dropped on it, silently.
1019 ///
1020 /// The lanes below it move up one `ord`, so a handle a caller was holding
1021 /// (a selection, an open card) names the lane after it from here on -- the
1022 /// one thing a front-end owes this call.
1023 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1024 let Some(i) = self.index(lane) else {
1025 return Err(format!("there is no {} to remove", lane.label()).into());
1026 };
1027 // A subtitle lane is not in that rule: nothing lands on one by itself
1028 // -- a project starts without any and one is added when a caption is --
1029 // so the last of them comes off like any other empty track.
1030 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1031 return Err(format!(
1032 "{} is the only {} track: every import lands on it",
1033 lane.label(),
1034 match lane.kind {
1035 LaneKind::Video => "video",
1036 LaneKind::Audio => "audio",
1037 // Unreachable while the guard above lets the last subtitle
1038 // lane go, and its own word here so the sentence stays true
1039 // if that rule is ever relaxed.
1040 LaneKind::Subtitle => "subtitle",
1041 }
1042 )
1043 .into());
1044 }
1045 if !self.lanes[i].subs.is_empty() {
1046 // Three names and a count, exactly as the clips below get: the way
1047 // out of the refusal is the drag, so the words say so.
1048 let named: Vec<String> = self.lanes[i]
1049 .subs
1050 .iter()
1051 .take(3)
1052 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1053 .collect();
1054 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1055 0 => String::new(),
1056 n => format!(" and {n} more"),
1057 };
1058 return Err(format!(
1059 "{} still holds {}{rest}: delete those captions (or drag them to \
1060 another track) first",
1061 lane.label(),
1062 named.join(", ")
1063 )
1064 .into());
1065 }
1066 let clips = &self.lanes[i].clips;
1067 if !clips.is_empty() {
1068 // Three names and a count: a lane can hold forty clips and a
1069 // refusal nobody reads to the end says nothing at all.
1070 let named: Vec<String> = clips
1071 .iter()
1072 .take(3)
1073 .map(|c| {
1074 let name = self.sources.get(c.source).map_or_else(
1075 || format!("source {}", c.source),
1076 |s| s.path.display().to_string(),
1077 );
1078 format!("{name} at frame {}", c.start)
1079 })
1080 .collect();
1081 let rest = match clips.len().saturating_sub(named.len()) {
1082 0 => String::new(),
1083 n => format!(" and {n} more"),
1084 };
1085 return Err(format!(
1086 "{} still holds {}{rest}: delete those clips (or drag them to \
1087 another track) first",
1088 lane.label(),
1089 named.join(", ")
1090 )
1091 .into());
1092 }
1093 self.snapshot();
1094 self.lanes.remove(i);
1095 Ok(())
1096 }
1097
1098 /// Moves `lane` to display position `to` -- an index into
1099 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1100 /// the handle it answers to from now on. `None`, changing nothing and
1101 /// snapshotting nothing, for a lane that is not there, a position that is
1102 /// not, and a lane already standing in it.
1103 ///
1104 /// The whole track travels: its clips, its gain, its kind. Nothing is
1105 /// remapped, so no take changes lane and no group is broken -- this is the
1106 /// *order* of the lanes and nothing else, which is why one call is one undo
1107 /// step like an add or a removal.
1108 ///
1109 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1110 /// last video lane covering a frame, so moving one video lane past another
1111 /// changes which picture wins, in the preview and in an export alike. The
1112 /// audio lanes are summed and their sum does not care about order, so an
1113 /// audio track moved among the video ones is a rearrangement of the screen
1114 /// alone.
1115 ///
1116 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1117 /// position among the lanes of that kind), so a lane that crosses one of
1118 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1119 /// `V1`, clips and all -- while one that crosses only lanes of the other
1120 /// kind keeps its name. That is the returned handle: unchanged means every
1121 /// handle a caller holds still names the track it named before.
1122 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1123 let i = self.index(lane)?;
1124 if to >= self.lanes.len() || to == i {
1125 return None;
1126 }
1127 self.snapshot();
1128 let data = self.lanes.remove(i);
1129 self.lanes.insert(to, data);
1130 Some(handles(&self.lanes)[to])
1131 }
1132
1133 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1134 /// not there. The one place a handle becomes a position.
1135 fn index(&self, lane: Lane) -> Option<usize> {
1136 self.lanes
1137 .iter()
1138 .enumerate()
1139 .filter(|(_, l)| l.kind == lane.kind)
1140 .map(|(i, _)| i)
1141 .nth(lane.ord)
1142 }
1143
1144 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1145 let i = self.index(lane)?;
1146 Some(&mut self.lanes[i].clips)
1147 }
1148
1149 /// The files the clips index into, in import order; index 0 is the file the
1150 /// project was opened with.
1151 pub fn sources(&self) -> &[Source] {
1152 &self.sources
1153 }
1154
1155 /// The same list in the `(path, stream)` shape the audio engine indexes
1156 /// into -- [`crate::AudioSession::open_multi_streams`] and
1157 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1158 /// was placed with is the stream that plays *and* the stream that exports.
1159 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1160 self.sources
1161 .iter()
1162 .map(|s| (s.path.clone(), s.audio_stream))
1163 .collect()
1164 }
1165
1166 /// Index for `path` played on `audio_stream`, appending it if it is new.
1167 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1168 /// by two paths imports once and two streams of one file are two sources.
1169 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1170 /// no history: a source entry alone changes nothing playable.
1171 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1172 let source = Source::new(path, audio_stream);
1173 match self.sources.iter().position(|s| *s == source) {
1174 Some(idx) => idx,
1175 None => {
1176 self.sources.push(source);
1177 self.sources.len() - 1
1178 }
1179 }
1180 }
1181
1182 /// Append a whole-file clip of `source` to the end of every *media* lane,
1183 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1184 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1185 /// come in through [`Project::add_subtitles`], which is the palette.
1186 ///
1187 /// One history snapshot, so an import is one undo step, and undoing it
1188 /// leaves the (harmless) source entry behind, because indexes are forever.
1189 /// Refused for an unknown source index.
1190 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1191 if source >= self.sources.len() {
1192 return false;
1193 }
1194 self.snapshot();
1195 let start = self.timeline_frames();
1196 let clip = Clip {
1197 start,
1198 in_frame: 0,
1199 out_frame: frame_count.max(1),
1200 source,
1201 link: Some(self.new_link()),
1202 eq: None,
1203 color: None,
1204 fit: FitPolicy::default(),
1205 speed: Speed::NORMAL,
1206 };
1207 for data in self
1208 .lanes
1209 .iter_mut()
1210 .filter(|l| l.kind != LaneKind::Subtitle)
1211 {
1212 data.clips.push(clip);
1213 }
1214 true
1215 }
1216
1217 /// Drops a source entry -- the file a library row *is* -- and renumbers
1218 /// every clip that indexed past it, which is why this is more than a
1219 /// `Vec::remove`.
1220 ///
1221 /// Refused, changing nothing, while any clip still plays from it: the
1222 /// refusal names the lanes and how many clips each holds, so a caller can
1223 /// say what has to be deleted first. The *last* entry goes like any other
1224 /// -- a project may name no file at all, which is an empty library over an
1225 /// empty timeline (nothing can play, since a clip would have refused the
1226 /// removal). What a front-end does with that is its own decision: `edith`'s
1227 /// window goes back to the empty state it launches in, and
1228 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1229 /// refuses to write a project that names nothing, because no such file
1230 /// could be opened again.
1231 ///
1232 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1233 /// source index of its own -- a clipboard, which is the one thing outside
1234 /// this type that does -- has to fix it up or drop it, or a paste plays a
1235 /// different file. [`PlaybackSession::remove_source`] hands back the index
1236 /// that went for exactly that.
1237 ///
1238 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1239 /// snapshot older than the removal can name the very source being removed
1240 /// (delete a file's clips, then remove the file) and restoring it would
1241 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1242 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1243 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1244 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1245 /// exists) currently rules out.
1246 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1247 let Some(source) = self.sources.get(idx) else {
1248 return Err(format!("there is no source {idx} to remove").into());
1249 };
1250 let name = source.path.display().to_string();
1251 let used: Vec<String> = handles(&self.lanes)
1252 .into_iter()
1253 .zip(&self.lanes)
1254 .filter_map(
1255 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1256 0 => None,
1257 1 => Some(format!("{} (1 clip)", lane.label())),
1258 n => Some(format!("{} ({n} clips)", lane.label())),
1259 },
1260 )
1261 .collect();
1262 if !used.is_empty() {
1263 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1264 }
1265 self.sources.remove(idx);
1266 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1267 if c.source > idx {
1268 c.source -= 1;
1269 }
1270 }
1271 self.history.clear();
1272 Ok(())
1273 }
1274
1275 /// The sources a clip actually names, with the clips reindexed onto them
1276 /// -- what a save writes. Indexes are forever *inside* a session (see
1277 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1278 /// entry behind; writing that orphan to a project file would let a file
1279 /// nothing plays refuse a future load. New indexes are assigned in order of
1280 /// first use -- lane by lane, in display order -- so the same project always
1281 /// emits the same bytes.
1282 ///
1283 /// Every lane comes out, in display order and with its kind: that is what a
1284 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1285 /// takes back.
1286 ///
1287 /// The equalizer and colour tables are pruned the same way and for the same
1288 /// reason: an undone [`set_eq`](Project::set_eq) or
1289 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1290 /// and this is the one moment they can go -- the indexes that survive it are
1291 /// only the ones a clip names.
1292 ///
1293 /// One exception, and it is the emptied timeline's: a project no clip plays
1294 /// from still keeps its first source, if it has one. A file is what a
1295 /// reopened project scaffolds itself from -- the frame rate is written
1296 /// nowhere else -- so a save that pruned the last of them would write a
1297 /// project that cannot be loaded back at all.
1298 ///
1299 /// What comes out is *not* ordered by anything a reader may assume: first
1300 /// use, lane by lane, means the entry at index 0 can be a still or a song
1301 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1302 /// picks its rate and its audio reference by what a source *is*, never by
1303 /// where it sits.
1304 pub fn without_orphan_sources(&self) -> Parts {
1305 let mut moved = vec![None; self.sources.len()];
1306 let mut sources = Vec::new();
1307 let mut moved_eq = vec![None; self.eq.len()];
1308 let mut eq = Vec::new();
1309 let mut moved_color = vec![None; self.color.len()];
1310 let mut color = Vec::new();
1311 let mut lanes = self.lanes.clone();
1312 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1313 let old = c.source;
1314 c.source = match moved[old] {
1315 Some(new) => new,
1316 None => {
1317 sources.push(self.sources[old].clone());
1318 moved[old] = Some(sources.len() - 1);
1319 sources.len() - 1
1320 }
1321 };
1322 if let Some(old) = c.eq.map(usize::from) {
1323 c.eq = Some(match moved_eq[old] {
1324 Some(new) => new,
1325 None => {
1326 eq.push(self.eq[old].clone());
1327 let new = (eq.len() - 1) as u16;
1328 moved_eq[old] = Some(new);
1329 new
1330 }
1331 });
1332 }
1333 if let Some(old) = c.color.map(usize::from) {
1334 c.color = Some(match moved_color[old] {
1335 Some(new) => new,
1336 None => {
1337 color.push(self.color[old]);
1338 let new = (color.len() - 1) as u16;
1339 moved_color[old] = Some(new);
1340 new
1341 }
1342 });
1343 }
1344 }
1345 if sources.is_empty() {
1346 sources.extend(self.sources.first().cloned());
1347 }
1348 (
1349 sources,
1350 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1351 // comes out for one is an empty list, and its *place* in the display
1352 // order is what a save writes it for. What is on it travels beside
1353 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1354 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1355 eq,
1356 color,
1357 )
1358 }
1359
1360 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1361 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1362 /// track moves by it, which is what makes it a different control from a
1363 /// clip's equalizer (one frequency range of one take) and from the master
1364 /// volume (what this machine monitors at, which no file carries).
1365 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1366 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1367 }
1368
1369 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1370 /// One undo step like every other edit -- it is in the lane list, so an
1371 /// undo restores it with the rest. `false`, and no history, for a lane that
1372 /// is not there, for a value that is not finite, and for one already set.
1373 ///
1374 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1375 /// a value nobody reads: words have no loudness, so a slider that appeared
1376 /// to move one would be a control with no effect. (A video lane's gain is
1377 /// meaningless in the same way but is kept settable: it is the pair `A1`
1378 /// carries for a take, and mixing reads it off the audio lane alone.)
1379 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1380 let Some(i) = self.index(lane) else {
1381 return false;
1382 };
1383 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1384 return false;
1385 }
1386 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1387 if self.lanes[i].gain_db == db {
1388 return false;
1389 }
1390 self.snapshot();
1391 self.lanes[i].gain_db = db;
1392 true
1393 }
1394
1395 /// Every lane's volume in dB, in display order -- what a save writes,
1396 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1397 ///
1398 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1399 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1400 /// one): a save zips the two lists, so a lane that is in one and not the
1401 /// other would hand every track below it the volume of the track above.
1402 pub fn lane_gains(&self) -> Vec<f32> {
1403 self.lanes.iter().map(|l| l.gain_db).collect()
1404 }
1405
1406 /// What is placed on every lane, in display order and in step with
1407 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1408 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1409 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1410 ///
1411 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1412 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1413 /// clip's source there is no orphan to prune and no index to move.
1414 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1415 self.lanes.iter().map(|l| l.subs.clone()).collect()
1416 }
1417
1418 /// The placements a *load* puts back, one list per lane in display order --
1419 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1420 /// same reason. Called *after*
1421 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1422 /// names.
1423 ///
1424 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1425 /// like it, by name and in release, because it is the same untrusted file:
1426 /// a placement on a lane that is not a subtitle lane, an empty span or an
1427 /// empty window, a track the palette does not have, a span running past the
1428 /// last frame there is, and a lane that is out of order or overlaps itself
1429 /// ([`place_sub`] refuses every one of those on the live timeline).
1430 ///
1431 /// [`place_sub`]: Project::place_sub
1432 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1433 let names = handles(&self.lanes);
1434 let palette = self.subtitles.len();
1435 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1436 let name = lane.label();
1437 if list.is_empty() {
1438 continue;
1439 }
1440 if data.kind != LaneKind::Subtitle {
1441 return Err(format!(
1442 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1443 subtitle track",
1444 list.len()
1445 )
1446 .into());
1447 }
1448 for s in &list {
1449 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1450 return Err(format!(
1451 "{name} caption at {} is empty: {} frames of [{}, {})",
1452 s.start, s.frames, s.in_us, s.out_us
1453 )
1454 .into());
1455 }
1456 if s.track >= palette {
1457 return Err(format!(
1458 "{name} caption at {} names subtitle track {} of {palette}",
1459 s.start, s.track
1460 )
1461 .into());
1462 }
1463 if s.start.checked_add(s.frames).is_none() {
1464 return Err(format!(
1465 "{name} caption at {} runs past the last frame there is",
1466 s.start
1467 )
1468 .into());
1469 }
1470 }
1471 if !subs_sorted_disjoint(&list) {
1472 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1473 }
1474 data.subs = list;
1475 // The counter also has to clear the ids these captions carry: this
1476 // is the door a load's placements come through, *after*
1477 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1478 // a hand-grouped caption may carry the highest id in the file.
1479 self.next_link = self.next_link.max(
1480 data.subs
1481 .iter()
1482 .filter_map(|s| s.link)
1483 .max()
1484 .map_or(0, |m| m.saturating_add(1)),
1485 );
1486 }
1487 Ok(self)
1488 }
1489
1490 /// The mix settings a *load* puts back: lane volumes in display order (a
1491 /// short list leaves the rest at unity) and the master limiter, both
1492 /// clamped as their setters clamp them.
1493 ///
1494 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1495 /// setters push an undo step, and a project that arrives one undo away from
1496 /// a state it was never in is a project whose first ctrl+z is a surprise.
1497 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1498 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1499 if db.is_finite() {
1500 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1501 }
1502 }
1503 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1504 self
1505 }
1506
1507 /// The HDR rendition a *load* puts back -- the same door
1508 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1509 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1510 self.tone = preset;
1511 self
1512 }
1513
1514 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1515 /// project setting, not a clip's: one picture, one look
1516 /// ([`crate::tonemap::Preset`]).
1517 pub fn tone(&self) -> crate::tonemap::Preset {
1518 self.tone
1519 }
1520
1521 /// Sets it. `false` for the one already in force, which is what keeps a
1522 /// re-pick of the current rendition from costing a reseek.
1523 ///
1524 /// corner-cut: not an undo step, for the reason the limiter and the project
1525 /// resolution are not -- it is not in the lane list the history snapshots.
1526 /// Upgrade path is the same one: a history entry holding the project's own
1527 /// settings beside the lanes.
1528 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1529 if self.tone == preset {
1530 return false;
1531 }
1532 self.tone = preset;
1533 true
1534 }
1535
1536 /// The subtitle tracks a *load* puts back, in the order they were saved --
1537 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1538 /// the same reason.
1539 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1540 self.subtitles = tracks;
1541 self
1542 }
1543
1544 /// What this timeline shows over the picture, in the order they were added:
1545 /// what a front-end lists and what a save writes.
1546 pub fn subtitles(&self) -> &[SubtitleTrack] {
1547 &self.subtitles
1548 }
1549
1550 /// Adds a track, unless the very same one -- same file, same track number
1551 /// inside it -- is already on the list. `false` for that repeat: importing
1552 /// the same `.srt` twice is one subtitle track, not two identical ones.
1553 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1554 if self
1555 .subtitles
1556 .iter()
1557 .any(|t| t.path == track.path && t.track == track.track)
1558 {
1559 return false;
1560 }
1561 self.subtitles.push(track.clone());
1562 true
1563 }
1564
1565 /// Takes the track at `idx` off the list -- what a row's own remove goes
1566 /// through, so whatever an import added can be taken back out. Refused by
1567 /// name for a row this project does not have, rather than a silent no-op:
1568 /// a front-end holding a stale index has picked the wrong row and needs to
1569 /// hear it.
1570 ///
1571 /// Every index past `idx` moves down by one, as [`remove_source`](
1572 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1573 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1574 /// it, or it names a different track afterwards. The placements on the
1575 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1576 /// index into this very list, so every one past `idx` is walked down with
1577 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1578 /// for its clips, for its reason.
1579 ///
1580 /// Refused, changing nothing, while anything placed on a subtitle lane
1581 /// plays *this* row: the placement would have to be deleted or retargeted,
1582 /// and either one is an edit nobody asked for. The refusal names the lane
1583 /// and the frame it is at, up to three of them --
1584 /// [`remove_source`](Project::remove_source) refuses the same way for the
1585 /// same silent corruption.
1586 ///
1587 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1588 /// history snapshots hold the lane list and subtitles are not on it
1589 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1590 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1591 /// door, which reads the subtitles of a file and nothing else -- and not a
1592 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1593 /// entry holding the project's own settings beside the lanes. The history
1594 /// is *cleared* rather than kept, as a source removal clears it: the
1595 /// snapshots hold the indexes as they were before the reindex, so an undo
1596 /// into one would put every placement past `idx` on the wrong track.
1597 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1598 if idx >= self.subtitles.len() {
1599 return Err(format!("there is no subtitle track {idx} to remove").into());
1600 }
1601 let placed: Vec<String> = handles(&self.lanes)
1602 .into_iter()
1603 .zip(&self.lanes)
1604 .flat_map(|(lane, data)| {
1605 data.subs
1606 .iter()
1607 .filter(move |s| s.track == idx)
1608 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1609 })
1610 .take(3)
1611 .collect();
1612 if !placed.is_empty() {
1613 return Err(format!(
1614 "{} is on the timeline ({}): delete those clips first",
1615 self.track_name(idx),
1616 placed.join(", ")
1617 )
1618 .into());
1619 }
1620 self.subtitles.remove(idx);
1621 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1622 if s.track > idx {
1623 s.track -= 1;
1624 }
1625 }
1626 self.history.clear();
1627 Ok(())
1628 }
1629
1630 /// What a refusal calls a palette row: the name the panel shows, and the
1631 /// index alone for a row that is not there.
1632 fn track_name(&self, track: usize) -> String {
1633 self.subtitles
1634 .get(track)
1635 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1636 }
1637
1638 /// The subtitle lanes in display order -- what a front-end lays out and
1639 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1640 /// [`audio_lanes`](Project::audio_lanes).
1641 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1642 self.lanes()
1643 .into_iter()
1644 .filter(|l| l.kind == LaneKind::Subtitle)
1645 .collect()
1646 }
1647
1648 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1649 /// for a subtitle track, and empty for every other lane and for one that is
1650 /// not there.
1651 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1652 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1653 }
1654
1655 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1656 /// twin, with one deliberate difference: it **refuses** an overlap instead
1657 /// of overwriting what it lands on.
1658 ///
1659 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1660 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1661 /// carries is a *window of a track* and where the hand let go, and the
1662 /// second of those is the argument. So a caller builds the placement once
1663 /// (from the palette row it dragged) and drops it at as many frames as it
1664 /// likes without rewriting the field each time.
1665 ///
1666 /// A picture placed over a picture hides it and the hidden one is still
1667 /// there to drag back out; two captions in one frame are two lines nobody
1668 /// asked to stack, and the words that lost are gone from the screen with
1669 /// nothing to show for it. So the refusal names the placement in the way,
1670 /// and the caller picks another frame or another lane -- which is what a
1671 /// second subtitle lane is for.
1672 ///
1673 /// One undo step on success, and none on any refusal: an empty window or an
1674 /// empty span, a track the palette does not have
1675 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1676 /// subtitle lane, a span that would run past the last frame there is, and
1677 /// the overlap above.
1678 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1679 if lane.kind != LaneKind::Subtitle {
1680 return Err(format!(
1681 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1682 the others",
1683 lane.label()
1684 )
1685 .into());
1686 }
1687 let Some(i) = self.index(lane) else {
1688 return Err(format!("there is no {} to place on", lane.label()).into());
1689 };
1690 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1691 return Err(format!(
1692 "that placement is empty: {} frames of [{}, {})",
1693 sub.frames, sub.in_us, sub.out_us
1694 )
1695 .into());
1696 }
1697 if sub.track >= self.subtitles.len() {
1698 return Err(format!(
1699 "it names subtitle track {} of {}",
1700 sub.track,
1701 self.subtitles.len()
1702 )
1703 .into());
1704 }
1705 // The placement belongs to no group, for [`place`]'s reason: a caption
1706 // dragged out of the palette arrives alone, and grouping it with what
1707 // is under it is a hand's decision ([`Project::group_all`]).
1708 let sub = SubClip {
1709 start: at,
1710 link: None,
1711 ..sub
1712 };
1713 if at.checked_add(sub.frames).is_none() {
1714 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1715 }
1716 if let Some(other) = self.lanes[i]
1717 .subs
1718 .iter()
1719 .find(|o| o.end() > sub.start && o.start < sub.end())
1720 {
1721 return Err(format!(
1722 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1723 on another subtitle track",
1724 lane.label(),
1725 other.start,
1726 other.start,
1727 other.end()
1728 )
1729 .into());
1730 }
1731 self.snapshot();
1732 let subs = &mut self.lanes[i].subs;
1733 let idx = subs.partition_point(|o| o.start < sub.start);
1734 subs.insert(idx, sub);
1735 debug_assert!(subs_sorted_disjoint(subs));
1736 Ok(())
1737 }
1738
1739 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1740 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1741 /// refused an overlap where that one clamps to it, for
1742 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1743 /// still and no picture under it that a landing would hide, so "as far as
1744 /// it goes" would silently be a frame nobody named.
1745 ///
1746 /// A caption *in* a group drags the group: one delta for every member --
1747 /// its clips and its other captions -- clamped to the room each of them
1748 /// has, exactly as a clip's drag always has. That is the point of putting
1749 /// a caption in a group: the words go where the picture goes.
1750 ///
1751 /// The window travels untouched: a caption dragged later says the same
1752 /// words later, exactly as a clip dragged later plays the same pictures
1753 /// later.
1754 ///
1755 /// One undo step on success; nothing changed and no step on a refusal --
1756 /// an index that is not there, a lane that is not a subtitle lane or is not
1757 /// there, and (for a caption in no group) an overlap. A drop that changes
1758 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1759 /// up and put it back has done nothing wrong, and a front-end showing every
1760 /// `Err` would say so.
1761 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1762 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1763 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1764 };
1765 if to.kind != LaneKind::Subtitle {
1766 return Err(format!(
1767 "{} is not a subtitle track: a caption cannot play on it",
1768 to.label()
1769 )
1770 .into());
1771 }
1772 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1773 return Err(format!("there is no {} to move onto", to.label()).into());
1774 };
1775 if (here, start) == (dest, sub.start) {
1776 // A pick-up-put-back: the drag ended where it began, which is not a
1777 // mistake to name -- `Ok`, and no undo step, because nothing
1778 // changed. A refusal here would toast a hand that did nothing.
1779 return Ok(());
1780 }
1781 if start.checked_add(sub.frames).is_none() {
1782 return Err(
1783 format!("a placement at frame {start} runs past the last frame there is").into(),
1784 );
1785 }
1786 // A grouped caption carries its group, clamped to the room the whole
1787 // group has rather than refused ([`Project::move_room]) -- one drag, one
1788 // delta, one undo step.
1789 let members = self.group_of(from, idx).expect("the subtitle was found");
1790 if !members.alone() {
1791 if members
1792 .subs
1793 .iter()
1794 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1795 {
1796 return Err(format!(
1797 "a group is one caption per track: {} already carries this group",
1798 to.label()
1799 )
1800 .into());
1801 }
1802 let want = i64::from(start) - i64::from(sub.start);
1803 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1804 return Err(format!(
1805 "another placement already covers those frames on {}",
1806 to.label()
1807 )
1808 .into());
1809 };
1810 let delta = want.clamp(lo, hi);
1811 self.snapshot();
1812 for &(l, i) in &members.clips {
1813 let c = &mut self.lanes[l].clips[i];
1814 c.start = (i64::from(c.start) + delta) as u32;
1815 }
1816 for &(l, i) in &members.subs {
1817 let s = &mut self.lanes[l].subs[i];
1818 s.start = (i64::from(s.start) + delta) as u32;
1819 }
1820 let moved = self.lanes[here].subs.remove(idx);
1821 let subs = &mut self.lanes[dest].subs;
1822 let at = subs.partition_point(|o| o.start < moved.start);
1823 subs.insert(at, moved);
1824 debug_assert!(subs_sorted_disjoint(subs));
1825 debug_assert!(members
1826 .clips
1827 .iter()
1828 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1829 return Ok(());
1830 }
1831 let moved = SubClip { start, ..sub };
1832 if let Some(other) = self.lanes[dest]
1833 .subs
1834 .iter()
1835 .enumerate()
1836 .find(|&(j, o)| {
1837 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
1838 })
1839 .map(|(_, o)| *o)
1840 {
1841 return Err(format!(
1842 "the {} subtitle at frame {} already covers [{}, {})",
1843 to.label(),
1844 other.start,
1845 other.start,
1846 other.end()
1847 )
1848 .into());
1849 }
1850 self.snapshot();
1851 self.lanes[here].subs.remove(idx);
1852 let subs = &mut self.lanes[dest].subs;
1853 let at = subs.partition_point(|o| o.start < moved.start);
1854 subs.insert(at, moved);
1855 debug_assert!(subs_sorted_disjoint(subs));
1856 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
1857 Ok(())
1858 }
1859
1860 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
1861 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
1862 /// pulling an edge past what is legal means "as far as it goes".
1863 ///
1864 /// The window follows the edge, in the seconds the frames are worth at
1865 /// `fps`: a head pulled in starts the caption later *in its track* (the
1866 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
1867 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
1868 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
1869 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
1870 /// needed here and nowhere else in this file, because a trim is the only
1871 /// edit that changes a *duration*.
1872 ///
1873 /// The walls: one frame always survives, an edge never crosses the
1874 /// neighbouring subtitle on its own lane, a head never walks back past the
1875 /// track's own start (`in_us` of 0), and a tail never runs past the last
1876 /// cue the track has -- which is the source length a media trim needs a
1877 /// caller's table for, and which this one can simply read.
1878 ///
1879 /// `Err`, with nothing changed and no undo step, for an index that is not
1880 /// there and an unusable `fps`. An edge that ends up where it already was
1881 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
1882 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
1883 /// reason: a drag that stops at a wall is not a mistake to report.
1884 pub fn trim_sub(
1885 &mut self,
1886 lane: Lane,
1887 idx: usize,
1888 edge: Edge,
1889 to: u32,
1890 fps: f64,
1891 ) -> crate::Result<()> {
1892 if !(fps.is_finite() && fps > 0.0) {
1893 return Err(format!("{fps} is not a frame rate to trim against").into());
1894 }
1895 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
1896 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
1897 };
1898 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
1899 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
1900 };
1901 let to = to.clamp(lo, hi);
1902 let at = match edge {
1903 Edge::Start => sub.start,
1904 Edge::End => sub.end(),
1905 };
1906 if to == at {
1907 // The edge is where it was asked to go -- either the hand did not
1908 // move it, or the clamp above stopped it at a wall it was already
1909 // standing against. Both are a drag that changed nothing: `Ok`, no
1910 // undo step, and no toast for a box that simply stopped moving.
1911 return Ok(());
1912 }
1913 self.snapshot();
1914 let members = self.group_of(lane, idx).expect("the subtitle was found");
1915 let i = self.index(lane).expect("the subtitle was found on it");
1916 let s = &mut self.lanes[i].subs[idx];
1917 match edge {
1918 // The words that stay are the words that were there, so the window
1919 // moves with the head -- a trim, not a slip.
1920 Edge::Start => {
1921 // Clamped to a window that is still a window: the walls above
1922 // are frames and the rounding between the two clocks is not
1923 // exact, and neither is a caller's hand-built placement.
1924 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
1925 .clamp(0, s.out_us - 1);
1926 s.frames = s.end() - to;
1927 s.start = to;
1928 }
1929 Edge::End => {
1930 s.out_us =
1931 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
1932 s.frames = to - s.start;
1933 }
1934 }
1935 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
1936 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
1937 // A caption in a group drags its group's edge with it, exactly as a
1938 // clip's trim does: one delta, each member clamped to its own room.
1939 // No source table to grow by, which only tightens how far a member may
1940 // follow -- never whether it may.
1941 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
1942 Ok(())
1943 }
1944
1945 /// How far that edge may travel, `(first, last)` timeline frame inclusive
1946 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
1947 /// drawing the box during a drag asks. `None` for an index that is not
1948 /// there.
1949 pub fn trim_sub_room(
1950 &self,
1951 lane: Lane,
1952 idx: usize,
1953 edge: Edge,
1954 fps: f64,
1955 ) -> Option<(u32, u32)> {
1956 let subs = self.sub_lane(lane);
1957 let s = *subs.get(idx)?;
1958 // How many timeline frames a stretch of the track is worth, which is
1959 // what turns its two walls -- its own start, and its last cue -- into
1960 // frames. A rate that is not a rate leaves the window where it is.
1961 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
1962 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
1963 false => 0,
1964 };
1965 Some(match edge {
1966 Edge::Start => (
1967 s.start
1968 .saturating_sub(frames_of(s.in_us))
1969 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
1970 s.end() - 1,
1971 ),
1972 Edge::End => {
1973 // Out to the end of the track it reads, and never over the
1974 // subtitle behind it. A track the palette no longer has (or one
1975 // with no cues at all) may not grow, exactly as a source with no
1976 // entry in a media trim's table may not.
1977 let track_end = self
1978 .subtitles
1979 .get(s.track)
1980 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
1981 .unwrap_or(s.out_us);
1982 (
1983 s.start + 1,
1984 s.start
1985 .saturating_add(frames_of(track_end - s.in_us).max(1))
1986 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
1987 )
1988 }
1989 })
1990 }
1991
1992 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
1993 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
1994 /// `false` for an index that is not there (which a lane that is not a
1995 /// subtitle lane always is).
1996 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
1997 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
1998 return false;
1999 };
2000 self.snapshot();
2001 self.lanes[i].subs.remove(idx);
2002 true
2003 }
2004
2005 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2006 /// window of its track, clipped to that window and shifted to where the
2007 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2008 /// carried through the picture's spans -- this is its twin for a track that
2009 /// is placed on a lane of its own, and it is what a preview draws and what
2010 /// an export of the lane would write.
2011 ///
2012 /// Cut, not stretched: a cue half inside the window keeps the half that is
2013 /// inside, and a cue wholly outside it is gone -- the same rule the media
2014 /// spans follow. `fps` is the timeline's rate, needed here because a
2015 /// placement's *position* is in frames while its words are in microseconds.
2016 ///
2017 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2018 /// of their cues, no file opened), which is how a front-end asks it.
2019 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2020 if !(fps.is_finite() && fps > 0.0) {
2021 return Vec::new();
2022 }
2023 let mut out = Vec::new();
2024 for s in self.sub_lane(lane) {
2025 let Some(track) = self.subtitles.get(s.track) else {
2026 // A placement whose track was taken off the palette
2027 // ([`Project::remove_subtitles`]) shows nothing rather than
2028 // showing another track's words.
2029 continue;
2030 };
2031 // Where the placement's own first microsecond lands on the
2032 // timeline, and how many microseconds of timeline one microsecond
2033 // of the window is worth: the placement's own proportion, which a
2034 // group's re-rate changes (the frames compress, the window does
2035 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2036 // every cue lands where it always did; at 2x the words cross the
2037 // screen in half the time, cue for cue.
2038 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2039 let onto = |t: i64| {
2040 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2041 };
2042 for cue in &track.cues {
2043 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2044 if b <= a {
2045 continue; // wholly outside the window this placement keeps
2046 }
2047 out.push(SubtitleCue {
2048 start_us: onto(a),
2049 end_us: onto(b),
2050 text: cue.text.clone(),
2051 image: cue.image.clone(),
2052 });
2053 }
2054 }
2055 // The placements come in timeline order, but two lanes' worth (or a
2056 // track whose cues a window reordered) do not.
2057 out.sort_by_key(|cue| cue.start_us);
2058 out
2059 }
2060
2061 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2062 /// lanes is multiplied by on its way into the mix: the same lanes in the
2063 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2064 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2065 /// the bit-exact path.
2066 pub fn audio_gains(&self) -> Vec<f32> {
2067 self.audio_lanes()
2068 .into_iter()
2069 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2070 .collect()
2071 }
2072
2073 /// The master limiter the mix is summed through. A project setting, not a
2074 /// clip's and not a lane's: there is one mix.
2075 pub fn limiter(&self) -> Limiter {
2076 self.limiter
2077 }
2078
2079 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2080 /// for a setting already in force.
2081 ///
2082 /// corner-cut: not an undo step, for the reason the project resolution is not
2083 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2084 /// lane list the history snapshots. Upgrade path is a history entry that
2085 /// holds the mix settings beside the lanes.
2086 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2087 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2088 if self.limiter == limiter {
2089 return false;
2090 }
2091 self.limiter = limiter;
2092 true
2093 }
2094
2095 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2096 /// plays flat (and for an index that is not there) -- what a feeder and an
2097 /// export ask before they build an [`crate::eq::EqState`].
2098 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2099 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2100 }
2101
2102 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2103 /// take them off. One undo step, like every other edit. `false` -- and no
2104 /// history -- for an index that is not there and for params holding a value
2105 /// that is not finite, which is the one thing the file format could not
2106 /// write and read back.
2107 ///
2108 /// Settings equal to ones already in the table share their entry, so a
2109 /// project that puts the same curve on twenty clips writes it once.
2110 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2111 if idx >= self.lane(lane).len() {
2112 return false;
2113 }
2114 let slot = match params {
2115 None => None,
2116 Some(params) => {
2117 if !finite(&params) {
2118 return false;
2119 }
2120 Some(match self.eq.iter().position(|p| *p == params) {
2121 Some(at) => at as u16,
2122 // corner-cut: the table is append-only within a session (see
2123 // the module docs) and `Clip::eq` is a u16, so the 65535th
2124 // *distinct* setting of one session is refused rather than
2125 // silently aliased. Upgrade path if a UI ever drags a slider
2126 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2127 // snapshot the table into the history and compact it here.
2128 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2129 None => {
2130 self.eq.push(params);
2131 (self.eq.len() - 1) as u16
2132 }
2133 })
2134 }
2135 };
2136 self.snapshot();
2137 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2138 true
2139 }
2140
2141 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2142 /// ungraded (and for an index that is not there) -- what the renderer and
2143 /// the export ask before they call [`crate::color::apply_yuv`].
2144 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2145 self.color
2146 .get(usize::from(self.lane(lane).get(idx)?.color?))
2147 }
2148
2149 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2150 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2151 /// (and no history) for an index that is not there or a value that is not
2152 /// finite, and equal settings share a table entry.
2153 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2154 self.write_color(lane, idx, params, true)
2155 }
2156
2157 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2158 /// one pointer drag, whose first write (a plain `set_color`) already took the
2159 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2160 /// not one per pixel -- and undoing it lands where the hand picked it up.
2161 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2162 self.write_color(lane, idx, params, false)
2163 }
2164
2165 fn write_color(
2166 &mut self,
2167 lane: Lane,
2168 idx: usize,
2169 params: Option<ColorParams>,
2170 snapshot: bool,
2171 ) -> bool {
2172 if idx >= self.lane(lane).len() {
2173 return false;
2174 }
2175 let slot = match params {
2176 None => None,
2177 Some(params) => {
2178 if !color_finite(&params) {
2179 return false;
2180 }
2181 Some(match self.color.iter().position(|p| *p == params) {
2182 Some(at) => at as u16,
2183 // corner-cut: the 65535th *distinct* grade of one session is
2184 // refused rather than silently aliased, exactly as `set_eq`
2185 // refuses the 65535th curve; same upgrade path.
2186 None if self.color.len() >= usize::from(u16::MAX) => return false,
2187 None => {
2188 self.color.push(params);
2189 (self.color.len() - 1) as u16
2190 }
2191 })
2192 }
2193 };
2194 if snapshot {
2195 self.snapshot();
2196 }
2197 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2198 true
2199 }
2200
2201 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2202 /// index that is not there, which is what every clip starts at anyway.
2203 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2204 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2205 }
2206
2207 /// Sets it, for the clip **and its whole group**: a link is one span on
2208 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2209 /// from its sound would be a group no save could load. One snapshot, so the
2210 /// group's change is one [`Project::undo`].
2211 ///
2212 /// The source range is untouched -- a speed says how many timeline frames
2213 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2214 /// split still address the file afterwards.
2215 ///
2216 /// Refused, changing nothing and costing no undo step, when the clip would
2217 /// grow into the one after it on its own lane: slowing a clip down makes it
2218 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2219 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2220 /// something a user can go and fix. Also for an index that is not there.
2221 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2222 self.write_speed(lane, idx, speed, true)
2223 }
2224
2225 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2226 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2227 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2228 /// not one per rate it passed through -- exactly as
2229 /// [`set_color_live`](Self::set_color_live) is for a slider.
2230 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2231 self.write_speed(lane, idx, speed, false)
2232 }
2233
2234 fn write_speed(
2235 &mut self,
2236 lane: Lane,
2237 idx: usize,
2238 speed: Speed,
2239 snapshot: bool,
2240 ) -> crate::Result<()> {
2241 let Some(members) = self.group_of(lane, idx) else {
2242 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2243 };
2244 let labels = handles(&self.lanes);
2245 // The clip the hand is holding is the group's clock: everything else
2246 // in the group, caption members included, re-times by the ratio its new
2247 // rate gives its own frames. The clips take the rate itself; a caption
2248 // has none, so it takes the *ratio* -- its span on the timeline
2249 // compresses or stretches about the held clip's head, while the words
2250 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2251 // timeline moves, the track does not).
2252 let Some(held) = self.lane(lane).get(idx).copied() else {
2253 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2254 };
2255 // The same per-member piece `speeded_playhead` builds for this op,
2256 // asked here instead of read there -- a caption's length comes from
2257 // the map's own ends (`end - start`), never `round(len * ratio)`
2258 // separately, which is what let the two answers drift apart by a
2259 // frame.
2260 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2261 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2262 let retimed = |s: SubClip| {
2263 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2264 let start = map.apply(s.start);
2265 let end = map.apply(s.end()).max(start.saturating_add(1));
2266 SubClip { start, frames: end - start, ..s }
2267 };
2268 for &(l, i) in &members.clips {
2269 let clips = &self.lanes[l].clips;
2270 let mut moved = clips[i];
2271 moved.speed = speed;
2272 if let Some(next) = clips.get(i + 1)
2273 && moved.end() > next.start
2274 {
2275 let name = labels[l].label();
2276 return Err(format!(
2277 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2278 move it along, or trim this one first",
2279 moved.end(),
2280 next.start
2281 )
2282 .into());
2283 }
2284 }
2285 // ...and the captions, against their own lanes' captions: a stretch
2286 // that runs one into its neighbour is refused for the clip arm's
2287 // reason -- a lane may not overlap itself -- and by name like it.
2288 let subs: Vec<(usize, usize, SubClip)> = members
2289 .subs
2290 .iter()
2291 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2292 .collect();
2293 for &(l, i, moved) in &subs {
2294 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2295 if j != i && moved.start < other.end() && other.start < moved.end() {
2296 return Err(format!(
2297 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2298 starts at {}: move it along, or trim this one first",
2299 labels[l].label(),
2300 self.lanes[l].subs[i].start,
2301 moved.end(),
2302 other.start
2303 )
2304 .into());
2305 }
2306 }
2307 }
2308 if snapshot {
2309 self.snapshot();
2310 }
2311 for (l, i) in members.clips {
2312 self.lanes[l].clips[i].speed = speed;
2313 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2314 }
2315 for (l, i, moved) in subs {
2316 self.lanes[l].subs[i] = moved;
2317 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2318 }
2319 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2320 Ok(())
2321 }
2322
2323 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2324 /// playhead standing at `at` -- read off the geometry **before** the
2325 /// write, because the old ends are gone after it. The question a card
2326 /// asks as its bar moves: the picture under the cursor has to stay the
2327 /// picture under the cursor, or the scene changes with the rate.
2328 ///
2329 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2330 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2331 /// a clip member keeps its own start and re-fits its length at the new
2332 /// rate -- its **old** rate against the new one, which is what the bar's
2333 /// live samples ask about as much as a first press does; a caption
2334 /// member scales about the held clip's start by the held clip's own
2335 /// proportion; and a playhead outside every member's old extent stays
2336 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2337 /// (or the room a stretch takes) absorbs the difference, not the
2338 /// playhead. `None` for an index that is not there.
2339 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2340 let members = self.group_of(lane, idx)?;
2341 let held = self.lane(lane).get(idx).copied()?;
2342 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2343 for &(l, i) in members.clips.iter().chain(&members.subs) {
2344 let (span, map) = match self
2345 .lanes[l]
2346 .clips
2347 .get(i)
2348 .filter(|_| members.clips.contains(&(l, i)))
2349 {
2350 // The clip's own span, re-fitted at its own old rate: one
2351 // piece of the map, anchored where the clip itself is. The
2352 // new length is the same *source* frames at the new rate --
2353 // len divided by it, never multiplied.
2354 Some(c) => (
2355 (c.start, c.start + c.frames()),
2356 TimelineMap::piece(
2357 (c.start, c.start + c.frames()),
2358 (
2359 c.start,
2360 c.start + (c.len() as f64 / new).round() as u32,
2361 ),
2362 ),
2363 ),
2364 // The caption's span, scaled about the held clip's head by
2365 // the held clip's proportion -- the offset the group keeps.
2366 None => {
2367 let s = self.lanes[l].subs.get(i)?;
2368 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2369 (
2370 (s.start, s.end()),
2371 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2372 )
2373 }
2374 };
2375 // The piece owns only its own old span: outside it the playhead
2376 // is another member's question, or nobody's.
2377 if (span.0..span.1).contains(&at) {
2378 return Some(map.apply(at));
2379 }
2380 }
2381 Some(at)
2382 }
2383
2384 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2385 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2386 /// every clip starts at anyway.
2387 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2388 self.lane(lane)
2389 .get(idx)
2390 .map_or(FitPolicy::default(), |c| c.fit)
2391 }
2392
2393 /// Sets it. One undo step like every other edit, and `false` (with no
2394 /// history) for an index that is not there. Unlike an eq or a grade there is
2395 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2396 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2397 if idx >= self.lane(lane).len() {
2398 return false;
2399 }
2400 self.snapshot();
2401 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2402 true
2403 }
2404
2405 /// Every frame number on every lane rewritten onto a timeline counted at
2406 /// another rate: `k` is old timeline frames per new one, `counts` is how
2407 /// long each source is on the *new* timeline (indexed as
2408 /// [`Project::sources`] is), and the edit survives as the same seconds of
2409 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2410 /// the edit list, and the only thing that touches the frame numbers without
2411 /// being an edit anyone made.
2412 ///
2413 /// Every position -- a clip's start and its end alike -- goes through the
2414 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2415 /// stays a gap, and a take's picture and its sound land on the same frame on
2416 /// their two lanes: no lane can drift against another. A clip is then only
2417 /// ever made to *fit* the room its own start and end mapped to, never to
2418 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2419 /// below is the backstop for the one case that could: a slow clip so short
2420 /// that no source range fits its new room at all).
2421 ///
2422 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2423 /// onto the new grid, so a rate picked, unpicked and picked again is within
2424 /// a frame of where it started rather than back at it. Upgrade path is
2425 /// keeping the edit list at one reference rate and conforming on the way
2426 /// out, which every frame number in this module would then be measured in.
2427 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2428 for lane in &mut self.lanes {
2429 let mut cursor = 0;
2430 for clip in &mut lane.clips {
2431 let start = k.timeline_at(clip.start).max(cursor);
2432 // The room its own end mapped to -- never zero, since a clip is
2433 // never empty even on a grid too coarse to hold it.
2434 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2435 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2436 // Its footage, held inside the file's new length: a clip whose
2437 // out-point was the last frame of its source must not come out
2438 // of this naming a frame past the end -- that is a project that
2439 // would not open again ([`crate::PlaybackSession::open_project`]
2440 // refuses one by name).
2441 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2442 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2443 clip.start = start;
2444 clip.in_frame = in_frame;
2445 clip.out_frame = in_frame + len;
2446 cursor = clip.end();
2447 }
2448 // A subtitle's *window* is in microseconds and a rate change moves
2449 // no seconds, so only where it sits is remapped -- through the same
2450 // [`Rate::timeline_at`] every clip boundary goes through, so a
2451 // caption still starts on the frame its picture does.
2452 let mut cursor = 0;
2453 for sub in &mut lane.subs {
2454 let start = k.timeline_at(sub.start).max(cursor);
2455 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2456 sub.start = start;
2457 cursor = sub.end();
2458 }
2459 }
2460 }
2461
2462 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2463 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2464 ///
2465 /// A subtitle lane counts like any other: a caption placed past the last
2466 /// picture holds the timeline open under it, exactly as an `A2` running
2467 /// past `V1` does, rather than being silently clipped away by the length
2468 /// ([`crate::export::timeline_cues`] clips cues to this).
2469 pub fn timeline_frames(&self) -> u32 {
2470 self.lanes
2471 .iter()
2472 .filter_map(|l| match l.kind {
2473 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2474 _ => l.clips.last().map(Clip::end),
2475 })
2476 .max()
2477 .unwrap_or(0)
2478 }
2479
2480 /// The same, counting the *media* alone: where the last picture or sound
2481 /// runs out, with the captions over them ignored.
2482 ///
2483 /// What an export actually writes ends here -- the picture loop walks the
2484 /// composite spans and the file stops with them -- so this is the length a
2485 /// cue has to be inside of to be written at all (what
2486 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2487 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2488 /// thing is a picture or a sound, which is every timeline that has no
2489 /// caption hanging past the end of both.
2490 pub fn media_frames(&self) -> u32 {
2491 self.lanes
2492 .iter()
2493 .filter(|l| l.kind != LaneKind::Subtitle)
2494 .filter_map(|l| l.clips.last().map(Clip::end))
2495 .max()
2496 .unwrap_or(0)
2497 }
2498
2499 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2500 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2501 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2502 self.lane_spans(Lane::V1)
2503 }
2504
2505 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2506 // Timeline frames, not source ones: a box on a lane is as wide as the
2507 // clip is long *there*, which a speed halves or quadruples.
2508 self.lane(lane)
2509 .iter()
2510 .map(|c| (c.start, c.frames()))
2511 .collect()
2512 }
2513
2514 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2515 /// and past the end -- [`Project::span_at`] is the version that tells those
2516 /// two apart.
2517 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2518 let clips = self.lane(lane);
2519 let idx = at(clips, timeline_frame)?;
2520 Some((idx, source_frame(&clips[idx], timeline_frame)))
2521 }
2522
2523 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2524 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2525 self.map(Lane::V1, timeline_frame)
2526 }
2527
2528 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2529 /// it, or the gap running to the next clip (or to the end of the timeline,
2530 /// which is where a lane shorter than its neighbour keeps showing black).
2531 /// `None` at or past the end of the timeline, which is the only "nothing
2532 /// left" there is.
2533 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2534 let total = self.timeline_frames();
2535 if timeline_frame >= total {
2536 return None;
2537 }
2538 let clips = self.lane(lane);
2539 Some(match at(clips, timeline_frame) {
2540 Some(idx) => Span {
2541 start: timeline_frame,
2542 len: clips[idx].end() - timeline_frame,
2543 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2544 speed: clips[idx].speed,
2545 },
2546 None => Span {
2547 start: timeline_frame,
2548 speed: Speed::NORMAL,
2549 // The next placement, or the end of the timeline: a gap is
2550 // bounded by what comes after it, never by its own bookkeeping.
2551 len: clips
2552 .iter()
2553 .find(|c| c.start > timeline_frame)
2554 .map_or(total, |c| c.start)
2555 - timeline_frame,
2556 from: None,
2557 },
2558 })
2559 }
2560
2561 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2562 /// gaps included -- the whole play list, which is what an export walks.
2563 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2564 let mut out = Vec::new();
2565 let mut t = timeline_frame;
2566 while let Some(span) = self.span_at(lane, t) {
2567 t = span.end();
2568 out.push(span);
2569 }
2570 out
2571 }
2572
2573 /// What the *composite* shows from `timeline_frame` on -- the answer
2574 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2575 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2576 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2577 /// (the usual overlay convention). A frame no video lane covers is a gap,
2578 /// which is black however many lanes are above or below it.
2579 ///
2580 /// No blending, so exactly one lane is visible at a time and the composite
2581 /// is itself a span list -- which is why one decoder plays it, the same one
2582 /// a single-lane timeline uses, rather than N running at once.
2583 ///
2584 /// The span is cut short wherever a *higher* lane's clip starts, because
2585 /// from that frame on a different lane wins; that is what makes walking
2586 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2587 ///
2588 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2589 /// lanes would then be visible in one frame and the caller needs a decoder
2590 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2591 /// (this same walk, per lane) feeding N decoders.
2592 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2593 let total = self.timeline_frames();
2594 if timeline_frame >= total {
2595 return None;
2596 }
2597 let video = self.video_lanes();
2598 // The last covering lane is the winner; only the lanes above it can
2599 // interrupt what it shows.
2600 let winner = video
2601 .iter()
2602 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2603 let (from, speed, until) = match winner {
2604 Some(i) => {
2605 let clips = self.lane(video[i]);
2606 let idx = at(clips, timeline_frame).expect("just found above");
2607 (
2608 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2609 clips[idx].speed,
2610 clips[idx].end(),
2611 )
2612 }
2613 // Nothing covers it: black until something above the floor starts.
2614 None => (None, Speed::NORMAL, total),
2615 };
2616 let takeover = video[winner.map_or(0, |i| i + 1)..]
2617 .iter()
2618 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
2619 .map(|c| c.start)
2620 .min();
2621 Some(Span {
2622 start: timeline_frame,
2623 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
2624 from,
2625 speed,
2626 })
2627 }
2628
2629 /// The video lanes in display order, topmost last -- the order the composite
2630 /// rule counts in.
2631 fn video_lanes(&self) -> Vec<Lane> {
2632 self.lanes()
2633 .into_iter()
2634 .filter(|l| l.kind == LaneKind::Video)
2635 .collect()
2636 }
2637
2638 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
2639 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
2640 /// index on that lane. `None` over a gap and past the end. What a front-end
2641 /// asks to act on "the clip on screen" without re-deriving the rule.
2642 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
2643 let video = self.video_lanes();
2644 let winner = video
2645 .iter()
2646 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
2647 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
2648 }
2649
2650 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
2651 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
2652 /// answers "the clip on screen"; this answers it per lane, which is what
2653 /// walking the lanes for something to select needs.
2654 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
2655 at(self.lane(lane), timeline_frame)
2656 }
2657
2658 /// How the composite is graded at `timeline_frame`, so the picture playback
2659 /// converts and the one an export encodes are graded from one answer.
2660 /// `None` over a gap (black is black) and for a clip nobody has graded,
2661 /// which is the byte-identical path everywhere.
2662 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
2663 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2664 self.color_of(lane, idx)
2665 }
2666
2667 /// How the composite meets the project canvas at `timeline_frame`, so the
2668 /// picture playback composes and the one an export encodes are placed from
2669 /// one answer. `Fit` over a gap, where black is already the canvas.
2670 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
2671 self.composite_clip_at(timeline_frame)
2672 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
2673 }
2674
2675 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
2676 /// viewer sees from `timeline_frame` to the end, in order. What an export
2677 /// encodes and what playback walks at a clip boundary.
2678 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
2679 let mut out = Vec::new();
2680 let mut t = timeline_frame;
2681 while let Some(span) = self.composite_span_at(t) {
2682 t = span.end();
2683 out.push(span);
2684 }
2685 out
2686 }
2687
2688 /// Split every lane at `timeline_frame`, so that frame becomes the first
2689 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
2690 /// (`false`, no change) when no lane has a clip to split there -- at a
2691 /// placement's own start, in a gap, and past the end -- all of which would
2692 /// produce an empty clip or nothing at all.
2693 ///
2694 /// Lanes' halves share an id only where they are the *same* span: the lanes
2695 /// are edited apart, so the clip being cut here may start (or end)
2696 /// somewhere else on another lane, and a group id whose clips disagree
2697 /// about their span is not one take (see [`links_are_consistent`], which
2698 /// refuses to load one).
2699 ///
2700 /// Metadata only: no mapping changes, in any lane.
2701 pub fn split(&mut self, timeline_frame: u32) -> bool {
2702 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
2703 }
2704
2705 /// [`split`](Project::split), with the snapshot optional and the lanes
2706 /// named: a batch that has already taken a snapshot
2707 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
2708 /// region and must still be one undo press, and a *scoped* batch must not
2709 /// cut a lane it was told to leave alone.
2710 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
2711 let cut: Vec<Option<Clip>> = self
2712 .lanes
2713 .iter()
2714 .enumerate()
2715 .map(|(i, l)| {
2716 on.contains(&i)
2717 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
2718 .flatten()
2719 })
2720 .collect();
2721 // The same question on the subtitle lanes, in their own arithmetic: a
2722 // razor cuts the captions with the picture, and a frame where only a
2723 // caption can be cut is still a cut.
2724 let cut_subs: Vec<bool> = self
2725 .lanes
2726 .iter()
2727 .enumerate()
2728 .map(|(i, l)| {
2729 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
2730 })
2731 .collect();
2732 // The links the captions carry, read before the room is opened below
2733 // -- `sub_open_room` takes the id off both halves, exactly as
2734 // `open_room` does for a clip, and the split hands the halves theirs
2735 // back afterwards.
2736 let sub_orig: Vec<Option<u32>> = self
2737 .lanes
2738 .iter()
2739 .zip(&cut_subs)
2740 .map(|(l, &cut)| {
2741 cut.then(|| {
2742 l.subs
2743 .iter()
2744 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
2745 .and_then(|s| s.link)
2746 })
2747 .flatten()
2748 })
2749 .collect();
2750 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
2751 return false;
2752 }
2753 if snapshot {
2754 self.snapshot();
2755 }
2756 for (data, _) in self
2757 .lanes
2758 .iter_mut()
2759 .zip(&cut_subs)
2760 .filter(|&(_, &cut)| cut)
2761 {
2762 // A split is room of no width: the halves keep their windows by
2763 // proportion and nothing moves.
2764 sub_open_room(&mut data.subs, timeline_frame, 0);
2765 debug_assert!(subs_sorted_disjoint(&data.subs));
2766 }
2767 // Each side is its own question, and the answer is the group the clip
2768 // already carried: the left half *keeps* its take's id -- the take the
2769 // frames before the cut still are -- and the right halves of one take
2770 // share one fresh id of their own, clips and captions alike. A lane
2771 // holding no group (a `place`ment, a caption nobody grouped) comes out
2772 // of the cut holding none, which is what it went in with. The captions'
2773 // own links were drawn above, before the room opened.
2774 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
2775 let mut distinct: Vec<u32> = Vec::new();
2776 for id in orig.iter().chain(&sub_orig).flatten() {
2777 if !distinct.contains(id) {
2778 distinct.push(*id);
2779 }
2780 }
2781 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
2782 let right_of =
2783 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
2784 for (l, data) in self.lanes.iter_mut().enumerate() {
2785 if !cut_subs[l] {
2786 continue;
2787 }
2788 // The pair the razor just made: they touch at the frame it cut.
2789 if let Some(idx) = data
2790 .subs
2791 .iter()
2792 .position(|s| s.end() == timeline_frame)
2793 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
2794 {
2795 data.subs[idx].link = sub_orig[l];
2796 data.subs[idx + 1].link = right_of(sub_orig[l]);
2797 }
2798 }
2799 for (data_i, data) in self.lanes.iter_mut().enumerate() {
2800 // The lanes this call was not scoped to are not cut, whatever their
2801 // own clips would allow.
2802 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
2803 continue;
2804 };
2805 let mut tail = data.clips[idx];
2806 // Where the cut lands *in the file*, which is the clip's own rate
2807 // away from where it lands on the timeline. Both halves keep the
2808 // speed, and `splittable` has already refused any frame at which
2809 // the two would not add up to the one being cut.
2810 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
2811 tail.start = timeline_frame;
2812 tail.link = right_of(orig[data_i]);
2813 data.clips[idx].out_frame = tail.in_frame;
2814 data.clips[idx].link = orig[data_i];
2815 data.clips.insert(idx + 1, tail);
2816 }
2817 true
2818 }
2819
2820 /// The inverse of [`split`](Project::split): rejoin the placements that meet
2821 /// at `timeline_frame` in every lane and put the result back in one group.
2822 /// Only what a split could have produced is rejoined -- the two sides must
2823 /// touch on the timeline *and* be consecutive frames of the same source --
2824 /// so the clip list comes back exactly as it was and traversal with it.
2825 /// `false` when no lane has such a pair. The rejoined placement keeps the
2826 /// **left** half's id, which is the take the split left on it: rejoining a
2827 /// cut take puts the take back, id and all.
2828 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
2829 // What each lane would end up covering, if it joins here at all.
2830 let joined: Vec<Option<(u32, u32)>> = self
2831 .lanes
2832 .iter()
2833 .map(|l| {
2834 joinable(&l.clips, timeline_frame)
2835 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
2836 })
2837 .collect();
2838 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
2839 let join_subs: Vec<Option<usize>> = self
2840 .lanes
2841 .iter()
2842 .map(|l| sub_joinable(&l.subs, timeline_frame))
2843 .collect();
2844 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
2845 return false;
2846 }
2847 self.snapshot();
2848 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
2849 if let Some(idx) = sub {
2850 data.subs[idx].frames += data.subs[idx + 1].frames;
2851 data.subs[idx].out_us = data.subs[idx + 1].out_us;
2852 data.subs.remove(idx + 1);
2853 debug_assert!(subs_sorted_disjoint(&data.subs));
2854 }
2855 let Some(idx) = joinable(&data.clips, timeline_frame) else {
2856 continue;
2857 };
2858 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
2859 data.clips.remove(idx + 1);
2860 }
2861 true
2862 }
2863
2864 /// Take the placement at `idx` of `lane` out of its group: every clip and
2865 /// every caption carrying its id -- on however many lanes -- is handed an
2866 /// id of its own, so from here on each half moves, trims and is deleted
2867 /// alone. The music video whose sound is to be cut against its picture
2868 /// starts here, and so does the caption that has to come off the picture it
2869 /// was pinned to.
2870 ///
2871 /// An id of its own rather than none at all: a half no other lane is grouped
2872 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
2873 /// (see [`links_are_consistent`]), and it is what a front-end already draws
2874 /// as detached. `None` would instead say "was never part of a take", which
2875 /// is what a one-lane [`place`](Project::place) means.
2876 ///
2877 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
2878 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
2879 /// the group back. Refused (`false`, nothing changed) for an index that is
2880 /// not there, a placement in no group at all, and one whose group has no
2881 /// other half -- that one is already detached, and a refusal must not cost
2882 /// an undo step.
2883 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
2884 let Some(members) = self.group_of(lane, idx) else {
2885 return false;
2886 };
2887 if members.alone() {
2888 return false;
2889 }
2890 let Some(id) = self
2891 .lane(lane)
2892 .get(idx)
2893 .and_then(|c| c.link)
2894 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
2895 else {
2896 return false;
2897 };
2898 self.snapshot();
2899 // Drawn before the walk: `new_link` takes the whole project, and the
2900 // walk holds the lanes.
2901 let count = members.clips.len() + members.subs.len();
2902 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
2903 for data in &mut self.lanes {
2904 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
2905 c.link = fresh.pop();
2906 }
2907 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
2908 s.link = fresh.pop();
2909 }
2910 }
2911 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2912 true
2913 }
2914
2915 /// Put two clips on two lanes into one group, so what moves one moves the
2916 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
2917 /// how a picture is regrouped with sound it was never opened with. Whatever
2918 /// either of them was grouped with comes along: those clips cover this same
2919 /// span already, so the result is one group and not two overlapping ones.
2920 ///
2921 /// Same frames or nothing: a group id names **one span** on however many
2922 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
2923 /// clips that do not cover the same frames cannot be one take, and the
2924 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
2925 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
2926 /// mean, not the rule.
2927 ///
2928 /// Metadata only, one snapshot. The error says what is wrong, because
2929 /// `false` would not: a bad index, one lane twice (a group is at most one
2930 /// clip per lane), spans that disagree, and a pair that is already one take
2931 /// -- nothing changes, and none of them costs an undo step.
2932 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
2933 if a == b {
2934 return Err(format!(
2935 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
2936 a.label()
2937 )
2938 .into());
2939 }
2940 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
2941 p.lane(lane)
2942 .get(idx)
2943 .copied()
2944 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
2945 };
2946 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
2947 if (x.start, x.end()) != (y.start, y.end()) {
2948 return Err(format!(
2949 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
2950 a.label(),
2951 x.start,
2952 x.end(),
2953 b.label(),
2954 y.start,
2955 y.end()
2956 )
2957 .into());
2958 }
2959 if x.link.is_some() && x.link == y.link {
2960 return Err("those two are one take already".into());
2961 }
2962 self.snapshot();
2963 let id = self.new_link();
2964 // Every clip either of them was grouped with, by the same rule: all of
2965 // them cover this span, so one id over the lot stays consistent.
2966 let old = [x.link, y.link];
2967 for data in &mut self.lanes {
2968 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
2969 if old.contains(&c.link) {
2970 c.link = Some(id);
2971 }
2972 }
2973 }
2974 // And the two themselves, which a `place` may have left in no group.
2975 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
2976 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
2977 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2978 Ok(())
2979 }
2980
2981 /// Put every placement the picks name into one group -- the group a hand
2982 /// builds with ctrl-click and a menu: the picture, its sound and the
2983 /// caption over it, on as many lanes as the picks name. What any of them
2984 /// was already grouped with rides along (one group, not two sharing a
2985 /// member), and the members keep their own spans: a group is one id over
2986 /// one placement per lane, and the offsets between them are what the group
2987 /// preserves -- a drag, a trim and a delete all move the members *by the
2988 /// same distance*, not to the same frames.
2989 ///
2990 /// No two picks may name one lane -- that is the one clip-per-lane rule,
2991 /// and the refusal says which lane -- and a pick that names nothing is
2992 /// refused with its own words. At least two picks, or there is nothing to
2993 /// group.
2994 ///
2995 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
2996 /// apart again. None of the refusals changes anything or costs an undo
2997 /// step.
2998 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
2999 if picks.len() < 2 {
3000 return Err("a group is two placements or more: pick another one first".into());
3001 }
3002 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3003 for &(lane, idx) in picks {
3004 if seen.contains(&lane) {
3005 return Err(format!(
3006 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3007 track",
3008 lane.label()
3009 )
3010 .into());
3011 }
3012 seen.push(lane);
3013 let there = if lane.kind == LaneKind::Subtitle {
3014 idx < self.sub_lane(lane).len()
3015 } else {
3016 idx < self.lane(lane).len()
3017 };
3018 if !there {
3019 let what = if lane.kind == LaneKind::Subtitle {
3020 "subtitle"
3021 } else {
3022 "clip"
3023 };
3024 return Err(
3025 format!("there is no {what} {idx} on {}", lane.label()).into()
3026 );
3027 }
3028 }
3029 let links: Vec<Option<u32>> = picks
3030 .iter()
3031 .map(|&(lane, idx)| {
3032 if lane.kind == LaneKind::Subtitle {
3033 self.sub_lane(lane)[idx].link
3034 } else {
3035 self.lane(lane)[idx].link
3036 }
3037 })
3038 .collect();
3039 // The picks are already one per lane (`seen`, above), but a pick's
3040 // *existing* group can carry a second member onto a lane another
3041 // pick (or another existing group in the merge) already occupies --
3042 // two captions on one sub lane, say, each grouped with a different
3043 // clip before this call. Merging both in would leave that lane with
3044 // two members of one id, which `links_are_consistent` may never see:
3045 // refused by name, before anything moves, rather than a group closed
3046 // broken.
3047 let labels = handles(&self.lanes);
3048 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3049 for (li, data) in self.lanes.iter().enumerate() {
3050 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3051 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3052 if n > 0 {
3053 per_lane.insert(li, n as u32);
3054 }
3055 }
3056 // A pick that carries no link of its own is invisible to the scan
3057 // above (there is no `Some` to match): it still claims its lane.
3058 for &(lane, _) in picks {
3059 let li = self.index(lane).expect("checked above");
3060 per_lane.entry(li).or_insert(0);
3061 if !self.lanes[li]
3062 .clips
3063 .iter()
3064 .any(|c| c.link.is_some() && links.contains(&c.link))
3065 && !self.lanes[li]
3066 .subs
3067 .iter()
3068 .any(|s| s.link.is_some() && links.contains(&s.link))
3069 {
3070 *per_lane.get_mut(&li).expect("just inserted") += 1;
3071 }
3072 }
3073 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3074 return Err(format!(
3075 "a group is one placement per lane: merging these groups would put two on {}",
3076 labels[li].label()
3077 )
3078 .into());
3079 }
3080 self.snapshot();
3081 let id = self.new_link();
3082 // Whatever any pick was grouped with comes along, for [`group`]'s
3083 // reason -- one id over the lot, not two groups sharing a member.
3084 for data in &mut self.lanes {
3085 for c in data.clips.iter_mut() {
3086 if c.link.is_some() && links.contains(&c.link) {
3087 c.link = Some(id);
3088 }
3089 }
3090 for s in data.subs.iter_mut() {
3091 if s.link.is_some() && links.contains(&s.link) {
3092 s.link = Some(id);
3093 }
3094 }
3095 }
3096 // And the picks themselves, which a `place` may have left in no group.
3097 // The lane seats are read before the walk, which holds the lanes.
3098 let seats: Vec<(usize, bool)> = picks
3099 .iter()
3100 .map(|&(lane, _)| {
3101 (
3102 self.index(lane).expect("checked above"),
3103 lane.kind == LaneKind::Subtitle,
3104 )
3105 })
3106 .collect();
3107 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3108 let _ = lane;
3109 if sub {
3110 self.lanes[at].subs[idx].link = Some(id);
3111 } else {
3112 self.lanes[at].clips[idx].link = Some(id);
3113 }
3114 }
3115 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3116 Ok(())
3117 }
3118
3119 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3120 /// lands on and leaving every other clip exactly where it is -- the
3121 /// per-lane paste. Anything already there is trimmed away (and split in two
3122 /// if `clip` lands inside it), which is what keeps the lane sorted and
3123 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3124 /// gap. Refused only for an empty `clip`.
3125 ///
3126 /// The placement belongs to no group: a clipboard clip carries the link id
3127 /// of the take it was copied from, and placing it twice -- or placing a copy
3128 /// back over the clip it came from -- would put that id on two clips of one
3129 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3130 /// `None` rather than a fresh id because a one-lane placement has nothing on
3131 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3132 /// become a group again.
3133 ///
3134 /// Refused for an empty `clip`, for a lane that is not there, and for a
3135 /// subtitle lane, which carries no picture and no sound
3136 /// ([`Project::place_sub`] is its door).
3137 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3138 if clip.out_frame <= clip.in_frame
3139 || lane.kind == LaneKind::Subtitle
3140 || self.index(lane).is_none()
3141 {
3142 return false;
3143 }
3144 self.snapshot();
3145 let clip = Clip {
3146 start: timeline_frame,
3147 link: None,
3148 ..clip
3149 };
3150 self.insert_over(lane, clip);
3151 true
3152 }
3153
3154 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3155 /// one grouped take -- what a picture let go over a further video track
3156 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3157 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3158 /// this half a file with sound landed on a layer silent, and the only way to
3159 /// hear it was to drop it a second time on an audio lane.
3160 ///
3161 /// Both halves overwrite what they land on and neither ripples, exactly as
3162 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3163 /// nothing under it moves. One history snapshot for the pair, the added lane
3164 /// included, so one [`Project::undo`] takes the whole placement back. The two
3165 /// carry one link, which is what makes them one take to a drag, a trim and a
3166 /// save.
3167 ///
3168 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3169 /// there or is not a video lane: sound placed alone is
3170 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3171 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3172 if clip.out_frame <= clip.in_frame
3173 || lane.kind != LaneKind::Video
3174 || self.index(lane).is_none()
3175 {
3176 return false;
3177 }
3178 self.snapshot();
3179 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3180 // an ord names a lane only while every ord below it does.
3181 while self.lane_count(LaneKind::Audio) <= lane.ord {
3182 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3183 }
3184 let clip = Clip {
3185 start: timeline_frame,
3186 link: Some(self.new_link()),
3187 ..clip
3188 };
3189 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3190 self.insert_over(half, clip);
3191 }
3192 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3193 true
3194 }
3195
3196 /// `clip` into `lane` at its own start, over whatever it lands on: the
3197 /// insert both placement doors make, which is what keeps a lane sorted and
3198 /// disjoint. The caller has checked that the lane is there.
3199 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3200 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3201 clear(clips, clip.start, clip.end());
3202 let idx = clips.partition_point(|c| c.start < clip.start);
3203 clips.insert(idx, clip);
3204 debug_assert!(sorted_disjoint(clips));
3205 }
3206
3207 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3208 /// frame `start`: the drag that rearranges takes, along a track and across
3209 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3210 /// was. `start` at the clip's own is the pure lane change.
3211 ///
3212 /// The whole group travels the same distance, each half on the lane it
3213 /// already sits on -- a link means "these cover one span on however many
3214 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3215 /// sound would be a group no save could load. Only the dragged half changes
3216 /// lane, and that is not a desync: a link names no lane at all.
3217 ///
3218 /// `start` is **clamped**, never refused, to the room the group has: no
3219 /// member crosses a neighbour on the lane it lands on, exactly as
3220 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3221 /// dragging past a neighbour means "as far as it goes", and butting up
3222 /// against the take next door is how clips are laid end to end. The
3223 /// tightest member's wall wins, so a sound half boxed in between two others
3224 /// holds its picture still.
3225 ///
3226 /// Refused, changing nothing and costing no undo step, for a lane that is
3227 /// not there, an index that is not there, a move across *kinds* (a picture
3228 /// cannot play on an audio lane, and the save it wrote would not open
3229 /// again), a head let go *inside* another clip or into a gap too narrow to
3230 /// hold this one -- a move that overwrote what it landed on would destroy a
3231 /// take the pointer never named, which is what [`place`](Project::place)
3232 /// may do and a drag may not -- a half let go onto the lane its own partner
3233 /// is on, and a drop that changes neither lane nor frame, which is a clip
3234 /// picked up and put back down, i.e. a click.
3235 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3236 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3237 return false;
3238 };
3239 if from.kind != to.kind {
3240 return false;
3241 }
3242 let members = self.group_of(from, idx).expect("the clip was found");
3243 let held = self.index(from).expect("the clip was found on it");
3244 // The two halves of one group would land on one span of one lane, which
3245 // is the one thing a link may never mean. Refused rather than clamped:
3246 // the partner moves the same distance, so there is no room for it
3247 // anywhere on that lane.
3248 if dest != held
3249 && members
3250 .clips
3251 .iter()
3252 .chain(&members.subs)
3253 .any(|&(l, _)| l == dest)
3254 {
3255 return false;
3256 }
3257 let want = i64::from(start) - i64::from(clip.start);
3258 // How far the group may travel, in timeline frames and signed: every
3259 // member -- the clips and any caption grouped with them -- narrows it
3260 // to the gap it is landing in, and what is left is what the pointer is
3261 // clamped to.
3262 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3263 return false;
3264 };
3265 if lo > hi {
3266 return false;
3267 }
3268 let delta = want.clamp(lo, hi);
3269 if delta == 0 && dest == held {
3270 return false;
3271 }
3272 self.snapshot();
3273 for &(l, i) in &members.clips {
3274 let c = &mut self.lanes[l].clips[i];
3275 // In range by the walls above, which are `u32` frames throughout.
3276 c.start = (i64::from(c.start) + delta) as u32;
3277 }
3278 for &(l, i) in &members.subs {
3279 let s = &mut self.lanes[l].subs[i];
3280 s.start = (i64::from(s.start) + delta) as u32;
3281 }
3282 if dest != held {
3283 let clip = self.lanes[held].clips.remove(idx);
3284 let clips = &mut self.lanes[dest].clips;
3285 let at = clips.partition_point(|c| c.start < clip.start);
3286 clips.insert(at, clip);
3287 }
3288 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3289 debug_assert!(members
3290 .clips
3291 .iter()
3292 .chain(&members.subs)
3293 .all(|&(l, _)| {
3294 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3295 }));
3296 true
3297 }
3298
3299 /// How far a group drag may travel, `(least, most)` in timeline frames and
3300 /// signed: every member narrows the range to the gap it is landing in --
3301 /// the clips against their lanes' clips and the captions against their
3302 /// lanes' captions -- and what is left is what the pointer is clamped to.
3303 /// `travelling` names the one member that changes lane, if any: the clip a
3304 /// hand is carrying onto another track, whose walls are read on the lane it
3305 /// is let go over at the frame the pointer named. `None` when a member has
3306 /// no gap to land in at all.
3307 fn move_room(
3308 &self,
3309 members: &Members,
3310 travelling: Option<(usize, usize, usize, u32)>,
3311 ) -> Option<(i64, i64)> {
3312 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3313 for &(l, i) in members.clips.iter().chain(&members.subs) {
3314 let sub = members.subs.contains(&(l, i));
3315 let (start, frames) = match self.lanes[l]
3316 .clips
3317 .get(i)
3318 .filter(|_| !sub)
3319 .map(|c| (c.start, c.frames()))
3320 {
3321 Some(pair) => pair,
3322 None => {
3323 let s = self.lanes[l].subs.get(i)?;
3324 (s.start, s.frames)
3325 }
3326 };
3327 let land = travelling
3328 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3329 .map_or(l, |(_, _, dest, _)| dest);
3330 // Which gap this member's walls are read off: its own place on the
3331 // lane it stays on, and the frame the pointer named on the lane it
3332 // is let go over. A clip's neighbours are the clips of the lane it
3333 // lands on and a caption's are its captions -- the two lists of one
3334 // lane never meet.
3335 let at = match travelling {
3336 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3337 _ => start,
3338 };
3339 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3340 let neighbours: Vec<(u32, u32)> = if sub {
3341 self.lanes[land]
3342 .subs
3343 .iter()
3344 .map(|s| (s.start, s.end()))
3345 .collect()
3346 } else {
3347 self.lanes[land]
3348 .clips
3349 .iter()
3350 .map(|c| (c.start, c.end()))
3351 .collect()
3352 };
3353 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3354 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3355 continue;
3356 }
3357 if *other_start <= at && at < *other_end {
3358 // A head let go inside another placement, which a clamp
3359 // has no answer for: the drop is refused.
3360 return None;
3361 }
3362 match other_end <= &at {
3363 true => wall_lo = wall_lo.max(*other_end),
3364 false => wall_hi = wall_hi.min(*other_start),
3365 }
3366 }
3367 if wall_hi - wall_lo < frames {
3368 return None;
3369 }
3370 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3371 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3372 }
3373 Some((lo, hi))
3374 }
3375
3376 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3377 /// the drag on a clip's end that makes it play more or less of its source.
3378 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3379 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3380 /// is room that was already empty. One snapshot, so a whole drag is one
3381 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3382 /// sample. Changes the timeline->source mapping: the caller must reseek.
3383 ///
3384 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3385 /// exactly what they played before, which is what makes this a trim and not
3386 /// a slip.
3387 ///
3388 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3389 /// legal means "as far as it goes", and stopping the box there is the
3390 /// affordance. The walls are: one frame of clip always survives, an edge
3391 /// never crosses the neighbouring clip on its own lane, an in-point never
3392 /// walks back past the source's first frame, and an out-point never runs
3393 /// past `source_frames[clip.source]` -- the caller's table of how long each
3394 /// source actually is ([`Project`] does not know, and a clip ending past its
3395 /// file's last frame is a save that will not open again; see
3396 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3397 /// there may not grow at all.
3398 ///
3399 /// Linked placements trim *together*, by one delta: every member's same
3400 /// edge moves the distance the dragged one did, clamped to the room its
3401 /// own walls leave -- offsets between the members of a hand-built group
3402 /// survive the trim, exactly as they survive a drag.
3403 ///
3404 /// `false`, changing nothing and costing no undo step, for an index that is
3405 /// not there and for an edge that is already where it was asked to go.
3406 pub fn trim(
3407 &mut self,
3408 lane: Lane,
3409 idx: usize,
3410 edge: Edge,
3411 to: u32,
3412 source_frames: &[u32],
3413 ) -> bool {
3414 let (Some((lo, hi)), Some(clip)) = (
3415 self.trim_room(lane, idx, edge, source_frames),
3416 self.lane(lane).get(idx).copied(),
3417 ) else {
3418 return false;
3419 };
3420 let to = to.clamp(lo, hi);
3421 let at = match edge {
3422 Edge::Start => clip.start,
3423 Edge::End => clip.end(),
3424 };
3425 if to == at {
3426 return false;
3427 }
3428 // Worked out before anything moves: at a slow rate a room can be too
3429 // narrow to hold even one source frame ([`Speed::fit`]), and the
3430 // dragged clip refusing to fit must refuse the whole gesture rather
3431 // than be given a range wider than its room -- which is the overlap
3432 // the lane invariant exists to forbid. The walls below leave that room,
3433 // so this is the backstop for a project that came in through another
3434 // door.
3435 let room = match edge {
3436 // The frames that stay play what they played, so what survives is
3437 // measured from the *end*.
3438 Edge::Start => clip.end() - to,
3439 Edge::End => to - clip.start,
3440 };
3441 let Some(keep) = clip.speed.fit(room) else {
3442 return false;
3443 };
3444 let members = self.group_of(lane, idx).expect("checked above");
3445 self.snapshot();
3446 let still = self.is_still(&clip);
3447 let held = self.index(lane).expect("checked above");
3448 let c = &mut self.lanes[held].clips[idx];
3449 match edge {
3450 // A still has no earlier frame to walk an in-point back to --
3451 // every frame of it is the same picture -- so its head grows
3452 // *forward*: the range it plays is however long the new room is,
3453 // anchored at the source's frame 0. Bounded by `lo`, which is where
3454 // the cap in `source_frames` is applied.
3455 Edge::Start if still => {
3456 c.in_frame = 0;
3457 c.out_frame = keep;
3458 c.start = to;
3459 }
3460 Edge::Start => {
3461 // Non-negative by `lo`, which is what keeps the in-point on the
3462 // source.
3463 c.in_frame = c.out_frame - keep.min(c.out_frame);
3464 c.start = to;
3465 }
3466 // Never wider than the room the edge was clamped to: see
3467 // [`Speed::fit`].
3468 Edge::End => c.out_frame = c.in_frame + keep,
3469 }
3470 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3471 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3472 true
3473 }
3474
3475 /// The rest of a group after one member's `edge` has moved by `delta`:
3476 /// every other member's same edge moves the same distance, clamped to the
3477 /// room its own walls leave -- a clip's against its lane and its source,
3478 /// a caption's against its own lane, its window following by the
3479 /// placement's own proportion. The undo step is the caller's: this is the
3480 // second half of one edit, not an edit of its own.
3481 fn follow_group(
3482 &mut self,
3483 members: &Members,
3484 dragged: &(usize, usize),
3485 edge: Edge,
3486 delta: i64,
3487 source_frames: &[u32],
3488 ) {
3489 for &(l, i) in &members.clips {
3490 if (l, i) == *dragged {
3491 continue;
3492 }
3493 let c = self.lanes[l].clips[i];
3494 let at = match edge {
3495 Edge::Start => c.start,
3496 Edge::End => c.end(),
3497 };
3498 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3499 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3500 if to == at {
3501 continue;
3502 }
3503 let room = match edge {
3504 Edge::Start => c.end() - to,
3505 Edge::End => to - c.start,
3506 };
3507 let Some(keep) = c.speed.fit(room) else {
3508 continue;
3509 };
3510 let still = self.is_still(&self.lanes[l].clips[i]);
3511 let c = &mut self.lanes[l].clips[i];
3512 match edge {
3513 Edge::Start if still => {
3514 c.in_frame = 0;
3515 c.out_frame = keep;
3516 c.start = to;
3517 }
3518 Edge::Start => {
3519 c.in_frame = c.out_frame - keep.min(c.out_frame);
3520 c.start = to;
3521 }
3522 Edge::End => c.out_frame = c.in_frame + keep,
3523 }
3524 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3525 }
3526 for &(l, i) in &members.subs {
3527 if (l, i) == *dragged {
3528 continue;
3529 }
3530 let s = self.lanes[l].subs[i];
3531 let at = match edge {
3532 Edge::Start => s.start,
3533 Edge::End => s.end(),
3534 };
3535 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3536 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3537 if to == at {
3538 continue;
3539 }
3540 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3541 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3542 }
3543 }
3544
3545 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3546 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3547 /// What a front-end drawing the box *during* a drag asks, so the live width
3548 /// is the width the release will commit and an edge stops under the pointer
3549 /// rather than snapping back. The **clip's own** walls: the rest of its
3550 /// group follows by the same delta within their own ([`follow_group`]), so
3551 /// what is drawn for the dragged edge is what its own clip will commit.
3552 /// `None` for an index that is not there.
3553 pub fn trim_room(
3554 &self,
3555 lane: Lane,
3556 idx: usize,
3557 edge: Edge,
3558 source_frames: &[u32],
3559 ) -> Option<(u32, u32)> {
3560 let l = self.index(lane)?;
3561 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3562 }
3563
3564 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3565 /// its lane's storage index: the one wall computation, asked for the clip
3566 /// itself and for each member a group trim carries.
3567 fn clip_room(
3568 &self,
3569 l: usize,
3570 i: usize,
3571 edge: Edge,
3572 source_frames: &[u32],
3573 ) -> (u32, u32) {
3574 let clips = &self.lanes[l].clips;
3575 let c = clips[i];
3576 let (lo, hi) = match edge {
3577 Edge::Start => (
3578 // Back to the source's own first frame -- as many *timeline*
3579 // frames as that head is worth at the clip's rate, which at
3580 // real time is the head itself -- and never over the clip in
3581 // front of it. Saturating because a clip may hold *more*
3582 // head than the timeline has room for -- a ripple delete
3583 // slides a clip back to frame 0 with its in-point wherever
3584 // the cut left it -- and frame 0 is the other wall.
3585 //
3586 // A still is measured from its *tail* instead: it has no
3587 // in-point worth the name (every frame the same picture), so
3588 // its head reaches exactly as far as its tail does -- out to
3589 // the length the caller's table gives it, whole. Measured
3590 // from the in-point it would have no head room at all, which
3591 // is a placed picture whose left edge cannot be dragged out.
3592 // No entry in the table means no growth, as it does at the
3593 // other end.
3594 if self.is_still(&c) {
3595 c.end().saturating_sub(
3596 c.speed
3597 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
3598 )
3599 } else {
3600 c.start.saturating_sub(c.speed.room(c.in_frame))
3601 }
3602 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
3603 // One *frame of clip* always survives, and at a rate below
3604 // real time one frame of clip is several frames of timeline
3605 // ([`Speed::room`]): an edge dragged closer than that would
3606 // ask for a range no source frame fits in. At real time this
3607 // is `end - 1`, unchanged.
3608 c.end() - c.speed.room(1),
3609 ),
3610 Edge::End => (
3611 // ...and the same wall from the other end: the shortest this
3612 // clip can be is the room one source frame of it takes.
3613 c.start + c.speed.room(1),
3614 // Out to whatever is left of the source -- again in timeline
3615 // frames, at this clip's rate -- and never over the clip
3616 // behind it.
3617 c.start
3618 .saturating_add(
3619 c.speed.room(
3620 source_frames
3621 .get(c.source)
3622 .copied()
3623 .unwrap_or(c.out_frame)
3624 .saturating_sub(c.in_frame),
3625 ),
3626 )
3627 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
3628 ),
3629 };
3630 // `hi.max(lo)`: for a clip the invariants hold for, the range always
3631 // contains the edge's own place, and a caller's wrong `source_frames`
3632 // must not become an empty range (or a panicking `clamp`) here.
3633 (lo, hi.max(lo))
3634 }
3635
3636 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
3637 /// every frame is the same picture, so which frame of it a clip's in-point
3638 /// names is not a question -- what [`Project::trim`] lets grow at either
3639 /// end. `false` for a source that is not there.
3640 fn is_still(&self, clip: &Clip) -> bool {
3641 self.sources
3642 .get(clip.source)
3643 .is_some_and(|s| crate::is_image(&s.path))
3644 }
3645
3646 /// The placements that move as one with the one at `idx` of `lane` --
3647 /// itself and whatever carries its link, on the media lanes and the
3648 /// subtitle ones alike. `None` for an index that is not there.
3649 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
3650 let sub = lane.kind == LaneKind::Subtitle;
3651 let link = if sub {
3652 self.sub_lane(lane).get(idx)?.link
3653 } else {
3654 self.lane(lane).get(idx)?.link
3655 };
3656 let mut members = Members::default();
3657 match link {
3658 Some(link) => {
3659 for (l, data) in self.lanes.iter().enumerate() {
3660 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
3661 members.clips.push((l, i));
3662 }
3663 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
3664 members.subs.push((l, i));
3665 }
3666 }
3667 }
3668 None => {
3669 let l = self.index(lane).expect("the placement was found on it");
3670 if sub {
3671 members.subs.push((l, idx));
3672 } else {
3673 members.clips.push((l, idx));
3674 }
3675 }
3676 }
3677 Some(members)
3678 }
3679
3680 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
3681 /// new group, pushing everything from there on later by its length in
3682 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
3683 /// the clip it lands in is split around it; past the end of the timeline it
3684 /// goes down where it was asked for, with black in front of it -- which is
3685 /// what a library row let go on the open bed means, and what the ghost under
3686 /// the pointer promised. A clipboard means "put it here", not "here and
3687 /// black in front", and clamps to the end at its own door
3688 /// ([`crate::PlaybackSession::paste_at`]).
3689 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
3690 ///
3691 /// `V1` and `A1` and no other lane, because a take is one picture and one
3692 /// sound: copying it onto every lane there is would play the same audio
3693 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
3694 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
3695 /// video lane it is a clip that decodes to nothing, and a save carrying one
3696 /// does not open again -- and a still image ([`crate::is_image`]) reaches
3697 /// `V1` only, for the mirror of that reason. The room is still opened on
3698 /// every media lane, or the lanes it was not inserted into would slide out
3699 /// of step with the ones it was -- and the subtitle lanes are left alone:
3700 /// the words keep their own clock, and a caption that should travel with a
3701 /// clip is what a group is for.
3702 ///
3703 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
3704 /// Changes the timeline->source mapping: the caller must reseek. Refused for
3705 /// an empty `clip` and for one naming a source that is not there (both of
3706 /// which the public fields let a caller build), and for a paste whose ripple
3707 /// would push a clip past the last frame there is -- nothing is changed by
3708 /// any of them.
3709 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
3710 let Some(source) = self.sources.get(clip.source) else {
3711 return false;
3712 };
3713 if clip.out_frame <= clip.in_frame {
3714 return false;
3715 }
3716 let audio_only = crate::is_audio(&source.path);
3717 // ...and its mirror: a still is a picture and no sound, so a copy of one
3718 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
3719 // worker tries to demux -- which silences the *whole session*, not just
3720 // that clip -- and a save the engine's own `open_project` then refuses.
3721 let picture_only = crate::is_image(&source.path);
3722 // The frame it was asked for and no other: a row let go on the empty
3723 // bed past the last clip lands *there*, under the ghost that promised
3724 // it, with black in front. Clamping to the end here made every drop on
3725 // open bed an append -- the clipboard's rule, applied to a hand that
3726 // had named a place.
3727 let at = timeline_frame;
3728 // The room it takes on the timeline, which its speed decides -- not the
3729 // source range it reads.
3730 let len = clip.frames();
3731 // Room for it: `open_room` adds `len` to every start from `at` on, and a
3732 // hand-written file may hold a clip that ends at the very last frame
3733 // (`edith::check` permits `start + len == u32::MAX`). Refused here
3734 // rather than wrapped there -- a wrapped start lands *behind* the clip
3735 // it belongs after, which is an overlap no save will read back.
3736 if at.checked_add(len).is_none()
3737 || self
3738 .lanes
3739 .iter()
3740 .flat_map(|l| &l.clips)
3741 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
3742 {
3743 return false;
3744 }
3745 // ...and room *to open*: the paste splits whatever it lands inside of,
3746 // and a speeded clip can only be cut where its own rate has a source
3747 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
3748 // of one, which is the overlap a lane may never hold. At real time every
3749 // frame answers, so this cannot refuse an unspeeded paste.
3750 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
3751 if self
3752 .lanes
3753 .iter()
3754 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
3755 {
3756 return false;
3757 }
3758 self.snapshot();
3759 let clip = Clip {
3760 start: at,
3761 link: Some(self.new_link()),
3762 ..clip
3763 };
3764 // Only lanes that can play the source: a file with no picture belongs on
3765 // an audio lane and nowhere else, exactly as `place_stream_at` decides
3766 // it for an import. On a video lane it would decode to nothing, and the
3767 // save it wrote would not open again.
3768 let kinds: &[LaneKind] = match (audio_only, picture_only) {
3769 (true, _) => &[LaneKind::Audio],
3770 (_, true) => &[LaneKind::Video],
3771 _ => &[LaneKind::Video, LaneKind::Audio],
3772 };
3773 let takes: Vec<usize> = kinds
3774 .iter()
3775 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
3776 .collect();
3777 for (i, data) in self.lanes.iter_mut().enumerate() {
3778 open_room(&mut data.clips, at, len);
3779 // The subtitle lanes are NOT touched: a paste inserts media, and
3780 // the words keep their own clock. Opening room here used to split
3781 // a caption the paste landed inside and slide the rest behind it
3782 // -- "a caption that stayed put while the picture moved on no
3783 // longer says the same thing" -- but a caption pinned to nothing
3784 // (and a video arriving on a timeline of words alone) has no
3785 // picture to follow, and the split did to the words what no hand
3786 // asked for. A caption that should travel with a clip is what a
3787 // group is for, and a group moves as one.
3788 if takes.contains(&i) {
3789 let idx = data.clips.partition_point(|c| c.start < at);
3790 data.clips.insert(idx, clip);
3791 }
3792 debug_assert!(sorted_disjoint(&data.clips));
3793 debug_assert!(subs_sorted_disjoint(&data.subs));
3794 }
3795 true
3796 }
3797
3798 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
3799 /// silence, and nothing else moves. Refused only for an out-of-range index
3800 /// (which a lane that is not there always is) -- lifting the last placement
3801 /// there is leaves an *empty* timeline, which is a state the project holds
3802 /// like any other and an undo brings back.
3803 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
3804 if idx >= self.lane(lane).len() {
3805 return false;
3806 }
3807 self.snapshot();
3808 self.lane_mut(lane).expect("checked above").remove(idx);
3809 true
3810 }
3811
3812 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
3813 /// the hole: everything after slides back by `len`. The rippling delete --
3814 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
3815 /// empty range; a delete that leaves nothing behind empties the timeline,
3816 /// which is a state like any other and one undo away.
3817 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
3818 if len == 0 {
3819 return false;
3820 }
3821 // Nothing reaches past `at`: there is nothing to cut and nothing to
3822 // slide back, and a delete that changes nothing must not cost an undo
3823 // step (see [`snapshot`](Project::snapshot)).
3824 if !self
3825 .lanes
3826 .iter()
3827 .flat_map(|l| &l.clips)
3828 .any(|c| c.end() > at)
3829 {
3830 return false;
3831 }
3832 self.snapshot();
3833 let on = all_lanes(&self.lanes);
3834 ripple(&mut self.lanes, &on, at, len);
3835 true
3836 }
3837
3838 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
3839 /// out of the lanes in `scope` and close each hole, as one edit: the
3840 /// jumpcut a silence scan asks for ([`crate::silence`]).
3841 ///
3842 /// A lane that is not in `scope` **does not move**, which is the whole
3843 /// point of the parameter: the silences of a podcast track come out
3844 /// without the music track under it sliding. `scope` is an arbitrary set of
3845 /// lanes and not a kind or a range, so a caller with its own idea of what
3846 /// is selected (a take, a track, everything) says it in lanes and nothing
3847 /// here has to learn about selection.
3848 ///
3849 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
3850 /// reason this exists rather than a caller's loop over
3851 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
3852 /// undo press, not forty. Cut back to front, so a region's frames still
3853 /// mean what the caller measured while the ones before it are cut.
3854 ///
3855 /// The list is sorted and overlapping entries are merged before anything is
3856 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
3857 /// other's frames. Refused, with no undo step, for an empty list, for a
3858 /// scope naming no lane that is there, and -- by name -- when the scope
3859 /// would take one half of a take with it
3860 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
3861 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
3862 let regions = tidy(regions);
3863 let on = self.scoped(scope)?;
3864 let Some(&(first, _)) = regions.first() else {
3865 return Err("nothing to cut".into());
3866 };
3867 self.scope_holds_takes_whole(&on, first)?;
3868 self.snapshot();
3869 for &(at, len) in regions.iter().rev() {
3870 ripple(&mut self.lanes, &on, at, len);
3871 }
3872 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3873 Ok(())
3874 }
3875
3876 /// The storage indices of `scope`, which is what every batch below walks.
3877 /// `Err` for a scope that names nothing there rather than a silent no-op:
3878 /// an edit asked for on a lane that is not there did not happen, and the
3879 /// caller has to hear so.
3880 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
3881 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
3882 match on.is_empty() {
3883 true => Err("no track to work on".into()),
3884 false => Ok(on),
3885 }
3886 }
3887
3888 /// The law a scoped ripple lives under: **a group travels as one**, so a
3889 /// batch that moves one half of a take and not the other would leave the
3890 /// halves disagreeing about where they stand -- an offset no hand asked
3891 /// for, and the reason the take's lanes have to be scoped together.
3892 ///
3893 /// Refused by name rather than widened silently. Widening would edit a
3894 /// track the user did not scope, which is exactly the surprise scoping
3895 /// exists to end; a front-end that wants the take is free to *say* the
3896 /// take's lanes, and to name them in what it tells the user afterwards.
3897 ///
3898 /// Only from `from` on: a take sitting entirely before the first cut does
3899 /// not move, so it is not this rule's business.
3900 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
3901 let labels = handles(&self.lanes);
3902 // The halves of a group are on either of a lane's lists, and the
3903 // refusal names whichever sits outside the scope -- a clip like it
3904 // always has, and a caption now that a group may hold one.
3905 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
3906 let Some(id) = link else {
3907 return Ok(());
3908 };
3909 for (j, data) in self.lanes.iter().enumerate() {
3910 if on.contains(&j) {
3911 continue;
3912 }
3913 let clip = data.clips.iter().find(|o| o.link == Some(id));
3914 let sub = data.subs.iter().find(|s| s.link == Some(id));
3915 if let Some(half) = clip {
3916 return Err(format!(
3917 "the {what} at frame {start} is one take with the {} clip at frame {}: \
3918 moving one track of a take would pull it apart -- take the whole take, \
3919 or detach them first",
3920 labels[j].label(),
3921 half.start
3922 )
3923 .into());
3924 }
3925 if let Some(half) = sub {
3926 return Err(format!(
3927 "the {what} at frame {start} is one take with the {} caption at frame {}: \
3928 moving one track of a take would pull it apart -- take the whole take, \
3929 or detach them first",
3930 labels[j].label(),
3931 half.start
3932 )
3933 .into());
3934 }
3935 }
3936 Ok(())
3937 };
3938 for &i in on {
3939 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
3940 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
3941 }
3942 // A caption before the first cut does not move, so it is not this
3943 // rule's business -- exactly the clip test's own line.
3944 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
3945 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
3946 }
3947 }
3948 Ok(())
3949 }
3950
3951 /// Play every one of `regions` at `speed` instead of cutting it: each is
3952 /// split out of whatever covers it, re-rated, and the room it no longer
3953 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
3954 /// does not ripple, and a hole where a silence shrank is the one thing this
3955 /// must not leave. One snapshot for the lot, like
3956 /// [`cut_regions`](Project::cut_regions).
3957 ///
3958 /// The rate is **absolute**, not a multiplier on what is there: running it
3959 /// twice over the same stretch leaves it at `speed`, not at `speed`
3960 /// squared, so a second pass over an already-cut timeline changes nothing.
3961 ///
3962 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
3963 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
3964 ///
3965 /// Refused by name, with nothing changed and no undo step, when:
3966 ///
3967 /// * the scope would take one half of a take with it
3968 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
3969 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
3970 /// shrink by different amounts and the ripple would pull them apart,
3971 /// which is what cutting does not suffer and why delete mode has no such
3972 /// refusal;
3973 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
3974 /// piece could not be split out exactly;
3975 /// * two lanes' pieces would end up different lengths, which is a group
3976 /// whose halves disagree about their span (the refusal
3977 /// [`write_speed`](Project::write_speed) already makes, in its words);
3978 /// * the region would grow rather than shrink, i.e. it already plays faster
3979 /// than `speed`.
3980 pub fn speed_regions(
3981 &mut self,
3982 regions: &[(u32, u32)],
3983 speed: Speed,
3984 scope: &[Lane],
3985 ) -> crate::Result<()> {
3986 let regions = tidy(regions);
3987 let on = self.scoped(scope)?;
3988 let Some(&(first, _)) = regions.first() else {
3989 return Err("nothing to speed up".into());
3990 };
3991 self.scope_holds_takes_whole(&on, first)?;
3992 let labels = handles(&self.lanes);
3993 // Before anything is touched, because this is the refusal a person can
3994 // act on: a clip that laps over the edge of a silence has to be trimmed
3995 // (or the silences cut instead), and saying so after a rollback would
3996 // be saying it about a timeline that already looks different.
3997 for &(at, len) in &regions {
3998 for &l in &on {
3999 for c in &self.lanes[l].clips {
4000 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4001 {
4002 return Err(format!(
4003 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4004 speeding it up would pull the lanes apart -- trim it first, or cut the \
4005 silences out instead",
4006 labels[l].label(),
4007 c.start,
4008 at + len
4009 )
4010 .into());
4011 }
4012 }
4013 }
4014 }
4015 // The rest is checked as it is built: a split's own arithmetic is what
4016 // says whether a rate can address an edge. So the snapshot is taken
4017 // first and *rolled back* on a refusal -- one undo either way, and a
4018 // refusal still costs no step (`undo` pops the one just pushed).
4019 self.snapshot();
4020 for &(at, len) in regions.iter().rev() {
4021 self.write_split(at, false, &on);
4022 self.write_split(at + len, false, &on);
4023 let mut room: Option<(Lane, u32)> = None;
4024 let mut refused = None;
4025 for &l in &on {
4026 let clips = &self.lanes[l].clips;
4027 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4028 if (c.start, c.end()) != (at, at + len) {
4029 // *Which* edge did not come off: a rate that cannot
4030 // address the end of the silence is not a rate that
4031 // cannot address its start, and naming the wrong frame
4032 // sends the user looking in the wrong place.
4033 let edge = match c.start == at {
4034 true => at + len,
4035 false => at,
4036 };
4037 refused = Some(format!(
4038 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4039 detach it, or put it back to 1.00x first",
4040 labels[l].label(),
4041 c.start,
4042 c.speed
4043 ));
4044 continue;
4045 }
4046 let after = speed.frames(c.len());
4047 match room {
4048 None => room = Some((labels[l], after)),
4049 Some((first, n)) if n != after => {
4050 refused = Some(format!(
4051 "at {speed} the {} half of the silence at frame {at} would cover \
4052 {after} frames and the {} half {n}: they are one take and a take \
4053 is one span -- detach them first",
4054 labels[l].label(),
4055 first.label()
4056 ));
4057 }
4058 Some(_) => {}
4059 }
4060 }
4061 }
4062 let shrunk = match (refused, room) {
4063 (Some(e), _) => {
4064 self.undo();
4065 return Err(e.into());
4066 }
4067 // A gap on every lane: nothing to re-rate, and nothing to close.
4068 (None, None) => continue,
4069 (None, Some((_, after))) => after,
4070 };
4071 // The region's new length, on every scoped lane alike.
4072 let after = shrunk;
4073 let Some(delta) = len.checked_sub(shrunk) else {
4074 self.undo();
4075 return Err(format!(
4076 "the silence at frame {at} already plays faster than {speed}: \
4077 at that rate it would be {shrunk} frames instead of {len}"
4078 )
4079 .into());
4080 };
4081 for &l in &on {
4082 for c in &mut self.lanes[l].clips {
4083 if c.start == at && c.end() == at + len {
4084 c.speed = speed;
4085 } else if c.start >= at + len {
4086 c.start -= delta;
4087 }
4088 }
4089 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4090 // The captions on a scoped lane travel with the region's time:
4091 // a piece inside it plays in `after` frames instead of `len`
4092 // -- same words on less timeline, its window untouched, for
4093 // [`write_speed`]'s reason -- and everything behind the region
4094 // slides up by what the region gave back.
4095 //
4096 // The pieces inside re-time by their *boundaries*, not each
4097 // on its own: rounding one piece's start and its neighbour's
4098 // start apart can land both on the same frame (two one-frame
4099 // cues of a thirty-frame region at 2x both want frame 15), so
4100 // the mapped boundaries are walked in order and forced apart
4101 // -- each piece at least one frame, none past the region's own
4102 // new end, where the first follower lands exactly. A rounding
4103 // artifact is clamped, not refused: nothing about the words
4104 // asked for an overlap.
4105 let share = f64::from(after) / f64::from(len).max(1.);
4106 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4107 let mut prev = at;
4108 let subs = &mut self.lanes[l].subs;
4109 for i in 0..subs.len() {
4110 let s = subs[i];
4111 if s.start >= at + len {
4112 subs[i].start = s.start - delta;
4113 } else if s.start >= at && s.end() <= at + len {
4114 let mut start = map(s.start).max(prev);
4115 let end = map(s.end()).max(start + 1).min(at + after);
4116 start = start.min(end - 1);
4117 subs[i].start = start;
4118 subs[i].frames = end - start;
4119 prev = end;
4120 }
4121 }
4122 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4123 }
4124 }
4125 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4126 Ok(())
4127 }
4128
4129 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4130 /// -- the whole-group delete a single-lane front-end means. `false` for a
4131 /// bad index. Changes the mapping: the caller must reseek.
4132 pub fn delete(&mut self, idx: usize) -> bool {
4133 self.delete_in(Lane::V1, idx)
4134 }
4135
4136 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4137 /// in no group (or a group of one, which is the same thing to a delete) is
4138 /// what it always was: its own span cut out of *every* lane, so the
4139 /// timeline closes up under it. A clip in a group takes the group with it,
4140 /// each member by its **own** span and on its **own** lane -- the members
4141 /// keep their offsets, so their spans may disagree, and the lanes may end
4142 /// up out of step with each other, which is inherent to a hand-built group
4143 /// and one undo away. Every member -- clips and captions alike -- goes by
4144 /// the same law: its own span out of its own lane, hole closed; a caption
4145 /// in no group keeps the lift that leaves a gap, which is its own door's
4146 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4147 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4148 /// index, and for a lane that is not there. Changes the mapping: the
4149 /// caller must reseek.
4150 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4151 let Some(members) = self.group_of(lane, idx) else {
4152 return false;
4153 };
4154 if !members.alone() {
4155 return self.delete_members(&members);
4156 }
4157 let Some(clip) = self.lane(lane).get(idx).copied() else {
4158 return false;
4159 };
4160 self.ripple_delete(clip.start, clip.frames())
4161 }
4162
4163 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4164 /// caption in no group lifts, exactly as its own key always made it
4165 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4166 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4167 /// span out of its own lane, hole closed, captions and clips alike.
4168 /// `false` for a bad index.
4169 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4170 let Some(members) = self.group_of(lane, idx) else {
4171 return false;
4172 };
4173 if !members.alone() {
4174 return self.delete_members(&members);
4175 }
4176 self.lift_sub(lane, idx)
4177 }
4178
4179 /// The one whole-group delete both doors land in: every member's own span
4180 /// cut out of its own lane and the hole closed there -- clips and
4181 /// captions by the same law -- and nothing else on another lane moves,
4182 /// which is what keeps one member's ripple from dragging another
4183 /// member's lane out from under it. One snapshot, one undo step.
4184 fn delete_members(&mut self, members: &Members) -> bool {
4185 self.snapshot();
4186 for &(l, i) in &members.clips {
4187 let c = self.lanes[l].clips[i];
4188 ripple(&mut self.lanes, &[l], c.start, c.frames());
4189 }
4190 // The captions go by the same law their clip siblings do -- the span
4191 // out of its own lane, the hole closed -- and not by the lift a
4192 // *lone* caption's delete is: deleted with its group, the words after
4193 // it slide up with everything else, or the lane the group emptied is
4194 // the one lane the delete left a hole in. `ripple` is the one
4195 // mechanism (it clears the span and shifts the rest, clips and
4196 // captions alike); a sub lane holds no clips, so its other list is
4197 // untouched.
4198 for &(l, i) in &members.subs {
4199 let s = self.lanes[l].subs[i];
4200 ripple(&mut self.lanes, &[l], s.start, s.frames);
4201 }
4202 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4203 true
4204 }
4205
4206 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4207 #[cfg(test)]
4208 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4209 self.lane(lane)
4210 }
4211
4212 /// How many undo steps are stacked: what the sweep asks so "one op, one
4213 /// snapshot" is a count and not a guess.
4214 #[cfg(test)]
4215 pub(crate) fn history_len(&self) -> usize {
4216 self.history.len()
4217 }
4218
4219 /// How many redo steps are stacked: what the sweep asks to check `undo`
4220 /// left a branch behind, and that a fresh edit clears it.
4221 #[cfg(test)]
4222 pub(crate) fn redo_len(&self) -> usize {
4223 self.redo.len()
4224 }
4225
4226 /// Every part of the project that an edit can change, as comparable
4227 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4228 #[cfg(test)]
4229 pub(crate) fn parts(&self) -> SweepParts {
4230 SweepParts(
4231 self.sources.len(),
4232 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4233 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4234 )
4235 }
4236
4237 /// Restore every lane from before the last successful edit -- the clips and
4238 /// the lane list both. `false` when there is nothing left to undo. Pushes
4239 /// the lanes just left onto the redo stack, so [`Project::redo`] can walk
4240 /// forward again.
4241 pub fn undo(&mut self) -> bool {
4242 match self.history.pop() {
4243 Some(prev) => {
4244 self.redo.push(std::mem::replace(&mut self.lanes, prev));
4245 true
4246 }
4247 None => false,
4248 }
4249 }
4250
4251 /// Restore every lane from before the last [`Project::undo`] -- the
4252 /// mirror of `undo`, walking the redo stack it fills. `false` when there
4253 /// is nothing left to redo, which is also true after any fresh edit: a
4254 /// new [`Project::snapshot`] clears the branch `undo` left behind.
4255 pub fn redo(&mut self) -> bool {
4256 match self.redo.pop() {
4257 Some(next) => {
4258 self.history.push(std::mem::replace(&mut self.lanes, next));
4259 true
4260 }
4261 None => false,
4262 }
4263 }
4264
4265 /// The project an export renders from: everything a render reads, with the
4266 /// undo history left behind. An export never walks the history back, and
4267 /// cloning it costs a copy of every lane list in the session -- this is
4268 /// taken on the UI thread, so it clones the lanes and the sources alone.
4269 pub fn export_snapshot(&self) -> Self {
4270 Self {
4271 sources: self.sources.clone(),
4272 lanes: self.lanes.clone(),
4273 eq: self.eq.clone(),
4274 color: self.color.clone(),
4275 history: Vec::new(),
4276 redo: Vec::new(),
4277 next_link: self.next_link,
4278 subtitles: self.subtitles.clone(),
4279 limiter: self.limiter,
4280 tone: self.tone,
4281 }
4282 }
4283
4284 /// Half-open `(source, start, end)` segments in *source* seconds, from
4285 /// `timeline_frame` to the end of the timeline -- the play list for the
4286 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4287 /// worker synthesises that many seconds of silence, which is what keeps the
4288 /// audio master clock counting across a hole instead of stalling on it.
4289 /// The first entry is partial when the position is mid-clip. Empty when the
4290 /// position is past the end or `fps` is not usable.
4291 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4292 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4293 }
4294
4295 /// [`segments_from`](Project::segments_from) for a named lane.
4296 pub fn lane_segments_from(
4297 &self,
4298 lane: Lane,
4299 timeline_frame: u32,
4300 fps: f64,
4301 ) -> Vec<(Option<usize>, f64, f64)> {
4302 if !(fps.is_finite() && fps > 0.0) {
4303 return Vec::new();
4304 }
4305 self.spans_from(lane, timeline_frame)
4306 .iter()
4307 .map(|span| match span.from {
4308 // A clip's window is in *source* seconds: where in the file it
4309 // reads from, which a delete before it never shifts. How many
4310 // source frames that is, is the span's own arithmetic -- at a
4311 // speed it is not the timeline length ([`Span::source_len`]).
4312 Some((source, in_frame)) => (
4313 Some(source),
4314 f64::from(in_frame) / fps,
4315 f64::from(in_frame + span.source_len()) / fps,
4316 ),
4317 // A gap has no file, so all it can say is how long it is.
4318 None => (None, 0.0, f64::from(span.len) / fps),
4319 })
4320 .collect()
4321 }
4322
4323 /// One play list per audio lane that *holds* something, in display order --
4324 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4325 /// what an export asks how many lanes it would have to mix.
4326 ///
4327 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4328 /// audio lane at all) still yields one all-gap list, so it plays silence
4329 /// against a master clock exactly as it did before there were lanes to
4330 /// count. Lanes with nothing on them are left out rather than mixed in as
4331 /// silence: they would cost a decode thread each and add zero.
4332 pub fn audio_segments_from(
4333 &self,
4334 timeline_frame: u32,
4335 fps: f64,
4336 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4337 self.audio_lanes()
4338 .into_iter()
4339 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4340 .collect()
4341 }
4342
4343 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4344 /// builds a play list for, in the same order. Public because everything
4345 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4346 /// which lane an mp4 export would copy -- has to read the very list the
4347 /// sound comes off, or the two answers drift apart (which is exactly how an
4348 /// `A2`-only project once exported silently, ledger).
4349 pub fn audio_lanes(&self) -> Vec<Lane> {
4350 let lanes: Vec<Lane> = self
4351 .lanes()
4352 .into_iter()
4353 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
4354 .collect();
4355 match lanes.is_empty() {
4356 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
4357 // no sound still plays silence against the master clock.
4358 true => vec![Lane::A1],
4359 false => lanes,
4360 }
4361 }
4362
4363 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
4364 /// segments plays at, and how long the timeline gives it: the same lanes in
4365 /// the same order, one entry per segment, `None` for a segment at real time
4366 /// -- which is every segment of a project nobody has speeded, and the path
4367 /// the audio worker leaves bit-identical.
4368 ///
4369 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
4370 /// the segment tuple is what every opener and a dozen tests speak, and a
4371 /// rate is not part of *which samples* a segment names.
4372 ///
4373 /// The seconds are what makes a resample exact: a segment's own window
4374 /// resolves to whole source frames, and dividing that by the rate would
4375 /// leave each clip a fraction of a frame short or long -- a drift that grows
4376 /// clip by clip. Told how much timeline it owes, the worker pads or trims
4377 /// the last few samples of each segment instead, so the sound stays locked
4378 /// to the picture however many speeded cuts it walks through.
4379 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
4380 self.audio_lanes()
4381 .into_iter()
4382 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
4383 .collect()
4384 }
4385
4386 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
4387 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4388 /// same walk, same `fps` refusal.
4389 pub fn lane_speeds_from(
4390 &self,
4391 lane: Lane,
4392 timeline_frame: u32,
4393 fps: f64,
4394 ) -> Vec<Option<Stretch>> {
4395 if !(fps.is_finite() && fps > 0.0) {
4396 return Vec::new();
4397 }
4398 self.spans_from(lane, timeline_frame)
4399 .iter()
4400 .map(|span| {
4401 (!span.speed.is_normal()).then(|| Stretch {
4402 step: span.speed.as_f64(),
4403 timeline_secs: f64::from(span.len) / fps,
4404 })
4405 })
4406 .collect()
4407 }
4408
4409 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
4410 /// segments plays through: the same lanes in the same order, one entry per
4411 /// segment, `None` where the segment is a gap or its clip plays flat.
4412 ///
4413 /// A parallel list rather than a fourth element of the segment tuple: that
4414 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
4415 /// and an effect is not part of *which samples* a segment names. A short
4416 /// list therefore means "flat from here on" rather than a length mismatch --
4417 /// see [`crate::AudioSession::open_mixed_streams_eq`].
4418 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
4419 self.audio_lanes()
4420 .into_iter()
4421 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
4422 .collect()
4423 }
4424
4425 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
4426 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4427 /// same walk, same `fps` refusal, so the two lists cannot come out different
4428 /// lengths.
4429 pub fn lane_eqs_from(
4430 &self,
4431 lane: Lane,
4432 timeline_frame: u32,
4433 fps: f64,
4434 ) -> Vec<Option<EqParams>> {
4435 if !(fps.is_finite() && fps > 0.0) {
4436 return Vec::new();
4437 }
4438 self.spans_from(lane, timeline_frame)
4439 .iter()
4440 // A span off a clip covers that clip's frames and no others, so its
4441 // own start names the clip -- the index a [`Span`] does not carry.
4442 .map(|span| {
4443 self.map(lane, span.start)
4444 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
4445 })
4446 .collect()
4447 }
4448
4449 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
4450 /// it has decided it will succeed -- a refusal must not cost an undo step.
4451 /// Clears the redo stack: a fresh edit branches off from here, so whatever
4452 /// `undo` had left to redo is no longer where this edit leads back to.
4453 fn snapshot(&mut self) {
4454 if self.history.len() == HISTORY_CAP {
4455 self.history.remove(0);
4456 }
4457 self.history.push(self.lanes.clone());
4458 self.redo.clear();
4459 }
4460
4461 fn new_link(&mut self) -> u32 {
4462 let id = self.next_link;
4463 self.next_link = self.next_link.saturating_add(1);
4464 id
4465 }
4466
4467}
4468
4469/// The handle of every lane, in storage order -- the one definition of what
4470/// [`Lane::ord`] counts.
4471fn handles(lanes: &[LaneData]) -> Vec<Lane> {
4472 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
4473 lanes
4474 .iter()
4475 .map(|l| match l.kind {
4476 LaneKind::Video => {
4477 video += 1;
4478 Lane::new(LaneKind::Video, video - 1)
4479 }
4480 LaneKind::Audio => {
4481 audio += 1;
4482 Lane::new(LaneKind::Audio, audio - 1)
4483 }
4484 LaneKind::Subtitle => {
4485 subtitle += 1;
4486 Lane::new(LaneKind::Subtitle, subtitle - 1)
4487 }
4488 })
4489 .collect()
4490}
4491
4492/// The one law a caption re-time scales by: frame `f` moves about the held
4493/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
4494/// commits it, [`Project::speeded_playhead`] previews it -- both build their
4495/// [`TimelineMap`] piece from this single answer so the two cannot drift
4496/// apart by a frame the way they once did.
4497fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
4498 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
4499 .round()
4500 .clamp(0., f64::from(u32::MAX)) as u32
4501}
4502
4503/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
4504/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
4505/// a speed cannot be applied twice or forgotten in one of them.
4506fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
4507 // Clamped inside the clip's own range: rounding at a slow rate can put the
4508 // last timeline frame of a clip a frame past its out-point, and a source
4509 // frame outside the range is one the next clip owns.
4510 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
4511}
4512
4513/// Index of the clip covering `frame`, or `None` for a gap or past the end.
4514/// Binary search: the sorted-disjoint invariant is what makes it legal.
4515fn at(clips: &[Clip], frame: u32) -> Option<usize> {
4516 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
4517 (frame < clips[idx].end()).then_some(idx)
4518}
4519
4520/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
4521/// there would cut in two. A placement's own first frame is not inside it.
4522fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
4523 let idx = at(clips, frame)?;
4524 // ...and, on a speeded clip, one its rate can actually address
4525 // ([`Speed::split_at`]): a cut between two showings of one source frame
4526 // would leave halves that no longer add up to the clip that was cut.
4527 (frame > clips[idx].start)
4528 .then_some(idx)
4529 .filter(|&idx| split_source(&clips[idx], frame).is_some())
4530}
4531
4532/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
4533/// rate cannot address that frame.
4534fn split_source(c: &Clip, frame: u32) -> Option<u32> {
4535 c.speed
4536 .split_at(c.len(), frame - c.start)
4537 .map(|src| c.in_frame + src)
4538}
4539
4540/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
4541/// rejoin: they must touch there, and be consecutive frames of one source.
4542fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
4543 let idx = clips.iter().position(|c| c.end() == frame)?;
4544 let next = clips.get(idx + 1)?;
4545 let joined = clips[idx].len() + next.len();
4546 (next.start == frame
4547 && next.source == clips[idx].source
4548 && next.in_frame == clips[idx].out_frame
4549 // ...at one rate, and one that puts the rejoined clip back in exactly
4550 // the room the two took up: what a split could have produced, which is
4551 // all this undoes.
4552 && next.speed == clips[idx].speed
4553 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
4554 .then_some(idx)
4555}
4556
4557/// The lane invariant: sorted by `start`, no two placements overlapping, no
4558/// empty placement. Checked at every constructor and asserted after every
4559/// mutation -- the offset model is only tractable while it holds.
4560/// The one thing an equalizer setting may not be: a value the text format
4561/// cannot write and read back as itself. Checked wherever params come in, so
4562/// what an edit produces is always what a save writes and a load reads.
4563fn finite(params: &EqParams) -> bool {
4564 params
4565 .bands
4566 .iter()
4567 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
4568}
4569
4570/// The same for a colour grade: [`crate::color`] itself falls back to identity
4571/// on a non-finite value, but a value that cannot be written and read back as
4572/// itself has no business reaching the model.
4573fn color_finite(p: &ColorParams) -> bool {
4574 p.brightness.is_finite()
4575 && p.contrast.is_finite()
4576 && p.saturation.is_finite()
4577 && p.tint.is_finite()
4578}
4579
4580fn sorted_disjoint(clips: &[Clip]) -> bool {
4581 clips.iter().all(|c| c.out_frame > c.in_frame)
4582 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
4583}
4584
4585/// The very same invariant on a subtitle lane, in that lane's own two units:
4586/// sorted by `start`, no two placements overlapping, no empty placement at
4587/// either end. Asserted after every mutation, exactly as its twin is.
4588fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
4589 subs.iter()
4590 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
4591 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
4592}
4593
4594/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
4595/// the one conversion between a lane's clock and a cue's, and `0` for a rate
4596/// that is not one (every caller of this has already refused such a rate).
4597fn us_of(frames: i64, fps: f64) -> i64 {
4598 match fps.is_finite() && fps > 0.0 {
4599 true => ((frames as f64) / fps * 1e6).round() as i64,
4600 false => 0,
4601 }
4602}
4603
4604/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
4605/// dropping what is inside the hole, splitting what straddles it and trimming
4606/// what overlaps an edge. The windows follow the cut by proportion
4607/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
4608fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
4609 let mut out = Vec::with_capacity(subs.len() + 1);
4610 for s in subs.drain(..) {
4611 if s.end() <= start || s.start >= end {
4612 out.push(s);
4613 continue;
4614 }
4615 if s.start < start {
4616 out.push(SubClip {
4617 frames: start - s.start,
4618 out_us: s.window_at(start),
4619 // Both pieces lose the group id, for [`clear`]'s reason: one
4620 // id on two boxes of one lane is the one thing it may never
4621 // mean.
4622 link: None,
4623 ..s
4624 });
4625 }
4626 if s.end() > end {
4627 out.push(SubClip {
4628 start: end,
4629 frames: s.end() - end,
4630 in_us: s.window_at(end),
4631 link: None,
4632 ..s
4633 });
4634 }
4635 }
4636 *subs = out;
4637}
4638
4639/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
4640/// `len`, splitting a placement that straddles `at` so the two halves end up on
4641/// either side of the hole. A `len` of 0 is that split alone, which is what a
4642/// [`Project::split`] over a subtitle lane is.
4643fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
4644 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
4645 let s = subs[idx];
4646 let cut = s.window_at(at);
4647 subs[idx] = SubClip {
4648 frames: at - s.start,
4649 out_us: cut,
4650 link: None,
4651 ..s
4652 };
4653 subs.insert(
4654 idx + 1,
4655 SubClip {
4656 start: at,
4657 frames: s.end() - at,
4658 in_us: cut,
4659 link: None,
4660 ..s
4661 },
4662 );
4663 }
4664 for s in subs.iter_mut().filter(|s| s.start >= at) {
4665 s.start += len;
4666 }
4667}
4668
4669/// [`joinable`] for a subtitle lane: the first of the two placements a
4670/// [`Project::regroup`] at `frame` would rejoin. What a split could have
4671/// produced and nothing else -- they touch on the timeline, they read the same
4672/// track, and the second one's window carries on where the first's stopped.
4673fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
4674 let idx = subs.iter().position(|s| s.end() == frame)?;
4675 let next = subs.get(idx + 1)?;
4676 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
4677 .then_some(idx)
4678}
4679
4680/// How far one `edge` of the caption at `idx` may travel against its own lane's
4681/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
4682/// rate, which a caption *following* a group's trim does not have to be exact
4683/// about -- its own walls, its own one surviving frame, and nothing that needs
4684/// a clock.
4685fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
4686 let s = &subs[idx];
4687 match edge {
4688 Edge::Start => (
4689 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
4690 s.end() - 1,
4691 ),
4692 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
4693 }
4694}
4695
4696/// Move one `edge` of `s` to timeline frame `to`, its window following by the
4697/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
4698/// forwards and backwards. The caption a group's trim is carrying has no rate
4699/// of its own and needs none: what one frame of it is worth in microseconds is
4700/// the window it already shows over the frames it already takes.
4701fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
4702 let per_frame = s.window_us() / i64::from(s.frames.max(1));
4703 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
4704 match edge {
4705 Edge::Start => {
4706 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
4707 s.frames = s.end() - to;
4708 s.start = to;
4709 }
4710 Edge::End => {
4711 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
4712 s.frames = to - s.start;
4713 }
4714 }
4715 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
4716}
4717
4718/// The grouping invariant, checked in release at [`Project::from_parts`] and
4719/// asserted by the tests after every edit: a link id names **at most one**
4720/// placement per lane -- a clip on a media lane or a caption on a subtitle
4721/// one, whichever carries it. That is all "these move together" can mean now
4722/// that a group is assembled by hand: the members keep their own spans and
4723/// their own offsets, and what binds them is the id alone.
4724///
4725/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
4726/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
4727/// placements of one group may cover different frames -- the offset-preserving
4728/// group a hand builds with [`Project::group_all`], which a drag moves by one
4729/// delta rather than by one span.
4730///
4731/// A link no other lane carries is legal and is not an error: lifting one half
4732/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
4733/// timeline has to load again.
4734/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
4735/// asked by the sweep suite's universal law.
4736#[cfg(test)]
4737pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
4738 links_are_consistent(&p.lanes)
4739}
4740
4741fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
4742 let handles = handles(lanes);
4743 for (data, lane) in lanes.iter().zip(&handles) {
4744 for (i, c) in data.clips.iter().enumerate() {
4745 let Some(id) = c.link else { continue };
4746 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
4747 return Err(
4748 format!("link {id} names two clips in the {} lane", lane.label()).into(),
4749 );
4750 }
4751 }
4752 // ...and the same for the captions, in their own list on the same lane:
4753 // a subtitle lane holds no `Clip`, so this is the only list a caption's
4754 // id could be doubled on.
4755 for (i, s) in data.subs.iter().enumerate() {
4756 let Some(id) = s.link else { continue };
4757 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
4758 return Err(format!(
4759 "link {id} names two captions in the {} lane",
4760 lane.label()
4761 )
4762 .into());
4763 }
4764 }
4765 }
4766 Ok(())
4767}
4768
4769/// Removes the timeline frames `[start, end)` from `clips`: placements inside
4770/// it go, one straddling it is split in two, one overlapping an edge is
4771/// trimmed. Source frames follow the trim, so what is left plays what it always
4772/// played. Leaves the lane sorted and disjoint.
4773///
4774/// A piece the hole cut is no longer the take its group id names -- and both
4775/// halves of a straddled placement carrying that id would be the same id twice
4776/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
4777fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
4778 let mut out = Vec::with_capacity(clips.len() + 1);
4779 for c in clips.drain(..) {
4780 // Disjoint from the hole: untouched.
4781 if c.end() <= start || c.start >= end {
4782 out.push(c);
4783 continue;
4784 }
4785 // The head that survives in front of the hole -- as much source as fits
4786 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
4787 // which at real time is that room itself. Never *more*: a head that
4788 // outgrew its room would reach into the hole it is being cut out of,
4789 // which is exactly the overlap a slow clip punched at a frame its rate
4790 // cannot address used to leave (at 0.25x a single source frame is four
4791 // timeline frames, and three frames of room hold none of it). `None`
4792 // there means no remainder at all, and the piece simply goes.
4793 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
4794 && c.start < start
4795 {
4796 out.push(Clip {
4797 out_frame: c.in_frame + keep.min(c.len()),
4798 link: None,
4799 ..c
4800 });
4801 }
4802 // ...and the tail behind it, which keeps reading up to where it would
4803 // have: measured from its out-point for the head's reason, so what it
4804 // occupies still ends where the whole clip did -- and dropped whole on
4805 // the same `None`.
4806 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
4807 && c.end() > end
4808 {
4809 out.push(Clip {
4810 start: end,
4811 in_frame: c.out_frame - keep.min(c.len()),
4812 link: None,
4813 ..c
4814 });
4815 }
4816 }
4817 *clips = out;
4818}
4819
4820/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
4821/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
4822/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
4823/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
4824/// the caller.
4825fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
4826 for &i in on {
4827 let clips = &mut lanes[i].clips;
4828 clear(clips, at, at + len);
4829 for c in clips.iter_mut().filter(|c| c.start >= at) {
4830 c.start -= len;
4831 }
4832 debug_assert!(sorted_disjoint(clips));
4833 // The subtitle lanes close the hole with everything else: a caption
4834 // left standing where the picture it belongs to was cut out is the
4835 // desync a lane model exists to make impossible.
4836 let subs = &mut lanes[i].subs;
4837 sub_clear(subs, at, at + len);
4838 for s in subs.iter_mut().filter(|s| s.start >= at) {
4839 s.start -= len;
4840 }
4841 debug_assert!(subs_sorted_disjoint(subs));
4842 }
4843}
4844
4845/// Every lane, as the index list the two above take: what "the whole timeline"
4846/// is spelled as, and the scope [`Project::ripple_delete`] and
4847/// [`Project::split`] have always had.
4848fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
4849 (0..lanes.len()).collect()
4850}
4851
4852/// A caller's region list as a batch may use it: sorted by start, empty entries
4853/// dropped, and touching or overlapping entries merged into one.
4854///
4855/// Overlapping regions are the one thing a batch cannot take -- cutting the
4856/// second would cut frames the first already moved -- and a detector handing
4857/// back two that touch means one silence, not two cuts. Merged rather than
4858/// refused: this is arithmetic on a preview, not a user's mistake.
4859fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
4860 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
4861 sorted.sort_by_key(|&(at, _)| at);
4862 let mut out: Vec<(u32, u32)> = Vec::new();
4863 for (at, len) in sorted {
4864 let end = at.saturating_add(len);
4865 match out.last_mut() {
4866 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
4867 _ => out.push((at, len)),
4868 }
4869 }
4870 out
4871}
4872
4873/// Slides everything from `at` on later by `len`, splitting a placement that
4874/// straddles `at` so the two halves end up on either side of the hole. The
4875/// insert half of a rippling paste. The two halves lose the group id for the
4876/// reason [`clear`] gives.
4877fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
4878 if let Some(idx) = splittable(clips, at) {
4879 let mut tail = clips[idx];
4880 // The cut in *source* frames, at the clip's own rate. `splittable` has
4881 // already refused a frame the rate cannot address, which is why
4882 // [`Project::paste`] refuses one too rather than opening room inside a
4883 // clip that cannot be cut there.
4884 tail.in_frame = split_source(&tail, at).expect("splittable said so");
4885 tail.start = at;
4886 tail.link = None;
4887 clips[idx].out_frame = tail.in_frame;
4888 clips[idx].link = None;
4889 clips.insert(idx + 1, tail);
4890 }
4891 for c in clips.iter_mut().filter(|c| c.start >= at) {
4892 c.start += len;
4893 }
4894}
4895
4896/// Absolute, symlink-resolved when the file is reachable; the path as given
4897/// when it is not -- an unreadable path still deserves an index, it simply
4898/// dedups by spelling.
4899pub(crate) fn canonical(path: &Path) -> PathBuf {
4900 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
4901}
4902
4903#[cfg(test)]
4904mod tests {
4905 use super::*;
4906
4907 const FPS: f64 = 30.0;
4908 /// Never opened -- `Project` is pure data, so a path that does not exist is
4909 /// simply a path that dedups by spelling.
4910 const FILE: &str = "/nonexistent/a.mp4";
4911 const FILE2: &str = "/nonexistent/b.mp4";
4912
4913 /// A contiguous placement, group id ignored: what most assertions compare.
4914 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
4915 Clip {
4916 start,
4917 in_frame,
4918 out_frame,
4919 source,
4920 link: None,
4921 eq: None,
4922 color: None,
4923 fit: FitPolicy::default(),
4924 speed: Speed::NORMAL,
4925 }
4926 }
4927
4928 /// A recognisable equalizer setting: one peak band, `n` telling two of them
4929 /// apart -- which is what makes the table's dedup and its prune visible.
4930 fn band_at(n: u32) -> EqParams {
4931 EqParams {
4932 bands: vec![crate::eq::Band {
4933 freq_hz: 1000.0,
4934 gain_db: f64::from(n) as f32 * 1.5,
4935 q: 0.707,
4936 kind: crate::eq::BandKind::Peak,
4937 }],
4938 }
4939 }
4940
4941 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
4942 /// for the colour table.
4943 fn grade_at(n: u32) -> ColorParams {
4944 ColorParams {
4945 brightness: f64::from(n) as f32 * 0.05,
4946 ..Default::default()
4947 }
4948 }
4949
4950 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
4951 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
4952 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
4953 }
4954
4955 /// Every lane with its group ids blanked, for comparing shape.
4956 fn shape(p: &Project) -> Vec<Vec<Clip>> {
4957 p.lanes()
4958 .into_iter()
4959 .map(|l| {
4960 p.lane(l)
4961 .iter()
4962 .map(|c| Clip { link: None, ..*c })
4963 .collect()
4964 })
4965 .collect()
4966 }
4967
4968 /// The *source frame* every timeline frame reads, per lane -- the traversal
4969 /// a player performs. Deliberately not the clip index: a split changes which
4970 /// clip a frame belongs to, and nothing else.
4971 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
4972 (0..p.timeline_frames() + 2)
4973 .map(|f| {
4974 p.lanes()
4975 .into_iter()
4976 .map(|l| p.map(l, f).map(|(_, source)| source))
4977 .collect()
4978 })
4979 .collect()
4980 }
4981
4982 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
4983 /// fixture. Built through `split` so the constructor path is exercised too.
4984 fn three() -> Project {
4985 let mut p = Project::single(FILE, 9);
4986 assert!(p.split(3));
4987 assert!(p.split(5));
4988 assert_eq!(
4989 shape(&p),
4990 [
4991 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
4992 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
4993 ]
4994 );
4995 p
4996 }
4997
4998 #[test]
4999 fn single_is_the_whole_file_on_both_lanes() {
5000 let p = Project::single(FILE, 150);
5001 assert_eq!(p.clips().len(), 1);
5002 assert_eq!(p.lane(Lane::A1).len(), 1);
5003 assert_eq!(p.timeline_frames(), 150);
5004 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5005 // grouped: video and audio carry the same link
5006 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5007 assert!(p.clips()[0].link.is_some());
5008 // degenerate mapping: timeline == source
5009 assert_eq!(p.map_timeline(0), Some((0, 0)));
5010 assert_eq!(p.map_timeline(149), Some((0, 149)));
5011 assert_eq!(p.map_timeline(150), None);
5012 // never-empty invariant survives a bogus frame count
5013 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5014 }
5015
5016 #[test]
5017 fn split_cuts_every_lane_and_regroups_it_back() {
5018 let mut p = Project::single(FILE, 9);
5019 let before = traversal(&p);
5020 let before_shape = shape(&p);
5021
5022 assert!(p.split(4));
5023 for l in p.lanes() {
5024 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5025 }
5026 // The two sides are two groups, one per side, matching across the lanes.
5027 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5028 assert_eq!(v[0].link, a[0].link);
5029 assert_eq!(v[1].link, a[1].link);
5030 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5031 // A split changes no mapping, in either lane.
5032 assert_eq!(traversal(&p), before, "a split moves nothing");
5033
5034 assert!(p.regroup(4), "the inverse rejoins them");
5035 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5036 assert_eq!(traversal(&p), before);
5037 assert_eq!(
5038 p.lane(Lane::V1)[0].link,
5039 p.lane(Lane::A1)[0].link,
5040 "and the rejoined clip is one group again"
5041 );
5042 }
5043
5044 /// The music video's own path: the take comes apart into halves that carry
5045 /// ids of their own, one undo puts it back, and two clips over the same
5046 /// frames become one take again by hand.
5047 #[test]
5048 fn a_take_comes_apart_and_goes_back_together() {
5049 let mut p = Project::single(FILE, 9);
5050 let one = p.clips()[0].link.expect("a fresh project is one take");
5051 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5052
5053 // A third lane in the same group -- and the merge case with it: a
5054 // placement is in no group, and grouping it in leaves *one* group.
5055 let v2 = p.add_lane(LaneKind::Video);
5056 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5057 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
5058 p.group(Lane::V1, 0, v2, 0)
5059 .expect("the same frames, one lane over");
5060 let id = p.clips()[0].link.expect("still a group");
5061 assert!(
5062 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5063 "one id over the three, not two groups sharing a span"
5064 );
5065 links_are_consistent(&p.lanes).expect("one id, one span");
5066
5067 // Detached by the sound: every half of the group, not only the two.
5068 assert!(p.ungroup(Lane::A1, 0));
5069 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
5070 assert!(
5071 ids.iter().all(Option::is_some),
5072 "a half keeps an id of its own"
5073 );
5074 assert!(
5075 ids.iter()
5076 .enumerate()
5077 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
5078 "and no two halves are the same group any more: {ids:?}"
5079 );
5080 links_are_consistent(&p.lanes).expect("a lone id is legal");
5081
5082 // One snapshot for the whole detach.
5083 assert!(p.undo());
5084 assert!(
5085 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5086 "one undo puts the whole group back"
5087 );
5088
5089 // And back together by hand: the two the pointer named, and only them.
5090 assert!(p.ungroup(Lane::V1, 0));
5091 p.group(Lane::V1, 0, Lane::A1, 0)
5092 .expect("both cover [0, 9)");
5093 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
5094 assert_ne!(
5095 p.lane(v2)[0].link,
5096 p.lane(Lane::V1)[0].link,
5097 "the third half stayed detached"
5098 );
5099 links_are_consistent(&p.lanes).expect("one id, one span");
5100 }
5101
5102 /// What a group may not be, and what a detach has nothing to take apart --
5103 /// none of which may cost an undo step.
5104 #[test]
5105 fn a_group_is_one_span_and_one_clip_per_lane() {
5106 let mut p = three();
5107 let before = shape(&p);
5108 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
5109
5110 assert!(
5111 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
5112 "two clips of one lane are never one take"
5113 );
5114 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
5115 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
5116 assert!(
5117 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
5118 "{spans}"
5119 );
5120 assert!(
5121 spans.contains("trim them to matching bounds first"),
5122 "{spans}"
5123 );
5124 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
5125
5126 // A half nothing else is grouped with is already detached, a placement
5127 // is in no group at all, and an index that is not there has nothing to
5128 // detach either.
5129 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
5130 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
5131 assert!(p.lift(Lane::A1, 0));
5132 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
5133 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
5134
5135 // Two undos, one per edit: not one of the refusals pushed a snapshot.
5136 assert!(p.undo());
5137 assert!(p.undo());
5138 assert_eq!(shape(&p), before);
5139 }
5140
5141 /// Where a re-rate puts a playhead: the scene under the cursor stays the
5142 /// scene under the cursor, measured the way a viewer would -- the source
5143 /// frame playing at the playhead is the same frame after the write, at
5144 /// every playhead position the re-rate can catch one.
5145 #[test]
5146 fn a_re_rate_keeps_the_frame_under_the_playhead() {
5147 let caption = |start: u32, frames: u32| SubClip {
5148 start,
5149 frames,
5150 track: 0,
5151 in_us: 0,
5152 out_us: i64::from(frames) * 1_000_000,
5153 link: None,
5154 };
5155 let track = || SubtitleTrack {
5156 path: FILE.into(),
5157 track: None,
5158 language: "eng".into(),
5159 name: String::new(),
5160 label: "eng".into(),
5161 cues: Vec::new(),
5162 bitmap: false,
5163 refused: None,
5164 };
5165 // A group of a 300-frame clip and a caption offset 30 frames into it.
5166 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
5167 let s1 = p.add_lane(LaneKind::Subtitle);
5168 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
5169 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5170
5171 // The frame playing at `at`: which clip, and which source frame of it.
5172 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
5173 p.span_at(Lane::V1, at)
5174 .and_then(|s| s.from.map(|(source, from)| (source, from)))
5175 };
5176
5177 // Inside the held clip: the source frame under the playhead is the
5178 // same one after the re-rate, at 2x and at half speed both.
5179 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
5180 let at = 120;
5181 let before = playing(&p, at).expect("a clip under the playhead");
5182 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
5183 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
5184 .expect("room for it");
5185 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
5186 assert_eq!(before, after, "{what}: the same source frame plays");
5187 // ...and the write itself is untouched by the question.
5188 assert!(p.undo(), "{what}: one step back");
5189 }
5190
5191 // Past the group -- the clip ends at 300 and the caption at 270, so
5192 // from 300 on nothing is re-timed under the playhead: unmoved.
5193 for at in [300u32, 301, 1_000] {
5194 assert_eq!(
5195 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
5196 Some(at),
5197 "at {at}: outside every member, unmoved"
5198 );
5199 }
5200 // The boundary is exact: the held clip's own last frame (299) maps
5201 // to its new one (149 -- the last frame inside [0, 150), where the
5202 // shrunken clip's last source frame plays), and its first stays put.
5203 assert_eq!(
5204 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
5205 Some(149)
5206 );
5207 assert_eq!(
5208 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
5209 Some(0)
5210 );
5211 // A spot the caption shares with the clip maps by the clip (it is
5212 // what is *playing* there): the held clip's own proportion, which on
5213 // this fixture is also its head.
5214 assert_eq!(
5215 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
5216 Some(45),
5217 "the clip under the caption owns the spot"
5218 );
5219 }
5220
5221 /// A playhead inside another clip member of the group: that member keeps
5222 /// its own head, so the mapping is by its proportion and not the held
5223 /// clip's -- and the frame under the cursor is still the frame that was.
5224 #[test]
5225 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
5226 let mut p = Project::single(FILE, 300);
5227 // A second clip, grouped with the first but starting 300 later: the
5228 // head the group shares and its own differ by exactly that.
5229 let v2 = p.add_lane(LaneKind::Video);
5230 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
5231 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
5232 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
5233
5234 let at = 450; // inside the second member, 150 past its head
5235 let before = p.span_at(v2, at).and_then(|s| s.from);
5236 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
5237 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5238 .expect("room for it");
5239 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
5240 assert_eq!(before, after, "the second member's own frame plays");
5241 // ...and the mapping itself: 150 past its head halves, the head stays.
5242 assert_eq!(mapped, Some(375));
5243 }
5244
5245 /// The link counter a load seeds sits past every id the file names,
5246 /// captions included: a hand-grouped caption may carry the highest id there
5247 /// is, and a counter that read the clips alone would hand it to the next
5248 /// group that asked -- silently grouping the caption with clips it never
5249 /// met.
5250 #[test]
5251 fn the_link_counter_sits_past_a_caption_only_id() {
5252 let track = || SubtitleTrack {
5253 path: FILE.into(),
5254 track: None,
5255 language: "eng".into(),
5256 name: String::new(),
5257 label: "eng".into(),
5258 cues: Vec::new(),
5259 bitmap: false,
5260 refused: None,
5261 };
5262 let mut p = Project::single(FILE, 9);
5263 p.add_lane(LaneKind::Subtitle);
5264 let caption = SubClip {
5265 start: 0,
5266 frames: 6,
5267 track: 0,
5268 in_us: 0,
5269 out_us: 6_000_000,
5270 // The highest id in the file, and only a caption carries it.
5271 link: Some(1),
5272 };
5273 let mut p = p
5274 .with_subtitles(vec![track()])
5275 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
5276 .expect("a caption may carry the file's highest id");
5277
5278 // A new group on lanes the caption is not on mints the next id -- which
5279 // must not be the caption's.
5280 let v2 = p.add_lane(LaneKind::Video);
5281 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5282 p.group_all(&[(Lane::V1, 0), (v2, 0)])
5283 .expect("the clips group");
5284 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
5285 assert_ne!(
5286 minted,
5287 1,
5288 "the caption's id is not re-issued to clips"
5289 );
5290 assert_eq!(
5291 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
5292 Some(1),
5293 "the caption keeps its own group"
5294 );
5295 assert!(links_are_consistent(&p.lanes).is_ok());
5296 }
5297
5298 /// A rate re-times the caption members of the group by the ratio it gives
5299 /// the held clip: the span on the timeline compresses about the held clip's
5300 /// head, the words' own window untouched -- and one undo puts it back.
5301 #[test]
5302 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
5303 let caption = |start: u32, frames: u32| SubClip {
5304 start,
5305 frames,
5306 track: 0,
5307 in_us: 0,
5308 out_us: i64::from(frames) * 1_000_000,
5309 link: None,
5310 };
5311 let track = || SubtitleTrack {
5312 path: FILE.into(),
5313 track: None,
5314 language: "eng".into(),
5315 name: String::new(),
5316 label: "eng".into(),
5317 cues: Vec::new(),
5318 bitmap: false,
5319 refused: None,
5320 };
5321 let grouped = || {
5322 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5323 let s1 = p.add_lane(LaneKind::Subtitle);
5324 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5325 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5326 (p, s1)
5327 };
5328
5329 // An aligned take, doubled: the caption plays in half the frames.
5330 let (mut p, s1) = grouped();
5331 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5332 .expect("room for it");
5333 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
5334 let s = p.sub_lane(s1)[0];
5335 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
5336 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
5337 assert!(links_are_consistent(&p.lanes).is_ok());
5338 assert!(p.undo());
5339 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
5340
5341 // An offset group, slowed to half: the caption's *offset from the held
5342 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
5343 // 0.5x, and still ends where the clip does.
5344 let (mut p, s1) = grouped();
5345 p.lift_sub(s1, 0);
5346 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
5347 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5348 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
5349 .expect("room for it");
5350 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
5351 let s = p.sub_lane(s1)[0];
5352 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
5353 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
5354
5355 // A stretch that runs the caption into its neighbour is refused, by
5356 // lane and frame, and costs no undo step.
5357 let (mut p, s1) = grouped();
5358 p.lift_sub(s1, 0);
5359 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5360 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
5361 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5362 let history = p.history.len();
5363 let err = p
5364 .set_speed(Lane::V1, 0, Speed::from_permille(500))
5365 .unwrap_err()
5366 .to_string();
5367 assert!(
5368 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
5369 "{err}"
5370 );
5371 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
5372 }
5373
5374 /// The silence scan's speed-up re-times the captions on a scoped lane with
5375 /// everything else: the piece inside the region plays in the region's new
5376 /// frames, and what sits behind the region slides up with the clips.
5377 #[test]
5378 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
5379 let caption = |start: u32, frames: u32| SubClip {
5380 start,
5381 frames,
5382 track: 0,
5383 in_us: 0,
5384 out_us: i64::from(frames) * 1_000_000,
5385 link: None,
5386 };
5387 let track = || SubtitleTrack {
5388 path: FILE.into(),
5389 track: None,
5390 language: "eng".into(),
5391 name: String::new(),
5392 label: "eng".into(),
5393 cues: Vec::new(),
5394 bitmap: false,
5395 refused: None,
5396 };
5397 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5398 let s1 = p.add_lane(LaneKind::Subtitle);
5399 // Words over the region [30, 60) and words behind it.
5400 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5401 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
5402
5403 // The region [30, 60) plays at 4x: 30 frames become 8, everything
5404 // behind slides up 22.
5405 // The scope is what the card's Take row says, caption lane included.
5406 p.speed_regions(
5407 &[(30, 30)],
5408 Speed::from_permille(4000),
5409 &[Lane::V1, Lane::A1, s1],
5410 )
5411 .expect("the region speeds up");
5412 let subs = p.sub_lane(s1);
5413 assert_eq!(
5414 (subs[0].start, subs[0].frames),
5415 (30, 8),
5416 "the piece inside plays in the region's new frames"
5417 );
5418 assert_eq!(
5419 (subs[1].start, subs[1].frames),
5420 (38, 30),
5421 "the piece behind slides up by what the region gave back"
5422 );
5423 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
5424 }
5425
5426 /// [`Project::speeded_playhead`]'s caption arm fires only when the
5427 /// playhead is inside a caption member and outside every clip member --
5428 /// a shape every other fixture avoids by keeping its caption inside the
5429 /// held clip. Here the caption overhangs the clip's tail, and the
5430 /// playhead standing in that overhang is answered by the caption's own
5431 /// piece: it scales about the held clip's head by the held clip's own
5432 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
5433 #[test]
5434 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
5435 let caption = |start: u32, frames: u32| SubClip {
5436 start,
5437 frames,
5438 track: 0,
5439 in_us: 0,
5440 out_us: i64::from(frames) * 1_000_000,
5441 link: None,
5442 };
5443 let track = || SubtitleTrack {
5444 path: FILE.into(),
5445 track: None,
5446 language: "eng".into(),
5447 name: String::new(),
5448 label: "eng".into(),
5449 cues: Vec::new(),
5450 bitmap: false,
5451 refused: None,
5452 };
5453 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5454 let s1 = p.add_lane(LaneKind::Subtitle);
5455 // The caption spans [80, 100) -- ten frames past the clip's own end
5456 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
5457 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
5458 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5459 // At 2x the clip halves to 45 frames; the overhang frame 95, which
5460 // no clip member's old span reaches, is the caption's own question:
5461 // half of 95 is 47.5, rounded to 48.
5462 assert_eq!(
5463 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
5464 Some(48),
5465 "the overhang frame answers through the caption's own piece"
5466 );
5467 }
5468
5469 /// `write_speed` and `speeded_playhead` are two questions of the SAME
5470 /// map ([`map`]'s architecture law): a caption's landed span comes from
5471 /// the map's own ends, and the playhead standing at the caption's own
5472 /// last frame before the write has to land exactly where the write put
5473 /// it -- across clip lengths and rates that round differently, and an
5474 /// odd-length caption straddling the clip's own tail edge, the corner
5475 /// where `write_speed` used to answer a frame short.
5476 #[test]
5477 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
5478 let caption = |start: u32, frames: u32| SubClip {
5479 start,
5480 frames,
5481 track: 0,
5482 in_us: 0,
5483 out_us: i64::from(frames) * 1_000_000,
5484 link: None,
5485 };
5486 let track = || SubtitleTrack {
5487 path: FILE.into(),
5488 track: None,
5489 language: "eng".into(),
5490 name: String::new(),
5491 label: "eng".into(),
5492 cues: Vec::new(),
5493 bitmap: false,
5494 refused: None,
5495 };
5496 for &len in &[90u32, 91, 177, 300, 301] {
5497 for &permille in &[500u16, 2000, 2500, 3000] {
5498 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
5499 let s1 = p.add_lane(LaneKind::Subtitle);
5500 // An odd-length caption straddling the clip's tail edge: its
5501 // own last frame lands past the held clip.
5502 let c_start = len.saturating_sub(3);
5503 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
5504 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5505 let speed = Speed::from_permille(permille);
5506 let last = c_start + 7 - 1;
5507 let mapped = p
5508 .speeded_playhead(Lane::V1, 0, speed, last)
5509 .expect("the caption is there");
5510 if p.set_speed(Lane::V1, 0, speed).is_err() {
5511 continue; // a refusal changes nothing: not this law's cell
5512 }
5513 let landed = p.sub_lane(s1)[0];
5514 if permille >= 1000 {
5515 // A speed-up compresses the timeline: many old frames
5516 // share one new frame, so the caption's own last old
5517 // frame lands flush with the write's own boundary --
5518 // the exact law [`write_speed`]'s worked drift-fix case
5519 // is stated against.
5520 assert_eq!(
5521 mapped,
5522 landed.end() - 1,
5523 "len {len} permille {permille}: the playhead at the caption's own \
5524 last frame lands where the write actually put it"
5525 );
5526 } else {
5527 // A slow-down expands it: one old frame becomes several
5528 // new ones, and `apply` answers where that frame's own
5529 // block *starts*, not where the caption's last new
5530 // frame (the end of that same block) sits -- a
5531 // one-frame gap inherent to the piece's own semantics,
5532 // not a drift between the two callers. Both still have
5533 // to agree the answer sits inside the caption the write
5534 // actually landed.
5535 assert!(
5536 (landed.start..landed.end()).contains(&mapped),
5537 "len {len} permille {permille}: the playhead lands inside the \
5538 caption the write actually put ({landed:?}), got {mapped}"
5539 );
5540 }
5541 }
5542 }
5543 }
5544
5545 /// A grouped caption's cues re-time with its clip: the placement's window
5546 /// crossed the timeline at its own proportion before any rate, and a
5547 /// re-rate changes that proportion (the frames compress, the window does
5548 /// not). A cue eight seconds into a window played at 2x crosses the screen
5549 /// four seconds in -- and at unity every cue lands exactly where it always
5550 /// did, byte for byte.
5551 #[test]
5552 fn a_grouped_captions_cues_re_time_with_its_clip() {
5553 let track = SubtitleTrack {
5554 path: FILE.into(),
5555 track: None,
5556 language: "eng".into(),
5557 name: String::new(),
5558 label: "eng".into(),
5559 cues: vec![crate::subtitle::Cue {
5560 start_us: 8_000_000,
5561 end_us: 9_000_000,
5562 text: "late line".into(),
5563 image: None,
5564 }],
5565 bitmap: false,
5566 refused: None,
5567 };
5568 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
5569 let s1 = p.add_lane(LaneKind::Subtitle);
5570 // Ten seconds of the track over ten seconds of timeline: unity.
5571 p.place_sub(
5572 s1,
5573 0,
5574 SubClip {
5575 start: 0,
5576 frames: 300,
5577 track: 0,
5578 in_us: 0,
5579 out_us: 10_000_000,
5580 link: None,
5581 },
5582 )
5583 .expect("placed");
5584
5585 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
5586 let unity = p.sub_lane_cues(s1, FPS);
5587 assert_eq!(
5588 unity
5589 .iter()
5590 .map(|c| (c.start_us, c.end_us, &*c.text))
5591 .collect::<Vec<_>>(),
5592 [(8_000_000, 9_000_000, "late line")],
5593 "a unity placement maps exactly as it always did"
5594 );
5595
5596 // Grouped with the clip and re-rated to 2x: the same window now crosses
5597 // in half the time, so the cue at 8s of it lands 4s in.
5598 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5599 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5600 .expect("room for it");
5601 let re_timed = p.sub_lane_cues(s1, FPS);
5602 assert_eq!(
5603 re_timed
5604 .iter()
5605 .map(|c| (c.start_us, c.end_us))
5606 .collect::<Vec<_>>(),
5607 [(4_000_000, 4_500_000)],
5608 "the cue crosses with the clip's new rate"
5609 );
5610 }
5611
5612 /// A video arriving on a timeline of words mutates none of them: the
5613 /// import's rippling insert used to open room on the subtitle lanes too,
5614 /// splitting a caption it landed inside and sliding the rest behind the
5615 /// video -- the hand asked for an add, and got a cut it never made. The
5616 /// words keep their own clock; co-travel is what a group is for.
5617 #[test]
5618 fn an_arriving_clip_never_touches_the_captions() {
5619 let caption = |start: u32, frames: u32| SubClip {
5620 start,
5621 frames,
5622 track: 0,
5623 in_us: i64::from(start) * 1_000_000 / 30,
5624 out_us: i64::from(start + frames) * 1_000_000 / 30,
5625 link: None,
5626 };
5627 let track = || SubtitleTrack {
5628 path: FILE.into(),
5629 track: None,
5630 language: "eng".into(),
5631 name: String::new(),
5632 label: "eng".into(),
5633 cues: Vec::new(),
5634 bitmap: false,
5635 refused: None,
5636 };
5637 // A timeline of words alone: 60 frames of caption, no media clips.
5638 let mut p = Project::single(FILE, 60)
5639 .with_subtitles(vec![track()]);
5640 for l in [Lane::V1, Lane::A1] {
5641 while !p.lane(l).is_empty() {
5642 p.lift(l, 0);
5643 }
5644 }
5645 let s1 = p.add_lane(LaneKind::Subtitle);
5646 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
5647 let before = p.sub_lane(s1).to_vec();
5648
5649 // The video lands BEFORE the caption's span: nothing moves.
5650 let vid = clip(0, 0, 30, 0);
5651 assert!(p.paste(0, vid), "the video goes down at the head");
5652 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
5653
5654 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
5655 // byte the placement the hand made.
5656 assert!(p.paste(15, vid), "a second video lands inside the caption");
5657 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
5658 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
5659 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
5660 assert!(links_are_consistent(&p.lanes).is_ok());
5661 }
5662
5663 /// The region's caption pieces re-time by mapped boundaries forced apart:
5664 /// rounding start and length independently can land two cues on one frame,
5665 /// and the artifact is clamped -- one frame each, in order, none past the
5666 /// region's new end -- never an overlap on the lane.
5667 #[test]
5668 fn a_regions_caption_pieces_never_round_onto_one_another() {
5669 let caption = |start: u32, frames: u32| SubClip {
5670 start,
5671 frames,
5672 track: 0,
5673 in_us: 0,
5674 out_us: i64::from(frames) * 1_000_000,
5675 link: None,
5676 };
5677 let track = |n| SubtitleTrack {
5678 path: FILE.into(),
5679 track: None,
5680 language: "eng".into(),
5681 name: String::new(),
5682 label: format!("eng{n}"),
5683 cues: Vec::new(),
5684 bitmap: false,
5685 refused: None,
5686 };
5687 // Three lanes, one repro shape each: adjacent one-frame cues, a
5688 // three-frame pair, and the region's last cue against the first
5689 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
5690 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
5691 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
5692 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
5693 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
5694 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
5695 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
5696 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
5697 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
5698
5699 let mut scope = vec![Lane::V1, Lane::A1];
5700 scope.extend(lanes.iter().copied());
5701 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
5702 .expect("the region speeds up");
5703 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
5704 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
5705 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
5706 };
5707 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
5708 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
5709 // and the walk pushes the second to where the first ends.
5710 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
5711 // The last cue of the region ends exactly where the region now does
5712 // (frame 15), and the caption behind it lands on that same frame:
5713 // touching, never overlapping.
5714 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
5715 for &lane in &lanes {
5716 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
5717 }
5718 }
5719
5720 /// The scope law names a caption half too: a scoped cut that would move one
5721 // track of a group whose caption sits outside the scope is refused.
5722 #[test]
5723 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
5724 let caption = |start: u32, frames: u32| SubClip {
5725 start,
5726 frames,
5727 track: 0,
5728 in_us: 0,
5729 out_us: i64::from(frames) * 1_000_000,
5730 link: None,
5731 };
5732 let track = || SubtitleTrack {
5733 path: FILE.into(),
5734 track: None,
5735 language: "eng".into(),
5736 name: String::new(),
5737 label: "eng".into(),
5738 cues: Vec::new(),
5739 bitmap: false,
5740 refused: None,
5741 };
5742 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5743 let s1 = p.add_lane(LaneKind::Subtitle);
5744 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5745 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5746
5747 // The subtitle lane is not in the scope, so the group's caption half
5748 // sits outside it: refused, in the law's own words.
5749 let err = p
5750 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
5751 .unwrap_err()
5752 .to_string();
5753 assert!(
5754 err.contains("is one take with the S1 caption at frame 0"),
5755 "{err}"
5756 );
5757
5758 // ...and with the caption's lane in the scope, the cut carries it:
5759 // the words over the hole go, and the words behind slide up.
5760 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
5761 .expect("the whole group is in the scope");
5762 let subs = p.sub_lane(s1);
5763 assert_eq!(
5764 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
5765 [(0, 10), (10, 75)],
5766 "the caption is cut and shifted with the clips"
5767 );
5768 }
5769
5770 /// The caption a hand groups: `group_all` over clips *and* a caption, the
5771 /// mates riding along, the offsets kept, the refusals in words.
5772 #[test]
5773 fn a_hand_built_group_holds_clips_and_a_caption() {
5774 let caption = |start: u32, frames: u32| SubClip {
5775 start,
5776 frames,
5777 track: 0,
5778 in_us: 0,
5779 out_us: i64::from(frames) * 1_000_000,
5780 link: None,
5781 };
5782 let track = || SubtitleTrack {
5783 path: FILE.into(),
5784 track: None,
5785 language: "eng".into(),
5786 name: String::new(),
5787 label: "eng".into(),
5788 cues: Vec::new(),
5789 bitmap: false,
5790 refused: None,
5791 };
5792 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5793 let v2 = p.add_lane(LaneKind::Video);
5794 let s1 = p.add_lane(LaneKind::Subtitle);
5795 // A layer at its own offset, and a caption over the head of the take.
5796 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
5797 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
5798
5799 // Too few, one lane twice, and an index that is not there: words, no
5800 // snapshot.
5801 let history = p.history.len();
5802 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
5803 assert!(p
5804 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
5805 .unwrap_err()
5806 .to_string()
5807 .contains("V1 is picked twice"));
5808 assert!(p
5809 .group_all(&[(Lane::V1, 0), (s1, 9)])
5810 .unwrap_err()
5811 .to_string()
5812 .contains("no subtitle 9"));
5813 assert_eq!(p.history.len(), history, "refusals cost no undo step");
5814
5815 // The group: the picture, the layer, and the caption -- and the sound
5816 // the picture was already grouped with comes along unasked.
5817 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
5818 .expect("three picks, three lanes");
5819 let id = p.lane(Lane::V1)[0].link.expect("grouped");
5820 for lane in [Lane::V1, Lane::A1, v2] {
5821 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
5822 }
5823 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
5824 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
5825 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
5826 assert!(links_are_consistent(&p.lanes).is_ok());
5827 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
5828
5829 // ...and one undo takes it apart again.
5830 assert!(p.undo());
5831 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
5832
5833 // Detach names a caption like it names a clip: every member an id of
5834 // its own, which is never `None` (see `ungroup`).
5835 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
5836 assert!(p.ungroup(s1, 0));
5837 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
5838 assert!(loose_sub.is_some() && loose_clip.is_some());
5839 assert_ne!(loose_sub, loose_clip);
5840 assert!(links_are_consistent(&p.lanes).is_ok());
5841 }
5842
5843 /// Two captions on one sub lane, each already grouped with a *different*
5844 /// clip: `group_all` over both those clips would merge the two existing
5845 /// groups into one id and leave both captions on `s1` carrying it --
5846 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
5847 /// group closes. Refused by name, and nothing moves.
5848 #[test]
5849 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
5850 let caption = |start: u32, frames: u32| SubClip {
5851 start,
5852 frames,
5853 track: 0,
5854 in_us: 0,
5855 out_us: i64::from(frames) * 1_000_000,
5856 link: None,
5857 };
5858 let track = || SubtitleTrack {
5859 path: FILE.into(),
5860 track: None,
5861 language: "eng".into(),
5862 name: String::new(),
5863 label: "eng".into(),
5864 cues: Vec::new(),
5865 bitmap: false,
5866 refused: None,
5867 };
5868 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5869 let v2 = p.add_lane(LaneKind::Video);
5870 let s1 = p.add_lane(LaneKind::Subtitle);
5871 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
5872 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
5873 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5874 // V1 grouped with the first caption, v2 with the second -- two
5875 // separate groups, each already one member per lane.
5876 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5877 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
5878 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
5879
5880 let history = p.history.len();
5881 let err = p
5882 .group_all(&[(Lane::V1, 0), (v2, 0)])
5883 .unwrap_err()
5884 .to_string();
5885 assert!(err.contains("one placement per lane"), "{err}");
5886 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
5887 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
5888 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
5889 assert!(links_are_consistent(&p.lanes).is_ok());
5890 }
5891
5892 /// A split hands the caption of a group the same ids it hands the clips:
5893 /// the left halves keep the group, the right halves share a fresh one.
5894 #[test]
5895 fn a_split_cuts_a_grouped_caption_with_its_clips() {
5896 let caption = |start: u32, frames: u32| SubClip {
5897 start,
5898 frames,
5899 track: 0,
5900 in_us: 0,
5901 out_us: i64::from(frames) * 1_000_000,
5902 link: None,
5903 };
5904 let track = || SubtitleTrack {
5905 path: FILE.into(),
5906 track: None,
5907 language: "eng".into(),
5908 name: String::new(),
5909 label: "eng".into(),
5910 cues: Vec::new(),
5911 bitmap: false,
5912 refused: None,
5913 };
5914 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5915 let s1 = p.add_lane(LaneKind::Subtitle);
5916 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
5917 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5918 let take = p.lane(Lane::V1)[0].link.expect("the group id");
5919
5920 assert!(p.split(4));
5921 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
5922 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
5923 assert_eq!(left.frames, 4);
5924 assert_eq!(
5925 right.link,
5926 p.lane(Lane::V1)[1].link,
5927 "the caption's tail shares the clips' fresh id"
5928 );
5929 assert_ne!(right.link, Some(take));
5930 assert!(links_are_consistent(&p.lanes).is_ok());
5931
5932 // Regroup at the seam restores the take, caption included.
5933 assert!(p.regroup(4));
5934 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
5935 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
5936 }
5937
5938 /// Deleting a member of a hand-built group takes the group: every
5939 /// member's own span out of its own lane, hole closed -- the lanes may
5940 /// end up out of step, which is what one undo restores together.
5941 #[test]
5942 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
5943 let caption = |start: u32, frames: u32| SubClip {
5944 start,
5945 frames,
5946 track: 0,
5947 in_us: 0,
5948 out_us: i64::from(frames) * 1_000_000,
5949 link: None,
5950 };
5951 let track = || SubtitleTrack {
5952 path: FILE.into(),
5953 track: None,
5954 language: "eng".into(),
5955 name: String::new(),
5956 label: "eng".into(),
5957 cues: Vec::new(),
5958 bitmap: false,
5959 refused: None,
5960 };
5961 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5962 let s1 = p.add_lane(LaneKind::Subtitle);
5963 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
5964 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5965 // A neighbour on a lane the group does not touch.
5966 let v2 = p.add_lane(LaneKind::Video);
5967 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
5968
5969 // By the picture or by the caption, the same whole-group delete.
5970 assert!(p.delete_sub_in(s1, 0));
5971 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
5972 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
5973 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
5974 assert!(links_are_consistent(&p.lanes).is_ok());
5975 assert!(p.undo(), "one step puts the group back");
5976 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
5977 }
5978
5979 /// The delete law, one statement for every anchor: a caption deleted
5980 /// WITH its group ripples its lane exactly as its clip siblings do --
5981 /// the hole closes and what follows slides up -- while a caption lifted
5982 /// alone leaves its gap, as it always has. And the delete of a grouped
5983 /// clip takes the group from whichever member was clicked.
5984 #[test]
5985 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
5986 let caption = |start: u32, frames: u32| SubClip {
5987 start,
5988 frames,
5989 track: 0,
5990 in_us: 0,
5991 out_us: i64::from(frames) * 1_000_000,
5992 link: None,
5993 };
5994 let track = || SubtitleTrack {
5995 path: FILE.into(),
5996 track: None,
5997 language: "eng".into(),
5998 name: String::new(),
5999 label: "eng".into(),
6000 cues: Vec::new(),
6001 bitmap: false,
6002 refused: None,
6003 };
6004 // V+A+S grouped, with a second caption BEHIND the group's caption:
6005 // closing the hole is what the second caption's position says.
6006 let group = || {
6007 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6008 let s1 = p.add_lane(LaneKind::Subtitle);
6009 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
6010 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
6011 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6012 (p, s1)
6013 };
6014
6015 // Deleted by the picture: all three lanes close.
6016 let (mut p, s1) = group();
6017 assert!(p.delete_in(Lane::V1, 0));
6018 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
6019 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
6020 assert_eq!(
6021 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
6022 [60],
6023 "the caption's lane closed by its own span: the follower slid up"
6024 );
6025 assert!(p.undo(), "one step");
6026 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
6027
6028 // By the sound: the same whole-group delete.
6029 let (mut p, s1) = group();
6030 assert!(p.delete_in(Lane::A1, 0));
6031 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6032 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6033
6034 // By the caption itself: the same again.
6035 let (mut p, s1) = group();
6036 assert!(p.delete_sub_in(s1, 0));
6037 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6038 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6039 assert!(links_are_consistent(&p.lanes).is_ok());
6040
6041 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6042 // unchanged.
6043 let (mut p, s1) = group();
6044 assert!(p.ungroup(s1, 0), "the caption stands alone");
6045 assert!(p.lift_sub(s1, 0));
6046 assert_eq!(
6047 p.sub_lane(s1)[0].start, 90,
6048 "the follower stayed put: a lone caption's lift is a gap"
6049 );
6050 }
6051
6052 /// Dragging a grouped caption carries its clips, one delta for all of them
6053 /// -- and a caption in no group refuses an overlap exactly as it always did.
6054 #[test]
6055 fn dragging_a_grouped_caption_carries_its_group() {
6056 let caption = |start: u32, frames: u32| SubClip {
6057 start,
6058 frames,
6059 track: 0,
6060 in_us: 0,
6061 out_us: i64::from(frames) * 1_000_000,
6062 link: None,
6063 };
6064 let track = || SubtitleTrack {
6065 path: FILE.into(),
6066 track: None,
6067 language: "eng".into(),
6068 name: String::new(),
6069 label: "eng".into(),
6070 cues: Vec::new(),
6071 bitmap: false,
6072 refused: None,
6073 };
6074 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6075 let s1 = p.add_lane(LaneKind::Subtitle);
6076 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6077 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6078
6079 // Same lane, further along: everyone moves by the same eight frames.
6080 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
6081 assert_eq!(p.sub_lane(s1)[0].start, 10);
6082 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
6083 assert!(links_are_consistent(&p.lanes).is_ok());
6084
6085 // ...and an ungrouped caption is the caption it always was.
6086 assert!(p.ungroup(s1, 0));
6087 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
6088 let s1 = q.add_lane(LaneKind::Subtitle);
6089 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
6090 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
6091 assert!(q
6092 .move_sub(s1, 0, s1, 3)
6093 .unwrap_err()
6094 .to_string()
6095 .contains("already covers"));
6096 }
6097
6098 /// A trim carries a group's caption by the same delta as its clips, clamped
6099 /// to the caption's own walls -- the offsets between the members survive.
6100 #[test]
6101 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
6102 let caption = |start: u32, frames: u32| SubClip {
6103 start,
6104 frames,
6105 track: 0,
6106 in_us: 0,
6107 out_us: i64::from(frames) * 1_000_000,
6108 link: None,
6109 };
6110 let track = || SubtitleTrack {
6111 path: FILE.into(),
6112 track: None,
6113 language: "eng".into(),
6114 name: String::new(),
6115 label: "eng".into(),
6116 cues: Vec::new(),
6117 bitmap: false,
6118 refused: None,
6119 };
6120 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6121 let s1 = p.add_lane(LaneKind::Subtitle);
6122 // The caption sits two frames into the take and ends one early. The
6123 // source runs past the clip, or there is no tail to pull out.
6124 let src = &[20];
6125 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
6126 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6127
6128 // The tail goes out by three: the clip to 12, the caption to 11.
6129 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
6130 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
6131 assert_eq!(
6132 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
6133 (2, 11),
6134 "the caption follows by the delta"
6135 );
6136 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
6137
6138 // The head comes in by two: everyone's start moves two along.
6139 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
6140 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
6141 assert!(links_are_consistent(&p.lanes).is_ok());
6142 }
6143
6144 #[test]
6145 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
6146 let mut p = three();
6147 let before = shape(&p);
6148 assert!(!p.split(0), "timeline 0 has nothing before it");
6149 assert!(!p.split(3), "existing boundary");
6150 assert!(!p.split(5), "existing boundary");
6151 assert!(!p.split(9), "one past the last frame");
6152 assert!(!p.split(1_000));
6153 assert_eq!(shape(&p), before);
6154 // one undo lands before the *second* split, so the refusals pushed nothing
6155 assert!(p.undo());
6156 assert_eq!(p.clips().len(), 2, "refused splits push no history");
6157
6158 // ...and a frame that is a gap in both lanes has nothing to split.
6159 let mut p = three();
6160 assert!(p.lift(Lane::V1, 1));
6161 assert!(p.lift(Lane::A1, 1));
6162 assert!(!p.split(4), "a gap is not a clip");
6163 }
6164
6165 #[test]
6166 fn regroup_refuses_what_a_split_could_not_have_made() {
6167 let mut p = three();
6168 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
6169 assert!(p.regroup(5));
6170 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
6171 // A boundary with a gap on one side, and one where the sources do not
6172 // meet, are both refused.
6173 let mut p = three();
6174 assert!(p.lift(Lane::V1, 1));
6175 assert!(p.lift(Lane::A1, 1));
6176 assert!(!p.regroup(3), "nothing starts at 3 any more");
6177 let mut p = three();
6178 for l in p.lanes() {
6179 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
6180 }
6181 assert!(!p.regroup(3), "source 100 does not follow source 3");
6182 assert!(!p.regroup(0), "nothing ends at 0");
6183 assert!(!p.regroup(1_000));
6184 }
6185
6186 #[test]
6187 fn map_and_spans_sweep_every_boundary() {
6188 let p = three();
6189 assert_eq!(p.timeline_frames(), 9);
6190 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
6191 // contiguous source here, so the clip index is what actually moves
6192 let expect = [
6193 (0, (0, 0)),
6194 (1, (0, 1)),
6195 (2, (0, 2)),
6196 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
6197 (4, (1, 4)),
6198 (5, (2, 5)),
6199 (6, (2, 6)),
6200 (7, (2, 7)),
6201 (8, (2, 8)),
6202 ];
6203 for (t, want) in expect {
6204 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
6205 }
6206 assert_eq!(p.map_timeline(9), None);
6207 // A span is the rest of the clip from where it was asked about.
6208 assert_eq!(
6209 p.span_at(Lane::V1, 6),
6210 Some(Span {
6211 start: 6,
6212 len: 3,
6213 from: Some((0, 6)),
6214 speed: Speed::NORMAL
6215 })
6216 );
6217 assert_eq!(p.span_at(Lane::V1, 9), None);
6218 }
6219
6220 /// The fit policy is one byte *in* the clip rather than an index into a
6221 /// table like the eq and the grade: there is nothing for a table to share.
6222 /// It costs the clip nothing at all -- the fields before it (a `usize`
6223 /// source and two `Option<u16>`s) already left the struct padded to 40
6224 /// bytes, and the byte landed in that padding. This is the assert that says
6225 /// so: a clip that grew a word grew every undo snapshot and every clipboard
6226 /// copy with it.
6227 #[test]
6228 fn a_fit_policy_costs_the_clip_no_word() {
6229 assert_eq!(
6230 std::mem::size_of::<Clip>(),
6231 40,
6232 "Clip changed size: {} bytes",
6233 std::mem::size_of::<Clip>()
6234 );
6235 }
6236
6237 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
6238 /// anything in `three()` so it is recognisable wherever it lands.
6239 const PASTED: Clip = Clip {
6240 start: 0,
6241 in_frame: 100,
6242 out_frame: 102,
6243 source: 0,
6244 link: None,
6245 eq: None,
6246 color: None,
6247 fit: FitPolicy::Fit,
6248 speed: Speed::NORMAL,
6249 };
6250
6251 #[test]
6252 fn paste_mid_clip_splits_around_it() {
6253 let mut p = three();
6254 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
6255 assert_eq!(p.timeline_frames(), 11);
6256 assert_eq!(
6257 shape(&p)[0],
6258 vec![
6259 clip(0, 0, 3, 0),
6260 clip(3, 3, 5, 0),
6261 clip(5, 5, 6, 0),
6262 clip(6, 100, 102, 0),
6263 clip(8, 6, 9, 0),
6264 ]
6265 );
6266 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
6267 // The pasted frames are exactly where they were asked for, and the
6268 // split-off remainder resumes after them.
6269 assert_eq!(p.map_timeline(6), Some((3, 100)));
6270 assert_eq!(p.map_timeline(7), Some((3, 101)));
6271 assert_eq!(p.map_timeline(8), Some((4, 6)));
6272 }
6273
6274 #[test]
6275 fn paste_at_boundary_zero_and_end() {
6276 let mut p = three();
6277 assert!(p.paste(3, PASTED), "existing boundary: no split");
6278 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
6279 assert_eq!(p.map_timeline(3), Some((1, 100)));
6280
6281 let mut p = three();
6282 assert!(p.paste(0, PASTED));
6283 assert_eq!(p.map_timeline(0), Some((0, 100)));
6284 assert_eq!(p.map_timeline(2), Some((1, 0)));
6285
6286 // At the end: appended, there being nothing in front to leave black.
6287 let mut p = three();
6288 assert!(p.paste(9, PASTED));
6289 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
6290 // Past it: down on the frame it was asked for, black in front of it --
6291 // a row let go on the open bed lands under the ghost that promised it.
6292 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
6293 assert!(p.paste(1_000, PASTED));
6294 assert_eq!(p.timeline_frames(), 1_002);
6295 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
6296 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
6297
6298 // An empty clip is the one thing refused, and it pushes no history.
6299 let mut p = three();
6300 assert!(!p.paste(4, clip(0, 7, 7, 0)));
6301 assert_eq!(p.clips().len(), 3);
6302 }
6303
6304 /// The data-loss paste: a clip of a source with no picture used to land on
6305 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
6306 /// carried it was refused on the way back in ("a box with a larger size").
6307 #[test]
6308 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
6309 let mut p = three();
6310 let wav = p.import("/nonexistent/song.wav", 0);
6311 let copied = Clip {
6312 source: wav,
6313 ..PASTED
6314 };
6315 assert!(p.paste(3, copied));
6316 // The room is opened on every lane, or the two would slide apart...
6317 assert_eq!(p.timeline_frames(), 11);
6318 assert_eq!(
6319 shape(&p)[0],
6320 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
6321 "the video lane got room and nothing else"
6322 );
6323 // ...but the clip itself only reaches the lane that can play it.
6324 assert_eq!(
6325 shape(&p)[1],
6326 vec![
6327 clip(0, 0, 3, 0),
6328 clip(3, 100, 102, wav),
6329 clip(5, 3, 5, 0),
6330 clip(7, 5, 9, 0)
6331 ]
6332 );
6333 // A source with a picture is unchanged: still the grouped pair.
6334 let mut p = three();
6335 assert!(p.paste(3, PASTED));
6336 assert_eq!(shape(&p)[0], shape(&p)[1]);
6337 }
6338
6339 /// A hand-written file may hold a clip that ends at the very last frame
6340 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
6341 /// to wrap its start round to the front of the lane: an overlap in debug, a
6342 /// project no reload would accept in release.
6343 #[test]
6344 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
6345 let far = clip(u32::MAX - 90, 0, 90, 0);
6346 let parts = |c: Clip| {
6347 Project::from_parts(
6348 vec![Source::new(FILE, 0)],
6349 two(vec![c], vec![c]),
6350 Vec::new(),
6351 Vec::new(),
6352 )
6353 .expect("valid parts")
6354 };
6355 let mut p = parts(far);
6356 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
6357 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
6358 assert!(!p.undo(), "...and pushes no history either");
6359 assert!(
6360 !p.paste(u32::MAX, PASTED),
6361 "appending has nowhere to go either: the timeline ends at the last frame"
6362 );
6363 // With room for exactly those frames the same paste is taken.
6364 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
6365 assert!(p.paste(0, PASTED));
6366 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
6367 }
6368
6369 #[test]
6370 fn paste_undoes_in_one_step() {
6371 let mut p = three();
6372 let before = shape(&p);
6373 assert!(p.paste(6, PASTED));
6374 assert!(p.undo());
6375 assert_eq!(shape(&p), before, "a paste is one undo step");
6376 }
6377
6378 #[test]
6379 fn a_copy_outlives_the_clip_it_came_from() {
6380 let mut p = three();
6381 let copied = p.clips()[1]; // [3,5)
6382 assert!(p.delete(1));
6383 // Just a frame range: the source is still on disk either way.
6384 assert!(p.paste(0, copied));
6385 assert_eq!(p.map_timeline(0), Some((0, 3)));
6386 assert_eq!(p.timeline_frames(), 9);
6387 }
6388
6389 #[test]
6390 fn delete_closes_the_gap_on_both_lanes() {
6391 let mut p = three();
6392 assert!(p.delete(1));
6393 assert_eq!(p.timeline_frames(), 7);
6394 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
6395 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
6396 // timeline 3 used to be source 3; the gap closed so it is source 5 now
6397 assert_eq!(p.map_timeline(3), Some((1, 5)));
6398 assert_eq!(p.map_timeline(6), Some((1, 8)));
6399 assert_eq!(p.map_timeline(7), None);
6400 }
6401
6402 #[test]
6403 fn delete_first_last_and_only() {
6404 let mut p = three();
6405 assert!(p.delete(0));
6406 assert_eq!(p.map_timeline(0), Some((0, 3)));
6407 assert_eq!(p.timeline_frames(), 6);
6408
6409 let mut p = three();
6410 assert!(p.delete(2));
6411 assert_eq!(p.timeline_frames(), 5);
6412 assert_eq!(p.map_timeline(4), Some((1, 4)));
6413
6414 assert!(!p.delete(2), "index past the end");
6415 assert!(p.delete(1));
6416 assert!(p.delete(0), "and the last remaining clip goes too");
6417 assert_eq!(p.clips().len(), 0);
6418 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
6419 assert!(!p.delete(0), "there is nothing left to delete");
6420 assert!(p.undo(), "one gesture, one undo");
6421 assert_eq!(p.clips().len(), 1);
6422 }
6423
6424 /// The offset model's point: one lane loses a clip, the other does not move.
6425 #[test]
6426 fn a_lift_leaves_a_gap_and_moves_nothing() {
6427 let mut p = three();
6428 let video_before = shape(&p)[0].clone();
6429 assert!(p.lift(Lane::A1, 1));
6430 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
6431 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
6432 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
6433 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
6434 assert_eq!(p.map(Lane::A1, 4), None);
6435 assert_eq!(
6436 p.span_at(Lane::A1, 3),
6437 Some(Span {
6438 start: 3,
6439 len: 2,
6440 from: None,
6441 speed: Speed::NORMAL
6442 })
6443 );
6444 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
6445 assert!(p.undo());
6446 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
6447 }
6448
6449 #[test]
6450 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
6451 let mut p = three();
6452 assert!(p.lift(Lane::A1, 2));
6453 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
6454 assert_eq!(
6455 p.span_at(Lane::A1, 5),
6456 Some(Span {
6457 start: 5,
6458 len: 4,
6459 from: None,
6460 speed: Speed::NORMAL
6461 }),
6462 "the audio lane holds silence to the end of the picture"
6463 );
6464 assert_eq!(p.span_at(Lane::A1, 9), None);
6465 // Every lane covers the timeline exactly, gaps included.
6466 for l in p.lanes() {
6467 let spans = p.spans_from(l, 0);
6468 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
6469 assert_eq!(spans[0].start, 0);
6470 }
6471 }
6472
6473 /// The timeline is emptiable: the last placement comes off like any other,
6474 /// the project holds "nothing on any lane" as a state, and one undo per
6475 /// gesture brings it back.
6476 #[test]
6477 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
6478 let mut p = Project::single(FILE, 9);
6479 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
6480 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
6481 assert_eq!(p.timeline_frames(), 0);
6482 assert_eq!(p.composite_span_at(0), None, "nothing to show");
6483 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
6484 assert!(!p.lift(Lane::A1, 0), "index past the end");
6485 assert!(p.undo(), "and the last lift comes back");
6486 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
6487 // A saved-and-loaded empty timeline is a project like any other, and it
6488 // still names the file its frame rate came from.
6489 assert!(p.lift(Lane::V1, 0));
6490 let (sources, lanes, eq, color) = p.without_orphan_sources();
6491 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
6492 let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
6493 assert_eq!(back.timeline_frames(), 0);
6494 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
6495 }
6496
6497 /// What a keyboard selection walks: one answer per lane, gaps included --
6498 /// the composite's own answer is one lane's and cannot say what the audio
6499 /// lane holds under the same playhead.
6500 #[test]
6501 fn lane_clip_at_answers_for_each_lane_separately() {
6502 let mut p = Project::single(FILE, 9);
6503 assert!(p.split(3), "both lanes split");
6504 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
6505 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
6506 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
6507 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
6508 // A gap on one lane leaves the other's clip selectable there.
6509 assert!(p.lift(Lane::A1, 0));
6510 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
6511 assert_eq!(
6512 p.lane_clip_at(Lane::A1, 3),
6513 Some(0),
6514 "indices moved with it"
6515 );
6516 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
6517 // A lane that is not there is not a panic.
6518 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
6519 }
6520
6521 #[test]
6522 fn place_overwrites_only_its_own_lane() {
6523 let mut p = three();
6524 let audio_before = shape(&p)[1].clone();
6525 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
6526 // is trimmed, nothing shifts.
6527 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
6528 assert_eq!(
6529 shape(&p)[0],
6530 vec![
6531 clip(0, 0, 3, 0),
6532 clip(3, 3, 4, 0),
6533 clip(4, 100, 102, 0),
6534 clip(6, 6, 9, 0),
6535 ]
6536 );
6537 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
6538 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
6539
6540 // Placed inside one clip, it splits it in two.
6541 let mut p = Project::single(FILE, 9);
6542 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
6543 assert_eq!(
6544 shape(&p)[0],
6545 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
6546 );
6547 // ...and placed past the end it makes a gap, which is the whole point.
6548 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
6549 assert_eq!(p.timeline_frames(), 22);
6550 assert_eq!(
6551 p.span_at(Lane::V1, 9),
6552 Some(Span {
6553 start: 9,
6554 len: 11,
6555 from: None,
6556 speed: Speed::NORMAL
6557 })
6558 );
6559 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
6560 }
6561
6562 /// A file with sound let go over a further video track: both halves go down,
6563 /// on the same frames, and the audio row is added when the `+ V` button left
6564 /// the project without one. One undo takes the lane and both clips back.
6565 #[test]
6566 fn a_take_placed_on_a_layer_lands_with_its_sound() {
6567 let mut p = three();
6568 let v2 = p.add_lane(LaneKind::Video);
6569 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
6570
6571 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
6572 let a2 = Lane::new(LaneKind::Audio, 1);
6573 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
6574 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
6575 assert_eq!(p.lane(v2)[0].start, 4);
6576 assert_eq!(p.lane(v2)[0].end(), 6);
6577 assert_eq!(
6578 p.lane(v2)[0].link,
6579 p.lane(a2)[0].link,
6580 "one take, not two placements"
6581 );
6582 assert!(p.lane(v2)[0].link.is_some());
6583 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
6584 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
6585
6586 // The pair overwrites its own two lanes and nothing else, exactly as a
6587 // one-lane place does.
6588 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
6589 assert_eq!(p.lane(v2), p.lane(a2));
6590 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
6591 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
6592
6593 assert!(p.undo(), "one step for the second pair");
6594 assert_eq!(p.lane(v2).len(), 1);
6595 assert!(p.undo(), "one step for the first pair *and* its lane");
6596 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
6597 assert!(p.lane(v2).is_empty());
6598
6599 // Refusals cost nothing: sound placed alone is `place`'s door.
6600 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
6601 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
6602 assert!(
6603 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
6604 "a lane that is not there"
6605 );
6606 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
6607 }
6608
6609 /// The drag between tracks: let go at the frames it already covers the clip
6610 /// keeps them, one undo takes it back, and every way it can be refused
6611 /// leaves the project untouched.
6612 #[test]
6613 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
6614 let v2 = Lane::new(LaneKind::Video, 1);
6615 let mut p = three();
6616 assert_eq!(p.add_lane(LaneKind::Video), v2);
6617 let before = shape(&p);
6618
6619 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
6620 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
6621 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
6622 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
6623 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
6624 // One snapshot: a single undo, and the lane list survives it.
6625 assert!(p.undo());
6626 assert_eq!(shape(&p), before);
6627
6628 // A lane that is not there, the lane and frame it is already at, an
6629 // index that is not there, and a move across kinds: all refused,
6630 // nothing changed.
6631 let history = p.history.len();
6632 for (from, idx, to, start) in [
6633 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
6634 (Lane::V1, 1, Lane::V1, 3),
6635 (Lane::V1, 9, v2, 3),
6636 (Lane::V1, 1, Lane::A1, 3),
6637 (Lane::A1, 1, v2, 3),
6638 ] {
6639 assert!(
6640 !p.move_clip(from, idx, to, start),
6641 "{from:?} {idx} -> {to:?} at {start}"
6642 );
6643 }
6644 assert_eq!(shape(&p), before);
6645 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
6646
6647 // Landing on another clip is refused rather than overwriting it: the
6648 // pointer named the lane, never the take already sitting there.
6649 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
6650 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
6651 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
6652 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
6653 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
6654 }
6655
6656 /// The drag *along* a track, which is the one every other editor has: the
6657 /// clip lands on the frame the pointer let it go at, and stops dead against
6658 /// the neighbour rather than overwriting it.
6659 #[test]
6660 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
6661 let sources = vec![Source::new(FILE, 0)];
6662 let lanes = vec![
6663 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
6664 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
6665 ];
6666 let mut p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
6667 let before = shape(&p);
6668
6669 // Into the gap, exactly where it was let go -- nothing else moves.
6670 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
6671 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
6672 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
6673 // Dragged past the clip in front of it: clamped to its wall, laid end
6674 // to end with it, never over it.
6675 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
6676 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
6677 // One undo per drag, and both of them together are the state it started
6678 // in -- the frames each clip plays never changed.
6679 assert!(p.undo() && p.undo());
6680 assert_eq!(shape(&p), before);
6681
6682 // A drop that changes nothing is a click, not an edit.
6683 let history = p.history.len();
6684 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
6685 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
6686 }
6687
6688 /// A drag carries the whole take: the sound half travels exactly as far as
6689 /// the picture does, and the tighter of their two walls stops both.
6690 #[test]
6691 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
6692 let mut p = three();
6693 assert!(
6694 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
6695 "room to the right"
6696 );
6697 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
6698 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
6699 // Something in the sound's way, and nothing at all in the picture's.
6700 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
6701 let before = shape(&p);
6702
6703 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
6704 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
6705 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
6706 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6707 assert!(p.undo());
6708 assert_eq!(shape(&p), before, "one undo for the whole take");
6709 }
6710
6711 /// The drag that does both at once -- another lane *and* another frame --
6712 /// which is what a pointer let go over a lane always names.
6713 #[test]
6714 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
6715 let v2 = Lane::new(LaneKind::Video, 1);
6716 let mut p = three();
6717 assert_eq!(p.add_lane(LaneKind::Video), v2);
6718
6719 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
6720 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
6721 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
6722 assert_eq!(
6723 p.lane(Lane::A1)[2].start,
6724 20,
6725 "its sound travelled the same distance"
6726 );
6727 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6728 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
6729 }
6730
6731 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
6732 /// [`three`] cuts up all nine of its frames.
6733 const SRC: &[u32] = &[9];
6734
6735 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
6736 /// else on the lane moves, and every wall stops the edge rather than
6737 /// refusing the gesture.
6738 #[test]
6739 fn trimming_the_tail_stops_at_every_wall() {
6740 let mut p = three();
6741
6742 // Pulled in: a gap opens behind it and the clip after it stays put.
6743 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
6744 assert_eq!(
6745 shape(&p)[0],
6746 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
6747 );
6748 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
6749 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
6750
6751 // ...and back out, no further than the clip behind it.
6752 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
6753 assert_eq!(
6754 shape(&p)[0][1],
6755 clip(3, 3, 5, 0),
6756 "stopped at the neighbour"
6757 );
6758 assert!(
6759 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
6760 "already at the wall"
6761 );
6762
6763 // One frame of clip always survives, however far back the pointer went.
6764 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
6765 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
6766
6767 // The last clip has no neighbour, so what stops it is the file: nine
6768 // frames is nine frames.
6769 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
6770 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
6771 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
6772 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
6773 // A source nobody told us the length of may not grow at all -- an
6774 // out-point past the end of a file is a save that will not open again.
6775 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
6776 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
6777 }
6778
6779 /// The head pulled in takes the in-point with it -- what stays plays what it
6780 /// always played -- and stops at the source's own first frame.
6781 #[test]
6782 fn trimming_the_head_moves_the_in_point() {
6783 let mut p = three();
6784 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
6785 assert_eq!(
6786 shape(&p)[0][0],
6787 clip(2, 2, 3, 0),
6788 "two frames off the front"
6789 );
6790 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
6791 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
6792 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
6793 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
6794 // One frame survives here too.
6795 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
6796 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
6797
6798 // A clip that does not begin at its source's first frame: its head goes
6799 // back to source frame 0 and not one frame further.
6800 let mut p = Project::single(FILE, 9);
6801 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
6802 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
6803 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
6804 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
6805 }
6806
6807 /// A clip whose in-point is *past* its own start -- what a ripple delete
6808 /// leaves, the piece in front of it gone and this one slid back to frame 0
6809 /// carrying the in-point the cut gave it. Its head has more source behind it
6810 /// than the timeline has room for, and the timeline's own first frame is the
6811 /// wall: asking is not an overflow, and the answer is 0.
6812 #[test]
6813 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
6814 let mut p = Project::single(FILE, 9);
6815 assert!(p.split(5));
6816 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
6817 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
6818
6819 assert_eq!(
6820 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
6821 Some((0, 3)),
6822 "back to frame 0 at most, and one frame of clip always survives"
6823 );
6824 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
6825 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
6826 assert_eq!(
6827 shape(&p)[0],
6828 vec![clip(2, 7, 9, 0)],
6829 "the in-point followed"
6830 );
6831 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
6832 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
6833 }
6834
6835 /// A still is trimmed from its head exactly as it is from its tail: it has
6836 /// no earlier frame to walk an in-point back to, so the wall is the length
6837 /// the caller's table allows it, measured back from the tail. Measured from
6838 /// the in-point -- which a placed picture has at 0 -- its left edge could
6839 /// never be dragged outwards at all.
6840 #[test]
6841 fn a_stills_head_stretches_out_like_its_tail() {
6842 const STILL: &str = "/nonexistent/card.png";
6843 /// What a still is held to, as `PlaybackSession` fills the table in.
6844 const CAP: &[u32] = &[60];
6845
6846 let mut p = Project::single(STILL, 20);
6847 assert!(p.lift(Lane::A1, 0), "a picture is silent");
6848 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
6849 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
6850
6851 // A source with no entry in the table may not grow, here as at the tail.
6852 assert_eq!(
6853 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
6854 Some((100, 119)),
6855 "a length nobody told us buys no head room"
6856 );
6857 assert_eq!(
6858 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
6859 Some((60, 119)),
6860 "back to a whole cap's worth, one frame of clip surviving"
6861 );
6862 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
6863 assert_eq!(
6864 shape(&p)[0][0],
6865 clip(80, 0, 40, 0),
6866 "twenty frames longer, and still read from the source's first frame"
6867 );
6868 // Past the cap is clamped, exactly as the tail is -- not refused.
6869 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
6870 assert_eq!(
6871 shape(&p)[0][0],
6872 clip(60, 0, 60, 0),
6873 "a cap's worth, no more"
6874 );
6875 // ...and the clip in front is the nearer wall of the two: no head trim
6876 // may open an overlap.
6877 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
6878 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
6879 assert_eq!(
6880 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
6881 Some((85, 119)),
6882 "up to the neighbour's last frame and not over it"
6883 );
6884 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
6885 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
6886 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
6887 }
6888
6889 /// Linked halves trim as one: a link is one span on however many lanes, so
6890 /// the sound follows the picture's edge -- and the tightest wall of the two
6891 /// is what stops both.
6892 #[test]
6893 fn linked_halves_trim_together() {
6894 let mut p = three();
6895 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
6896 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
6897
6898 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
6899 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
6900 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
6901 assert!(
6902 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
6903 "either half drags it"
6904 );
6905 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
6906 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6907
6908 // Something in the way on the *audio* lane stops the picture's tail as
6909 // well: the group can only go as far as its tightest member.
6910 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
6911 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
6912 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
6913 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
6914 links_are_consistent(&p.lanes).expect("still one span");
6915 }
6916
6917 /// A whole drag is one undo step -- the front-end commits once, at the
6918 /// release -- and an edge asked to stay where it is costs none at all.
6919 #[test]
6920 fn a_trim_is_one_undo_step() {
6921 let mut p = three();
6922 let before = shape(&p);
6923 let history = p.history.len();
6924
6925 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
6926 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
6927 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
6928 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
6929 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
6930 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
6931
6932 assert!(p.undo());
6933 assert_eq!(shape(&p), before, "both halves back, in one step");
6934 }
6935
6936 /// A moved half stays in its group: a link names a span, not a lane, so the
6937 /// picture on `V2` is still the same take as the sound under it on `A1`.
6938 #[test]
6939 fn move_clip_keeps_the_group() {
6940 let v2 = Lane::new(LaneKind::Video, 1);
6941 let mut p = three();
6942 p.add_lane(LaneKind::Video);
6943 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
6944 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
6945 assert!(p.move_clip(Lane::V1, 1, v2, 3));
6946 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
6947 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6948 assert_eq!(
6949 p.lane(v2)[0].start,
6950 p.lane(Lane::A1)[1].start,
6951 "and still covers the same span as its sound"
6952 );
6953 }
6954
6955 #[test]
6956 fn ripple_delete_spans_partial_clips() {
6957 let mut p = three();
6958 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
6959 assert!(p.ripple_delete(2, 4));
6960 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
6961 assert_eq!(shape(&p)[1], shape(&p)[0]);
6962 assert_eq!(p.timeline_frames(), 5);
6963 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
6964 assert!(p.undo());
6965 assert_eq!(shape(&p), shape(&three()));
6966 // One that takes everything is a delete like any other: the timeline
6967 // empties, and the undo it cost brings it back whole.
6968 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
6969 assert_eq!(p.timeline_frames(), 0);
6970 assert!(
6971 !p.ripple_delete(0, 100),
6972 "and a delete with nothing left to take is not an undo step"
6973 );
6974 assert!(p.undo());
6975 assert_eq!(shape(&p), shape(&three()));
6976 }
6977
6978 #[test]
6979 fn undo_restores_exactly() {
6980 let mut p = three();
6981 let after_splits = shape(&p);
6982 assert!(p.delete(1));
6983 assert!(p.undo());
6984 assert_eq!(shape(&p), after_splits);
6985
6986 // walk all the way back through both splits, then run dry
6987 assert!(p.undo());
6988 assert_eq!(p.clips().len(), 2);
6989 assert!(p.undo());
6990 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
6991 assert!(!p.undo(), "empty history");
6992 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
6993 }
6994
6995 #[test]
6996 fn redo_restores_exactly() {
6997 let mut p = three();
6998 assert!(p.delete(1));
6999 let after_delete = p.parts();
7000 assert!(p.undo());
7001 assert!(p.redo());
7002 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
7003 assert!(!p.redo(), "empty redo stack");
7004 }
7005
7006 #[test]
7007 fn edit_after_undo_empties_redo() {
7008 let mut p = three();
7009 assert!(p.delete(1));
7010 assert!(p.undo());
7011 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
7012 assert!(p.split(1), "a fresh edit");
7013 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
7014 assert!(!p.redo(), "so redo has nothing left");
7015 }
7016
7017 #[test]
7018 fn redo_on_empty_stack_is_false() {
7019 let mut p = three();
7020 assert!(!p.redo(), "nothing has been undone yet");
7021 }
7022
7023 /// Past the cap the *oldest* step goes, so a long session undoes exactly
7024 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
7025 #[test]
7026 fn history_stops_at_the_cap() {
7027 let mut p = Project::single(FILE, 400);
7028 for frame in 1..=150 {
7029 assert!(p.split(frame), "split {frame} is an edit");
7030 }
7031 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
7032 for step in 0..HISTORY_CAP {
7033 assert!(p.undo(), "undo {step} is inside the cap");
7034 }
7035 assert!(!p.undo(), "and the 101st has nothing left to take");
7036 // 100 undos off 150 splits is the timeline after the 50th: the older
7037 // steps were dropped, not the newer ones.
7038 assert_eq!(p.clips().len(), 51);
7039 }
7040
7041 /// Undo/redo by hand across a split must never merge two takes into one
7042 /// group by reusing an id.
7043 #[test]
7044 fn group_ids_are_never_reused() {
7045 let mut p = Project::single(FILE, 9);
7046 assert!(p.split(3));
7047 let first = p.clips()[1].link;
7048 assert!(p.undo());
7049 assert!(p.split(5));
7050 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
7051 }
7052
7053 #[test]
7054 fn segments_from_reads_the_audio_lane() {
7055 let p = three();
7056 // mid-clip: partial first segment, whole clips after it
7057 assert_eq!(
7058 p.segments_from(4, FPS),
7059 vec![
7060 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7061 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7062 ]
7063 );
7064 // on a boundary: nothing partial
7065 assert_eq!(
7066 p.segments_from(3, FPS),
7067 vec![
7068 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
7069 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7070 ]
7071 );
7072 // from the top: one entry per clip
7073 assert_eq!(p.segments_from(0, FPS).len(), 3);
7074 // last clip only
7075 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
7076 // past the end / unusable fps
7077 assert!(p.segments_from(9, FPS).is_empty());
7078 assert!(p.segments_from(0, 0.0).is_empty());
7079 assert!(p.segments_from(0, f64::NAN).is_empty());
7080 }
7081
7082 #[test]
7083 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
7084 let mut p = three();
7085 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
7086 assert_eq!(
7087 p.segments_from(0, FPS),
7088 vec![
7089 (Some(0), 0.0, 3.0 / 30.0),
7090 (None, 0.0, 2.0 / 30.0),
7091 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7092 ]
7093 );
7094 // The list still covers exactly the timeline: that is what stops the
7095 // master clock stalling at the hole.
7096 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7097 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
7098 // Starting inside the gap trims the silence, not the clip after it.
7099 assert_eq!(
7100 p.segments_from(4, FPS),
7101 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
7102 );
7103 // ...and a lane that is nothing but gap is a run of silence.
7104 assert!(p.lift(Lane::A1, 0));
7105 assert!(p.lift(Lane::A1, 0));
7106 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
7107 }
7108
7109 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
7110 /// of source 0 then [0,4) of source 1.
7111 fn two_sources() -> Project {
7112 let mut p = three();
7113 let s = p.import(FILE2, 0);
7114 assert_eq!(s, 1);
7115 assert!(p.append_clip(s, 4));
7116 p
7117 }
7118
7119 #[test]
7120 fn import_dedups_and_appends() {
7121 let mut p = Project::single(FILE, 9);
7122 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
7123 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
7124 assert_eq!(p.import(FILE2, 0), 1);
7125 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
7126 // ...but the same file on another audio stream is another source: it is
7127 // what a clip names, and a clip plays exactly one stream.
7128 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
7129 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
7130 assert_eq!(p.sources()[2].audio_stream, 1);
7131 assert!(p.append_clip(2, 4), "a stream entry is placeable");
7132 assert!(p.undo());
7133 assert_eq!(p.sources().len(), 3);
7134 assert!(!p.append_clip(3, 5), "unknown source index");
7135 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
7136
7137 // Two spellings of one real file are one source: this is the case the
7138 // raw-path comparison above would get wrong.
7139 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
7140 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
7141 let mut p = Project::single(here, 9);
7142 assert_eq!(p.import(detour, 0), 0);
7143 assert_eq!(p.sources().len(), 1);
7144 }
7145
7146 #[test]
7147 fn append_clip_is_one_undo_step() {
7148 let mut p = two_sources();
7149 assert_eq!(p.timeline_frames(), 13);
7150 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
7151 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
7152 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
7153 assert!(p.undo());
7154 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
7155 assert_eq!(
7156 p.sources().len(),
7157 2,
7158 "the orphan source entry stays -- indexes are forever"
7159 );
7160 // ...and it is still usable, so a redo-by-hand costs no reimport.
7161 assert!(p.append_clip(1, 0));
7162 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
7163 }
7164
7165 #[test]
7166 fn edits_carry_the_source_along() {
7167 let mut p = two_sources();
7168 // A split inside the second source splits into two source-1 clips.
7169 assert!(p.split(11));
7170 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
7171 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
7172
7173 // A source-1 clip pasted into source-0 territory keeps its file, and so
7174 // does the source-0 half that got split off around it.
7175 let copied = p.clips()[4];
7176 assert!(p.paste(1, copied));
7177 assert_eq!(p.clips()[1].source, 1);
7178 assert_eq!(p.clips()[1].in_frame, 2);
7179 assert_eq!(p.clips()[2].source, 0);
7180 assert!(p.undo());
7181 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
7182 }
7183
7184 #[test]
7185 fn segments_from_names_the_source() {
7186 let p = two_sources();
7187 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
7188 assert_eq!(
7189 p.segments_from(4, FPS),
7190 vec![
7191 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7192 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7193 (Some(1), 0.0, 4.0 / 30.0),
7194 ]
7195 );
7196 // Mid-clip in source 1: only that source is left.
7197 assert_eq!(
7198 p.segments_from(10, FPS),
7199 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
7200 );
7201 assert!(p.segments_from(13, FPS).is_empty());
7202 // Segments still cover exactly the timeline across the join.
7203 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7204 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
7205 }
7206
7207 #[test]
7208 fn segments_follow_deletes_and_fps() {
7209 let mut p = three();
7210 assert!(p.delete(0));
7211 // source seconds, not timeline: deleting the head does not shift them
7212 let segs = p.segments_from(0, 25.0);
7213 assert_eq!(
7214 segs,
7215 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
7216 );
7217 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
7218 assert!(
7219 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
7220 "segments must cover exactly the timeline: {played}"
7221 );
7222 }
7223
7224 #[test]
7225 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
7226 // Import a second file, undo it: source 1 is now an orphan.
7227 let mut p = two_sources();
7228 assert!(p.undo());
7229 let (sources, lanes, eq, color) = p.without_orphan_sources();
7230 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
7231 assert!(eq.is_empty(), "and a project with no equalizer writes none");
7232 assert!(color.is_empty(), "nor a colour it never graded with");
7233 assert_eq!(
7234 lanes,
7235 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
7236 "the clips are untouched"
7237 );
7238
7239 // Three sources where only the middle one is orphaned: the survivors
7240 // renumber, and the clips follow.
7241 let mut p = Project::single(FILE, 9);
7242 assert_eq!(p.import(FILE2, 0), 1);
7243 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
7244 assert!(p.append_clip(2, 4));
7245 let (sources, lanes, eq, color) = p.without_orphan_sources();
7246 assert_eq!(
7247 sources,
7248 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
7249 );
7250 assert_eq!(
7251 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
7252 [0, 1]
7253 );
7254 // ...and what comes out is loadable, with the same timeline.
7255 let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts");
7256 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
7257 assert_eq!(reloaded.sources().len(), 2);
7258 }
7259
7260 /// Taking a file out of the library: refused by name -- lanes and counts --
7261 /// while a clip still plays from it, and once nothing does, the entry goes
7262 /// and every clip that indexed past it is renumbered onto the short list.
7263 #[test]
7264 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
7265 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
7266 // plus a second stream of FILE as source 2 with a take of its own.
7267 let mut p = two_sources();
7268 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
7269 assert!(p.append_clip(2, 4));
7270
7271 let refusal = p
7272 .remove_source(1)
7273 .expect_err("a source with clips on it cannot go")
7274 .to_string();
7275 assert!(refusal.contains(FILE2), "names the file: {refusal}");
7276 assert!(
7277 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
7278 "names the lanes holding it: {refusal}"
7279 );
7280 assert!(refusal.contains("still plays"), "{refusal}");
7281 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
7282 assert_eq!(shape(&p)[0][3].source, 1);
7283
7284 // Delete FILE2's take -- the whole span, on every lane -- and the entry
7285 // is free to go. Source 2's clips become source 1's.
7286 assert!(p.delete_in(Lane::V1, 3));
7287 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
7288 p.remove_source(1).expect("nothing plays FILE2 any more");
7289 assert_eq!(
7290 p.sources(),
7291 [Source::new(FILE, 0), Source::new(FILE, 1)],
7292 "the middle entry is gone"
7293 );
7294 assert_eq!(
7295 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
7296 [0, 0, 0, 1],
7297 "the clips past it renumbered"
7298 );
7299 assert_eq!(
7300 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
7301 [0, 0, 0, 1],
7302 "on every lane"
7303 );
7304 // What is left is a project that still loads, which is the whole point
7305 // of renumbering rather than leaving a hole.
7306 let (sources, lanes, eq, color) = p.without_orphan_sources();
7307 Project::from_parts(sources, lanes, eq, color).expect("from_parts");
7308 }
7309
7310 /// The two edges of a removal: it retires the undo stack (the corner-cut on
7311 /// [`Project::remove_source`]), and the last entry goes like any other
7312 /// once nothing plays it -- a project may name no file at all.
7313 #[test]
7314 fn remove_source_retires_undo_and_empties_the_library() {
7315 let mut p = two_sources();
7316 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
7317 assert!(!p.history.is_empty(), "there is something to undo");
7318 p.remove_source(1).expect("nothing plays FILE2");
7319 assert!(
7320 p.history.is_empty(),
7321 "a snapshot naming the removed source must not survive it"
7322 );
7323 assert!(!p.undo(), "and so there is nothing left to undo");
7324
7325 // The last file standing is held to the one rule every row is -- what
7326 // plays cannot go -- and to no other.
7327 assert_eq!(p.sources().len(), 1);
7328 let refusal = p
7329 .remove_source(0)
7330 .expect_err("its clips are still on the lanes")
7331 .to_string();
7332 assert!(refusal.contains("still plays"), "{refusal}");
7333 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
7334 while p.delete_in(Lane::V1, 0) {}
7335 p.remove_source(0)
7336 .expect("the last row goes like any other");
7337 assert!(
7338 p.sources().is_empty(),
7339 "a project may name no file at all: an empty library over an empty timeline"
7340 );
7341 assert_eq!(p.timeline_frames(), 0);
7342 assert!(
7343 p.remove_source(0).is_err(),
7344 "and an index that is not there is refused, not panicked on"
7345 );
7346 }
7347
7348 /// A clip's equalizer is the clip's: it survives every edit that copies a
7349 /// placement, and it comes back with an undo.
7350 #[test]
7351 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
7352 let mut p = three();
7353 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
7354 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
7355 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7356 assert!(
7357 p.eq_of(Lane::V1, 0).is_none(),
7358 "one clip, not the lane above"
7359 );
7360
7361 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
7362 assert!(p.split(1));
7363 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7364 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
7365 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
7366
7367 // A clipboard copy carries it -- onto another lane, at that.
7368 let copied = p.lane(Lane::A1)[1];
7369 assert!(p.place(Lane::V1, 20, copied));
7370 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
7371 assert!(p.undo());
7372 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
7373
7374 // ...and a change to one is one undo step, in both directions.
7375 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
7376 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
7377 assert!(p.undo());
7378 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7379 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
7380 assert!(p.eq_of(Lane::A1, 0).is_none());
7381 assert!(p.undo());
7382 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7383
7384 // Two refusals, neither of which costs an undo step.
7385 let mut nan = band_at(1);
7386 nan.bands[0].q = f32::INFINITY;
7387 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
7388 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
7389 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7390 assert!(p.undo());
7391 assert_eq!(
7392 p.lane(Lane::A1).len(),
7393 3,
7394 "one step back is before the split"
7395 );
7396 assert!(p.undo());
7397 assert!(
7398 p.eq_of(Lane::A1, 0).is_none(),
7399 "and the next is before the setting: the refusals pushed none"
7400 );
7401 }
7402
7403 /// The table is append-only within a session, exactly as the sources are, so
7404 /// an undone setting is still in it -- and a save is where it goes.
7405 #[test]
7406 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
7407 let mut p = three();
7408 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
7409 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
7410 assert!(p.undo(), "back to the first setting");
7411 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
7412
7413 let (_, lanes, eq, _) = p.without_orphan_sources();
7414 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
7415 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
7416 assert_eq!(lanes[0].1[1].eq, None);
7417
7418 // One curve on three clips is one entry: settings that are equal share.
7419 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
7420 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
7421 let (_, lanes, eq, _) = p.without_orphan_sources();
7422 assert_eq!(eq.len(), 1, "equal settings share their entry");
7423 assert_eq!(lanes[1].1[2].eq, Some(0));
7424 reloads(&p, "an equalizer that outlived an undo");
7425 }
7426
7427 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
7428 /// grade is the clip's, through every edit that copies a placement.
7429 #[test]
7430 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
7431 let mut p = three();
7432 assert!(
7433 p.color_of(Lane::V1, 0).is_none(),
7434 "a fresh clip is ungraded"
7435 );
7436 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7437 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7438 assert!(
7439 p.color_of(Lane::A1, 0).is_none(),
7440 "one clip, not the lane below"
7441 );
7442 assert!(
7443 p.eq_of(Lane::V1, 0).is_none(),
7444 "and a grade is not an equalizer"
7445 );
7446
7447 // Cutting a graded clip must not grade half of it: both halves inherit.
7448 assert!(p.split(1));
7449 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7450 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
7451 assert!(
7452 p.color_of(Lane::V1, 2).is_none(),
7453 "the clip after it is ungraded"
7454 );
7455
7456 // A clipboard copy carries it -- onto another lane, at that.
7457 let copied = p.lane(Lane::V1)[1];
7458 assert!(p.place(Lane::A1, 20, copied));
7459 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
7460 assert!(p.undo());
7461 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
7462
7463 // ...and a change to one is one undo step, in both directions.
7464 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
7465 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
7466 assert!(p.undo());
7467 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7468 assert!(
7469 p.set_color(Lane::V1, 0, None),
7470 "and taking it off is an edit"
7471 );
7472 assert!(p.color_of(Lane::V1, 0).is_none());
7473 assert!(p.undo());
7474 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7475
7476 // Two refusals, neither of which costs an undo step.
7477 let nan = ColorParams {
7478 contrast: f32::NAN,
7479 ..grade_at(1)
7480 };
7481 assert!(
7482 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
7483 "no clip there"
7484 );
7485 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
7486 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7487 assert!(p.undo());
7488 assert_eq!(
7489 p.lane(Lane::V1).len(),
7490 3,
7491 "one step back is before the split"
7492 );
7493 assert!(p.undo());
7494 assert!(
7495 p.color_of(Lane::V1, 0).is_none(),
7496 "and the next is before the grade: the refusals pushed none"
7497 );
7498 }
7499
7500 /// A slider drag is one gesture: the press snapshots, every sample after it
7501 /// only regrades, and the single undo lands on what the clip was *before*
7502 /// the hand touched it -- not one step back down the drag.
7503 #[test]
7504 fn a_whole_colour_drag_undoes_in_one_step() {
7505 let mut p = three();
7506 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
7507 for n in 2..=8 {
7508 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
7509 }
7510 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
7511 assert!(p.undo());
7512 assert!(
7513 p.color_of(Lane::V1, 0).is_none(),
7514 "one undo is the whole gesture, back to ungraded"
7515 );
7516
7517 // The live write refuses what the snapshotting one refuses, and a
7518 // refusal still costs no history either way.
7519 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
7520 assert!(!p.set_color_live(
7521 Lane::V1,
7522 0,
7523 Some(ColorParams {
7524 contrast: f32::NAN,
7525 ..grade_at(1)
7526 })
7527 ));
7528 assert!(p.undo());
7529 assert_eq!(
7530 p.lane(Lane::V1).len(),
7531 2,
7532 "the next step back is the split before the drag: no sample pushed one"
7533 );
7534 }
7535
7536 /// The colour table is append-only within a session, exactly as the eq one
7537 /// is -- and a save is where an undone grade goes.
7538 #[test]
7539 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
7540 let mut p = three();
7541 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
7542 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7543 assert!(p.undo(), "back to the first grade");
7544 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
7545
7546 let (_, lanes, _, color) = p.without_orphan_sources();
7547 assert_eq!(
7548 color,
7549 vec![grade_at(1)],
7550 "what nothing plays is not written"
7551 );
7552 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
7553 assert_eq!(lanes[0].1[1].color, None);
7554
7555 // One grade on three clips is one entry: settings that are equal share.
7556 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
7557 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
7558 let (_, lanes, _, color) = p.without_orphan_sources();
7559 assert_eq!(color.len(), 1, "equal grades share their entry");
7560 assert_eq!(lanes[1].1[2].color, Some(0));
7561 reloads(&p, "a colour that outlived an undo");
7562
7563 // An equalizer and a grade on one clip are two independent tables.
7564 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
7565 let (_, lanes, eq, color) = p.without_orphan_sources();
7566 assert_eq!((eq.len(), color.len()), (1, 1));
7567 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
7568 }
7569
7570 /// Not a claim about correctness but about cost: a clip is copied on every
7571 /// paste, every undo snapshot and every lane clone, so its size is worth
7572 /// knowing. The eq index fit the padding a `Copy` clip already had; the
7573 /// colour one did not, and the struct grew a word.
7574 #[test]
7575 fn a_clip_is_still_a_small_copy() {
7576 assert_eq!(
7577 std::mem::size_of::<Clip>(),
7578 40,
7579 "Clip changed size -- 32 before the colour index, 40 after"
7580 );
7581 }
7582
7583 #[test]
7584 fn from_parts_has_no_history_and_checks_the_invariants() {
7585 let (sources, lanes, eq, color) = three().without_orphan_sources();
7586 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
7587 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone())
7588 .expect("valid parts");
7589 assert_eq!(p.clips(), three().clips());
7590 assert!(!p.undo(), "a loaded project has nothing to undo");
7591 assert!(p.split(4), "...and is editable from there");
7592 assert!(p.undo());
7593
7594 // A lane may be empty, and so may every lane -- an emptied timeline is a
7595 // project. No lane at all is not one: there would be nothing to place on.
7596 assert!(
7597 Project::from_parts(
7598 sources.clone(),
7599 two(video.clone(), Vec::new()),
7600 Vec::new(),
7601 Vec::new(),
7602 )
7603 .is_ok()
7604 );
7605 assert!(
7606 Project::from_parts(
7607 sources.clone(),
7608 two(Vec::new(), Vec::new()),
7609 Vec::new(),
7610 Vec::new(),
7611 )
7612 .is_ok()
7613 );
7614 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
7615 let bad: [Vec<Clip>; 5] = [
7616 vec![clip(0, 0, 3, 1)], // source that is not there
7617 vec![clip(0, 3, 3, 0)], // empty clip
7618 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
7619 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
7620 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
7621 ];
7622 for clips in bad {
7623 assert!(
7624 Project::from_parts(
7625 sources.clone(),
7626 two(clips.clone(), Vec::new()),
7627 Vec::new(),
7628 Vec::new(),
7629 )
7630 .is_err(),
7631 "{clips:?}"
7632 );
7633 assert!(
7634 Project::from_parts(
7635 sources.clone(),
7636 two(video.clone(), clips.clone()),
7637 Vec::new(),
7638 Vec::new(),
7639 )
7640 .is_err()
7641 );
7642 // ...and on a third lane, which is checked by the same walk.
7643 assert!(
7644 Project::from_parts(
7645 sources.clone(),
7646 vec![
7647 (LaneKind::Video, video.clone()),
7648 (LaneKind::Audio, audio.clone()),
7649 (LaneKind::Video, clips),
7650 ],
7651 Vec::new(),
7652 Vec::new(),
7653 )
7654 .is_err()
7655 );
7656 }
7657 // An equalizer index no table entry answers, and a table entry the file
7658 // format could not have written, are refused at this door too.
7659 let eqd = |i: u16| {
7660 vec![Clip {
7661 eq: Some(i),
7662 ..video[0]
7663 }]
7664 };
7665 assert!(
7666 Project::from_parts(
7667 sources.clone(),
7668 two(eqd(0), Vec::new()),
7669 Vec::new(),
7670 Vec::new(),
7671 )
7672 .is_err()
7673 );
7674 let mut nan = band_at(1);
7675 nan.bands[0].freq_hz = f32::NAN;
7676 assert!(
7677 Project::from_parts(
7678 sources.clone(),
7679 two(eqd(0), Vec::new()),
7680 vec![nan],
7681 Vec::new(),
7682 )
7683 .is_err()
7684 );
7685 let loaded = Project::from_parts(
7686 sources.clone(),
7687 two(eqd(0), Vec::new()),
7688 vec![band_at(1)],
7689 Vec::new(),
7690 )
7691 .expect("an eq the table holds");
7692 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
7693
7694 // The same two refusals for a colour, at the same door.
7695 let graded = |i: u16| {
7696 vec![Clip {
7697 color: Some(i),
7698 fit: FitPolicy::default(),
7699 speed: Speed::NORMAL,
7700 ..video[0]
7701 }]
7702 };
7703 assert!(
7704 Project::from_parts(
7705 sources.clone(),
7706 two(graded(0), Vec::new()),
7707 Vec::new(),
7708 Vec::new(),
7709 )
7710 .is_err(),
7711 "a colour index no entry answers"
7712 );
7713 assert!(
7714 Project::from_parts(
7715 sources.clone(),
7716 two(graded(0), Vec::new()),
7717 Vec::new(),
7718 vec![ColorParams {
7719 tint: f32::NAN,
7720 ..grade_at(1)
7721 }],
7722 )
7723 .is_err(),
7724 "a value the file format could not have written"
7725 );
7726 let loaded = Project::from_parts(
7727 sources.clone(),
7728 two(graded(0), Vec::new()),
7729 Vec::new(),
7730 vec![grade_at(1)],
7731 )
7732 .expect("a colour the table holds");
7733 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
7734
7735 // Group ids survive a load, and the next split gets a fresh one.
7736 let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts");
7737 assert!(p.split(4));
7738 assert!(p.clips().iter().all(|c| c.link.is_some()));
7739 }
7740
7741 /// The grouping rules, at the untrusted door and after every edit that can
7742 /// touch a link. A link id is at most one placement per lane -- a clip or a
7743 /// caption, whichever carries it -- and no sequence of edits may produce
7744 /// otherwise, because what an edit produces is what a save writes and a load
7745 /// reads.
7746 ///
7747 /// Amended for the offset-preserving group: the members keep their own
7748 /// spans, so two placements of one id covering different frames is *legal*
7749 /// -- it is what a hand-built group is -- and the only refusal left is the
7750 /// doubled id inside one lane.
7751 #[test]
7752 fn a_link_id_is_never_two_clips_of_one_lane() {
7753 let sources = vec![Source::new(FILE, 0)];
7754 let linked = |start, in_frame, out_frame, link| Clip {
7755 start,
7756 in_frame,
7757 out_frame,
7758 source: 0,
7759 link: Some(link),
7760 eq: None,
7761 color: None,
7762 fit: FitPolicy::default(),
7763 speed: Speed::NORMAL,
7764 };
7765
7766 // The door: a doubled id inside one lane, refused by name.
7767 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
7768 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
7769 .expect_err("refused")
7770 .to_string()
7771 };
7772 assert!(
7773 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
7774 .contains("link 7 names two clips in the V1 lane"),
7775 "a duplicate id inside one lane is refused by name"
7776 );
7777 // ...and the same doubling on a subtitle lane, in its own words: a
7778 // caption is the other placement an id may name.
7779 let caption = |start: u32, frames: u32, link| SubClip {
7780 start,
7781 frames,
7782 track: 0,
7783 in_us: 0,
7784 out_us: i64::from(frames) * 1_000_000,
7785 link: Some(link),
7786 };
7787 let subs = LaneData {
7788 clips: Vec::new(),
7789 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
7790 ..LaneData::new(LaneKind::Subtitle, Vec::new())
7791 };
7792 assert_eq!(
7793 links_are_consistent(&[subs]).unwrap_err().to_string(),
7794 "link 7 names two captions in the S1 lane"
7795 );
7796 // A pair covering *different* frames is legal now: the members of a
7797 // hand-built group keep their own spans, and what binds them is the id.
7798 let apart = Project::from_parts(
7799 sources.clone(),
7800 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
7801 Vec::new(),
7802 Vec::new(),
7803 );
7804 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
7805 // A one-sided link is *not* an error: it is what a lift leaves behind.
7806 let mut p = Project::single(FILE, 9);
7807 assert!(p.lift(Lane::A1, 0));
7808 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
7809 assert!(
7810 Project::from_parts(sources, lanes, eq, color).is_ok(),
7811 "a lifted lane's project has to load again"
7812 );
7813
7814 // The edits: nothing below may break either rule.
7815 let consistent = |p: &Project, what: &str| {
7816 assert!(
7817 links_are_consistent(&p.lanes).is_ok(),
7818 "{what}: {:?}",
7819 p.lanes
7820 );
7821 };
7822 let mut p = three();
7823 let copied = p.clips()[0];
7824 assert!(
7825 copied.link.is_some(),
7826 "the clipboard clip carries its group"
7827 );
7828 assert!(p.lift(Lane::V1, 0));
7829 assert!(p.place(Lane::V1, 0, copied));
7830 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
7831 assert_eq!(
7832 p.clips().iter().filter(|c| c.link == copied.link).count(),
7833 0,
7834 "a placement belongs to no group, so it cannot duplicate one"
7835 );
7836 consistent(&p, "lift + place twice");
7837 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
7838 consistent(&p, "place through a grouped clip");
7839 assert!(p.paste(6, copied), "a rippling paste through another");
7840 consistent(&p, "paste");
7841 assert!(p.split(2));
7842 consistent(&p, "split");
7843 assert!(p.ripple_delete(1, 3));
7844 consistent(&p, "ripple_delete");
7845 assert!(p.undo());
7846 consistent(&p, "undo");
7847 }
7848
7849 /// What an edit produces is what a save writes, so *every* state the public
7850 /// API can reach has to load again. The two the verifier panel found where
7851 /// it did not: a split and a regroup handed one group id to two clips that
7852 /// were not the same span, because the lanes had been edited apart.
7853 #[test]
7854 fn every_reachable_state_reloads() {
7855 let mut p = Project::single(FILE, 150);
7856 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
7857 assert!(p.split(10), "the lanes are cut apart at 10");
7858 reloads(&p, "place on one lane, then split");
7859
7860 let mut p = Project::single(FILE, 150);
7861 assert!(p.split(30));
7862 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
7863 assert!(p.regroup(30), "only the audio lane can rejoin");
7864 assert!(p.split(60));
7865 reloads(&p, "lift, regroup one lane, split");
7866
7867 // Two audio streams of one file, both placed: two source entries with
7868 // one path between them, which is the state a stream picked out of the
7869 // library reaches -- and the state a save has to write and read back.
7870 let mut p = Project::single(FILE, 150);
7871 let second = p.import(FILE, 1);
7872 assert_eq!(second, 1, "the same file on another stream is a new source");
7873 assert!(p.append_clip(second, 150));
7874 assert!(p.split(200));
7875 reloads(
7876 &p,
7877 "a second audio stream of the same file, placed and split",
7878 );
7879 let (sources, ..) = p.without_orphan_sources();
7880 assert_eq!(
7881 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
7882 [0, 1],
7883 "both entries survive the orphan prune: both are played"
7884 );
7885 }
7886
7887 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
7888 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
7889 /// is the stamp playback puts on a decoded source frame -- and the *last*
7890 /// source frame the pump is still holding at a timeline frame has to be
7891 /// exactly the one the export encoded there, at every rate. Anything else is
7892 /// A/V drift that grows with the clip, and no test of either side alone
7893 /// would see it.
7894 ///
7895 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
7896 /// is a better answer than the floor/floor this had: floor/floor put the
7897 /// preview a whole held frame off the export at slow rates.)
7898 #[test]
7899 fn speed_maps_both_ways() {
7900 for permille in (250..=4000).step_by(1) {
7901 let speed = Speed::from_permille(permille);
7902 assert_eq!(speed.permille(), permille, "no clamping in range");
7903 for d in 0..200u32 {
7904 let want = speed.source_at(d);
7905 // What the pump shows at `d` is the last frame whose stamp has
7906 // come due -- and it is `want`, the frame the export encodes
7907 // there. Slowed, that is the frame it is still holding; sped up,
7908 // it is the newest of the several that arrived.
7909 let held = (0..=want + 8)
7910 .filter(|&s| speed.timeline_at(s) <= d)
7911 .next_back();
7912 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
7913 }
7914 for n in 1..300u32 {
7915 // A footprint is never zero: a clip occupying no timeline frame
7916 // is a placement the lane invariants cannot hold.
7917 let frames = speed.frames(n);
7918 assert!(frames >= 1, "{speed} of {n} frames");
7919 // ...and its last timeline frame never reads past the clip.
7920 assert!(
7921 speed.source_at(frames - 1) < n,
7922 "{speed}: the last timeline frame of {n} reads past the clip"
7923 );
7924 // The trim inverse never overshoots the room it was given, and
7925 // answers for every room a footprint can be.
7926 let fit = speed.fit(frames).expect("a clip fits its own footprint");
7927 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
7928 // A room narrower than one source frame's own footprint holds
7929 // nothing, and says so rather than rounding something into it.
7930 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
7931 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
7932 }
7933 }
7934 // Real time is the identity map, byte for byte.
7935 for d in 0..1000 {
7936 assert_eq!(Speed::NORMAL.source_at(d), d);
7937 assert_eq!(Speed::NORMAL.timeline_at(d), d);
7938 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
7939 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
7940 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
7941 }
7942 // The one door: no zero, no reverse, nothing past the ends.
7943 assert_eq!(Speed::from_permille(0), Speed::MIN);
7944 assert_eq!(Speed::from_permille(249), Speed::MIN);
7945 assert_eq!(Speed::from_permille(4001), Speed::MAX);
7946 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
7947 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
7948 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
7949 }
7950
7951 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
7952 /// export encodes at a timeline frame is the one playback is holding there,
7953 /// a file is as long in timeline frames as the seconds it lasts, and the two
7954 /// compose so a speeded clip at another rate is exactly both.
7955 #[test]
7956 fn rate_composes_with_speed() {
7957 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
7958 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
7959 // the identity map or a single-rate project would move.
7960 for (source_fps, timeline_fps) in [
7961 (24000. / 1001., 30.),
7962 (30., 24000. / 1001.),
7963 (60., 30.),
7964 (25., 30.),
7965 (30., 30.),
7966 ] {
7967 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
7968 for n in 0..2000u32 {
7969 let source = rate.source_at(n);
7970 // The stamp is the *first* timeline-rate frame that shows it, so
7971 // the picture on screen at `n` is the picture encoded at `n`.
7972 let held = (0..=source + 4)
7973 .filter(|&s| rate.timeline_at(s) <= n)
7974 .next_back();
7975 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
7976 }
7977 // A file of `count` frames is `timeline_at(count)` frames long here,
7978 // and its last one still reads a frame the file has.
7979 for count in 1..500u32 {
7980 let frames = rate.timeline_at(count);
7981 assert!(frames >= 1, "a file is never zero frames long");
7982 assert!(
7983 rate.source_at(frames - 1) < count,
7984 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
7985 );
7986 }
7987 // No drift: the mapping is one exact division of the *rate itself*,
7988 // not an accumulation and not a rounded rate, so an hour in is as
7989 // true as the first second. (Held to the real ratio of the two rates
7990 // the caller asked for -- `as_f64` would be true of a wrong rate.)
7991 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
7992 let want = f64::from(n) * source_fps / timeline_fps;
7993 assert!(
7994 (f64::from(rate.source_at(n)) - want).abs() < 1.,
7995 "{source_fps} on {timeline_fps}: frame {n} drifted"
7996 );
7997 }
7998 }
7999 // The timeline's own rate is the identity, whichever way it is written.
8000 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
8001 assert!(
8002 Rate::from_fps(30.0004, 30.)
8003 .expect("30.0004 over 30")
8004 .is_real_time(),
8005 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
8006 );
8007 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
8008 // one thing `matches_timeline` refuses a file for now that the rate gate
8009 // is gone.
8010 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
8011 assert!(Rate::from_fps(30., f64::NAN).is_err());
8012 for n in 0..1000 {
8013 assert_eq!(Rate::REAL_TIME.source_at(n), n);
8014 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
8015 }
8016 // ...and the composition, in the order the decoder's door applies it:
8017 // the speed picks the clip's (timeline-rate) frame, the rate picks the
8018 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
8019 // timeline frames per frame shown, each of them exactly 800/1001 of a
8020 // file frame.
8021 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
8022 let speed = Speed::from_permille(2000);
8023 for d in 0..100u32 {
8024 assert_eq!(
8025 rate.source_at(speed.source_at(d)),
8026 (u64::from(d) * 2 * 800 / 1001) as u32,
8027 "2x of a 23.976 fps file at timeline frame {d}"
8028 );
8029 }
8030 }
8031
8032 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
8033 /// source frames per timeline frame and still starts at its own in-point,
8034 /// and a half-speed one shows every source frame twice.
8035 #[test]
8036 fn a_rate_maps_timeline_frames_onto_source_frames() {
8037 let mut p = Project::single(FILE, 40);
8038 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8039 .expect("room enough");
8040 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
8041 assert_eq!(
8042 p.map(Lane::V1, 0),
8043 Some((0, 0)),
8044 "and it starts where it did"
8045 );
8046 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
8047 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
8048 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
8049 // The span a decoder is handed: as many source frames as it will read,
8050 // which is the last shown frame's own and not one more -- timeline frame
8051 // 19 shows source frame 38, so 39 frames are read and the 40th is a
8052 // picture nothing would display.
8053 let span = p.span_at(Lane::V1, 0).expect("a span");
8054 assert_eq!((span.len, span.source_len()), (20, 39));
8055 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
8056 // ...and the same clip the other way round.
8057 let mut p = Project::single(FILE, 40);
8058 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8059 .expect("room enough");
8060 assert_eq!(p.timeline_frames(), 80);
8061 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
8062 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
8063 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
8064 assert_eq!(
8065 p.map(Lane::V1, 79),
8066 Some((0, 39)),
8067 "and the last timeline frame is still inside the source range"
8068 );
8069 }
8070
8071 /// A trim of a speeded clip is still a trim of its *source*, and the edge
8072 /// still stops at the wall: the room a rate leaves is measured in timeline
8073 /// frames and the range it commits in source ones.
8074 #[test]
8075 fn trimming_a_speeded_clip_stays_inside_its_room() {
8076 let mut p = Project::single(FILE, 40);
8077 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8078 .expect("room enough");
8079 // A second clip butted against the first, so the wall is a real one.
8080 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
8081 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
8082 assert_eq!(room, (1, 20), "out to the neighbour and no further");
8083 assert!(
8084 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
8085 "clamped to the wall, which is where the edge already is"
8086 );
8087 let c = p.clips()[0];
8088 assert_eq!(c.end(), 20, "so nothing moved");
8089 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
8090 // ...and in: half the timeline frames is half the source range.
8091 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
8092 let c = p.clips()[0];
8093 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
8094 assert_eq!(c.end(), 10, "and ten timeline frames of them");
8095 assert!(sorted_disjoint(p.clips()));
8096 }
8097
8098 /// The frames a rate cannot address: at half speed each source frame is on
8099 /// screen twice, and the cut between the two showings is not a cut in the
8100 /// file. Refused, so the two halves always add up to the clip that was cut.
8101 #[test]
8102 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
8103 let mut p = Project::single(FILE, 10);
8104 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8105 .expect("room enough");
8106 assert_eq!(p.timeline_frames(), 20);
8107 assert!(
8108 !p.split(3),
8109 "an odd frame is between two showings of one frame"
8110 );
8111 assert_eq!(p.clips().len(), 1, "and nothing was cut");
8112 assert!(p.split(4), "an even one is a frame boundary");
8113 let halves = p.clips().to_vec();
8114 assert_eq!(
8115 (halves[0].end(), halves[1].start, halves[1].end()),
8116 (4, 4, 20),
8117 "the halves meet, and still end where the clip did"
8118 );
8119 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
8120 assert!(p.regroup(4), "and the inverse puts it back");
8121 assert_eq!(p.clips().len(), 1);
8122 }
8123
8124 /// The same claim, swept: random op sequences off the public surface, the
8125 /// project reloaded after every one of them. A failure prints its seed, and
8126 /// the seed replays the whole sequence.
8127 #[test]
8128 fn random_edit_sequences_reload() {
8129 // Two thousand, not two hundred: the overlap a hole punched into a slow
8130 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
8131 // sequences, and a 200-seed sweep walked straight past it (it took a
8132 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
8133 // has no business being the narrow one.
8134 for seed in 0..2000u64 {
8135 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8136 let mut next = move |n: u32| {
8137 // xorshift64*: no dependency, and the seed replays it exactly.
8138 rng ^= rng << 13;
8139 rng ^= rng >> 7;
8140 rng ^= rng << 17;
8141 (rng >> 33) as u32 % n
8142 };
8143 let mut p = Project::single(FILE, 40);
8144 for step in 0..24 {
8145 let frame = next(44);
8146 // A clipboard copy carries the group id of the take it came from
8147 // -- the input that made a placement duplicate an id -- and, one
8148 // time in three, a rate of its own: a *speeded clip placed over
8149 // a speeded clip* is the shape whose remainders have to be run
8150 // through `Speed::fit`, and it is not a shape the lanes hand out
8151 // on their own often enough to be sure of.
8152 let mut copied = *p
8153 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
8154 .get(next(4) as usize)
8155 .unwrap_or(&clip(0, 0, 5, 0));
8156 if next(3) == 0 {
8157 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
8158 }
8159 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
8160 let idx = next(4) as usize;
8161 let _ = match next(16) {
8162 // A clip dragged along its own lane to wherever the pointer
8163 // let it go: the op that moves a placement without changing
8164 // what it plays, so what it may not do is land on top of the
8165 // neighbour it was dragged at.
8166 15 => p.move_clip(lane, idx, lane, frame),
8167 // ...and a second `place`, so a punch lands inside a clip
8168 // far more often than one op in fourteen would put it there.
8169 14 => p.place(lane, frame, copied),
8170 0 => p.split(frame),
8171 1 => p.regroup(frame),
8172 2 => p.lift(lane, idx),
8173 3 => p.place(lane, frame, copied),
8174 4 => p.paste(frame, copied),
8175 5 => p.ripple_delete(frame, next(9)),
8176 6 => p.delete(idx),
8177 7 => p.undo(),
8178 // An equalizer put on and taken off in the mix: what a clip
8179 // carries has to reload with it, and the entries an undo
8180 // orphans must not come back out of the prune.
8181 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8182 9 => p.set_eq(lane, idx, None),
8183 // ...and a colour grade in the same mix, for the same
8184 // reason: it rides on the clip and its orphans must go.
8185 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
8186 11 => p.set_color(lane, idx, None),
8187 // ...and a rate in with them, which is the one of the three
8188 // that moves *placements*: a clip that grew has to be
8189 // refused rather than overlap, and one that shrank leaves a
8190 // lane that still loads. Both are what `reloads` asks.
8191 12 => p
8192 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8193 .is_ok(),
8194 _ => p.append_clip(0, 1 + next(9)),
8195 };
8196 reloads(&p, &format!("seed {seed}, step {step}"));
8197 }
8198 }
8199 }
8200
8201 /// The save/load round trip a project must survive: the parts a save writes,
8202 /// handed back to the constructor a load goes through -- every lane of them,
8203 /// and the reloaded timeline has to be the same lanes in the same order.
8204 fn reloads(p: &Project, what: &str) {
8205 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
8206 match Project::from_parts(sources, lanes, eq, color) {
8207 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
8208 Ok(back) => {
8209 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
8210 // Placements, not whole clips: an orphan prune renumbers the
8211 // sources a clip names, which is the point of it.
8212 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
8213 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
8214 };
8215 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
8216 // The prune renumbers the eq table too, so what has to survive
8217 // is the settings themselves, clip by clip.
8218 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
8219 p.lanes()
8220 .into_iter()
8221 .map(|l| {
8222 (0..p.lane(l).len())
8223 .map(|i| p.eq_of(l, i).cloned())
8224 .collect()
8225 })
8226 .collect()
8227 };
8228 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
8229 // The colour table renumbers in the same prune, so the same
8230 // claim: the params a clip names, not the index it names them by.
8231 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
8232 p.lanes()
8233 .into_iter()
8234 .map(|l| {
8235 (0..p.lane(l).len())
8236 .map(|i| p.color_of(l, i).copied())
8237 .collect()
8238 })
8239 .collect()
8240 };
8241 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
8242 }
8243 }
8244 }
8245
8246 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
8247 /// -- each one sorted and disjoint, and one span per group id -- asserted
8248 /// directly, where the point is the invariant rather than the round trip.
8249 fn invariants_hold(p: &Project, what: &str) {
8250 for lane in p.lanes() {
8251 assert!(
8252 sorted_disjoint(p.lane(lane)),
8253 "{what}: {} is out of order or overlaps itself: {:?}",
8254 lane.label(),
8255 p.lane(lane)
8256 );
8257 }
8258 if let Err(e) = links_are_consistent(&p.lanes) {
8259 panic!("{what}: {e}\n{:?}", p.lanes);
8260 }
8261 }
8262
8263 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
8264 /// edited without any other lane hearing about it. A handle naming a lane
8265 /// that is not there reads as empty and refuses to mutate.
8266 #[test]
8267 fn a_third_lane_is_a_peer() {
8268 let mut p = three();
8269 assert_eq!(p.lane_count(LaneKind::Video), 1);
8270 assert_eq!(p.lane_count(LaneKind::Audio), 1);
8271 let v2 = p.add_lane(LaneKind::Video);
8272 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
8273 assert_eq!(v2.label(), "V2");
8274 assert_eq!(p.lane_count(LaneKind::Video), 2);
8275 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8276 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
8277
8278 // A handle for a lane that is not there: empty, and no mutation takes.
8279 let v3 = Lane::new(LaneKind::Video, 2);
8280 assert!(p.lane(v3).is_empty());
8281 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
8282 assert!(!p.lift(v3, 0));
8283 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
8284
8285 // Placing on V2 moves nothing else, and the lane can outrun the rest.
8286 let before = shape(&p);
8287 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8288 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
8289 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
8290 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8291 assert_eq!(
8292 p.timeline_frames(),
8293 16,
8294 "the last lane to end sets the length"
8295 );
8296 assert_eq!(p.map(v2, 5), Some((0, 21)));
8297 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
8298 assert_eq!(
8299 p.span_at(v2, 0),
8300 Some(Span {
8301 start: 0,
8302 len: 4,
8303 from: None,
8304 speed: Speed::NORMAL
8305 })
8306 );
8307 // Every lane still covers the whole timeline, gaps included.
8308 for l in p.lanes() {
8309 let spans = p.spans_from(l, 0);
8310 assert_eq!(
8311 spans.iter().map(|s| s.len).sum::<u32>(),
8312 16,
8313 "{}",
8314 l.label()
8315 );
8316 }
8317 // ...and playback still reads V1 and A1, whatever else is there.
8318 assert_eq!(p.clips(), p.lane(Lane::V1));
8319 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
8320 let segments = p.segments_from(0, FPS);
8321 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
8322 assert_eq!(
8323 segments[3],
8324 (None, 0.0, 7.0 / FPS),
8325 "A1 keeps the clock counting over the picture V2 added"
8326 );
8327 invariants_hold(&p, "place on V2");
8328
8329 // A lift is that lane's business too, and the lane list undoes.
8330 assert!(p.lift(v2, 0));
8331 assert!(p.lane(v2).is_empty());
8332 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
8333 assert!(p.undo());
8334 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8335 assert!(p.undo());
8336 assert!(p.lane(v2).is_empty(), "the placement came off V2");
8337 assert!(p.undo(), "and one more step takes the lane itself back");
8338 assert_eq!(p.lane_count(LaneKind::Video), 1);
8339 assert_eq!(shape(&p), shape(&three()));
8340 }
8341
8342 /// The add taken back: an empty lane comes off, a lane holding clips never
8343 /// does (and says which clips), the last lane of a kind never does, the
8344 /// lanes below the one that went move up an `ord`, and one undo puts it
8345 /// back where it stood.
8346 #[test]
8347 fn an_empty_lane_comes_off_again() {
8348 let mut p = three();
8349 let v2 = p.add_lane(LaneKind::Video);
8350 let v3 = p.add_lane(LaneKind::Video);
8351 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
8352 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
8353 let history = p.history.len();
8354
8355 // The last lane of its kind stays: `V1`/`A1` are where an import and a
8356 // paste land, and a project missing one would swallow half of a file
8357 // dropped on it.
8358 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
8359 assert_eq!(
8360 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
8361 "there is no V10 to remove"
8362 );
8363
8364 // A lane with clips on it refuses and names them: a track removal never
8365 // deletes a take.
8366 let refusal = why(p.remove_lane(v3));
8367 assert!(refusal.contains("V3 still holds"), "{refusal}");
8368 assert!(refusal.contains(FILE), "{refusal}");
8369 assert!(refusal.contains("at frame 0"), "{refusal}");
8370 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
8371 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
8372
8373 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
8374 // all.
8375 p.remove_lane(v2).expect("V2 is empty");
8376 assert_eq!(p.lane_count(LaneKind::Video), 2);
8377 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8378 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
8379 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
8380 invariants_hold(&p, "remove V2");
8381
8382 // ...and one stroke puts the empty lane back above it.
8383 assert!(p.undo());
8384 assert_eq!(p.lane_count(LaneKind::Video), 3);
8385 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
8386 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
8387 }
8388
8389 /// A track dragged to another place in the stack: the whole lane travels --
8390 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
8391 /// a video one, a lane that crosses one of its own kind swaps names with it
8392 /// (and swaps the composite with it), one undo puts the order back, and a
8393 /// save carries it.
8394 #[test]
8395 fn a_track_is_dragged_to_another_place_in_the_stack() {
8396 let mut p = three();
8397 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
8398 let before = shape(&p);
8399 let history = p.history.len();
8400
8401 // A1 over V1: the screen is rearranged and nothing else is. Both keep
8402 // their names -- neither crossed a lane of its own kind -- so every
8403 // handle a front-end holds still names the track it named before.
8404 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
8405 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
8406 assert_eq!(
8407 shape(&p),
8408 vec![before[1].clone(), before[0].clone()],
8409 "each lane's clips travelled with it, and none was remapped"
8410 );
8411 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
8412 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
8413 invariants_hold(&p, "A1 over V1");
8414
8415 // Nothing moves for a lane that is not there, a slot that is not, or a
8416 // lane already standing in the one it was pointed at.
8417 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
8418 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
8419 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
8420 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
8421
8422 // ...and one stroke puts the order back.
8423 assert!(p.undo());
8424 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
8425 assert_eq!(shape(&p), before);
8426
8427 // A second video lane over the first: display order *is* the stack, so
8428 // the last video lane covering a frame is the picture that shows.
8429 let v2 = p.add_lane(LaneKind::Video);
8430 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
8431 let over = shape(&p)[2].clone();
8432 assert_eq!(
8433 p.composite_span_at(0).map(|s| s.len),
8434 Some(5),
8435 "V2's five frames are what frame 0 shows"
8436 );
8437
8438 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
8439 // a position among the lanes of its kind. The picture that wins changes
8440 // with it: the take that was covering is the covered one now.
8441 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
8442 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
8443 assert_eq!(
8444 shape(&p),
8445 vec![over.clone(), before[0].clone(), before[1].clone()],
8446 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
8447 );
8448 assert_eq!(
8449 p.composite_span_at(0).map(|s| s.len),
8450 Some(3),
8451 "the lower video lane wins, and it is the old V1 now"
8452 );
8453 invariants_hold(&p, "V2 over V1");
8454
8455 // A save writes that order and a load takes it back.
8456 let (sources, lanes, eq, color) = p.without_orphan_sources();
8457 assert_eq!(
8458 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
8459 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
8460 );
8461 let back = Project::from_parts(sources, lanes, eq, color).expect("three lanes load");
8462 assert_eq!(back.lanes(), p.lanes());
8463 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
8464
8465 assert!(p.undo(), "and the stack goes back to how it stood");
8466 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
8467 }
8468
8469 /// The grouping rule across more than two lanes, under the offset model: a
8470 /// split *keeps* the group on the left halves and hands the right halves of
8471 /// that group one fresh id of their own -- a clip in no group comes out of
8472 /// the cut in none. So a take cut apart is two takes, one per side, and a
8473 /// lane that was never part of it stays out of both.
8474 #[test]
8475 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
8476 let mut p = Project::single(FILE, 9);
8477 let take = p.clips()[0].link.expect("a fresh project is one take");
8478 let v2 = p.add_lane(LaneKind::Video);
8479 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
8480 assert!(p.split(4));
8481 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
8482 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
8483 };
8484 let (left, right) = (side(&p, 0), side(&p, 1));
8485 // The lanes in order are V1, A1, V2: the take's two keep its id on the
8486 // left, and the placed clip never had one for the cut to keep.
8487 assert_eq!(
8488 left,
8489 vec![Some(take), Some(take), None],
8490 "the left halves keep the take"
8491 );
8492 // ...and the right halves of that take are one fresh group.
8493 assert_eq!(right[0], right[1]);
8494 assert_ne!(right[0], Some(take));
8495 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
8496 invariants_hold(&p, "split across three lanes");
8497
8498 // V2 ends early: the left halves still keep what each clip carried --
8499 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
8500 // shared by exactly the take's lanes.
8501 let mut p = Project::single(FILE, 9);
8502 let v2 = p.add_lane(LaneKind::Video);
8503 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
8504 assert!(p.split(3));
8505 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
8506 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
8507 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
8508 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
8509 invariants_hold(&p, "split where one lane ends early");
8510
8511 // The inverse rejoins each lane into the group its left half kept.
8512 assert!(p.regroup(3));
8513 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
8514 assert_eq!(
8515 p.lane(Lane::V1)[0].link,
8516 Some(take),
8517 "the take's id is back, not a fresh one"
8518 );
8519 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
8520 invariants_hold(&p, "regroup across three lanes");
8521 }
8522
8523 /// A group is one placement per lane, on however many lanes carry the id --
8524 /// not a video/audio pair and not a pairing by `ord` -- and the members may
8525 /// cover whatever frames they cover: the offset between them is what a
8526 /// hand-built group keeps. Lanes built by hand, because the rule is checked
8527 /// at the untrusted door and no edit can produce the one thing it refuses.
8528 #[test]
8529 fn a_group_may_span_any_lane() {
8530 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
8531 let one = |start: u32, end: u32, link| Clip {
8532 start,
8533 in_frame: start,
8534 out_frame: end,
8535 source: 0,
8536 link: Some(link),
8537 eq: None,
8538 color: None,
8539 fit: FitPolicy::default(),
8540 speed: Speed::NORMAL,
8541 };
8542 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
8543 let kinds = [
8544 LaneKind::Video,
8545 LaneKind::Audio,
8546 LaneKind::Video,
8547 LaneKind::Audio,
8548 ];
8549 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
8550 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
8551 };
8552 let take = || vec![one(0, 4, 7)];
8553 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
8554 // The same take on V1 + A2 only, the lanes between it empty: legal, the
8555 // way a lifted half is legal.
8556 let across = build([take(), Vec::new(), Vec::new(), take()]);
8557 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
8558 // ...and so is a group whose members disagree about their spans: the
8559 // offset between them is the hand's business, not the loader's.
8560 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
8561 assert!(
8562 links_are_consistent(&apart).is_ok(),
8563 "[0, 4) on V1 and [2, 6) on A2 are one group"
8564 );
8565 // One id twice in one lane is still that lane's error, by name.
8566 let twice = build([
8567 Vec::new(),
8568 Vec::new(),
8569 vec![one(0, 4, 7), one(4, 8, 7)],
8570 Vec::new(),
8571 ]);
8572 assert_eq!(
8573 links_are_consistent(&twice).unwrap_err().to_string(),
8574 "link 7 names two clips in the V2 lane"
8575 );
8576 }
8577
8578 /// Every lane a save writes comes out, in display order and with its kind --
8579 /// an empty one included, since it is state a front-end shows -- and a
8580 /// two-lane project still writes exactly the parts it always did.
8581 #[test]
8582 fn a_save_writes_every_lane_it_has() {
8583 let mut p = three();
8584 let before = p.without_orphan_sources();
8585 assert_eq!(before.1.len(), 2, "V1 and A1");
8586 let v2 = p.add_lane(LaneKind::Video);
8587 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8588 let a2 = p.add_lane(LaneKind::Audio);
8589 let (sources, lanes, eq, color) = p.without_orphan_sources();
8590 assert_eq!(
8591 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
8592 [
8593 LaneKind::Video,
8594 LaneKind::Audio,
8595 LaneKind::Video,
8596 LaneKind::Audio
8597 ],
8598 "display order, not video-then-audio"
8599 );
8600 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
8601 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
8602 // ...and all four load again as the same four.
8603 let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load");
8604 assert_eq!(back.lanes(), p.lanes());
8605 assert_eq!(back.lane(a2), p.lane(a2));
8606
8607 // Taking the lanes back leaves exactly what a two-lane save wrote.
8608 for _ in 0..3 {
8609 assert!(p.undo());
8610 }
8611 assert_eq!(
8612 p.without_orphan_sources(),
8613 before,
8614 "byte for byte the same parts a two-lane save always wrote"
8615 );
8616 }
8617
8618 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
8619 /// three lanes and grows more: every lane's own order and the one
8620 /// span-per-id rule after every op, *and* the reload the v4 format restored
8621 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
8622 /// project of any number of lanes.
8623 #[test]
8624 fn random_edit_sequences_keep_many_lanes_consistent() {
8625 for seed in 0..2000u64 {
8626 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8627 let mut next = move |n: u32| {
8628 rng ^= rng << 13;
8629 rng ^= rng >> 7;
8630 rng ^= rng << 17;
8631 (rng >> 33) as u32 % n
8632 };
8633 let mut p = Project::single(FILE, 40);
8634 let v2 = p.add_lane(LaneKind::Video);
8635 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
8636 let lanes = [Lane::V1, Lane::A1, v2];
8637 for step in 0..24 {
8638 let frame = next(44);
8639 let copied = *p
8640 .lane(lanes[next(3) as usize])
8641 .get(next(4) as usize)
8642 .unwrap_or(&clip(0, 0, 5, 0));
8643 let lane = lanes[next(3) as usize];
8644 let idx = next(4) as usize;
8645 let _ = match next(14) {
8646 // The drag, in the mix: a clip dragged along its own lane
8647 // and onto another one, at a frame the pointer picked --
8648 // which is where the group rule and the sorted+disjoint one
8649 // meet, since every half travels the same distance.
8650 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
8651 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8652 11 => p.set_eq(lane, idx, None),
8653 // A rate, which on many lanes is the group rule as well:
8654 // every clip carrying the link moves together or none of
8655 // them does, and `invariants_hold` is what says so.
8656 12 => p
8657 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8658 .is_ok(),
8659 0 => p.split(frame),
8660 1 => p.regroup(frame),
8661 2 => p.lift(lane, idx),
8662 3 => p.place(lane, frame, copied),
8663 4 => p.paste(frame, copied),
8664 5 => p.ripple_delete(frame, next(9)),
8665 6 => p.delete(idx),
8666 7 => p.undo(),
8667 8 => {
8668 p.add_lane(if next(2) == 0 {
8669 LaneKind::Video
8670 } else {
8671 LaneKind::Audio
8672 });
8673 true
8674 }
8675 _ => p.append_clip(0, 1 + next(9)),
8676 };
8677 invariants_hold(&p, &format!("seed {seed}, step {step}"));
8678 reloads(&p, &format!("seed {seed}, step {step}"));
8679 }
8680 }
8681 }
8682
8683 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
8684 /// there, `V1` shows again on either side of it, and a frame no video lane
8685 /// covers is a gap however many lanes there are.
8686 #[test]
8687 fn the_composite_is_the_topmost_lane_with_a_clip() {
8688 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8689 let lanes = vec![
8690 // V1: the whole 30 frames of source 0.
8691 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8692 // V2: source 1 over the middle third.
8693 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
8694 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8695 ];
8696 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
8697 assert_eq!(
8698 p.composite_spans_from(0),
8699 vec![
8700 Span {
8701 start: 0,
8702 len: 10,
8703 from: Some((0, 0)),
8704 speed: Speed::NORMAL
8705 },
8706 Span {
8707 start: 10,
8708 len: 10,
8709 from: Some((1, 5)),
8710 speed: Speed::NORMAL
8711 },
8712 Span {
8713 start: 20,
8714 len: 10,
8715 from: Some((0, 20)),
8716 speed: Speed::NORMAL
8717 },
8718 ],
8719 "V2 takes over for its own span and hands V1 back"
8720 );
8721 // A mid-span ask resolves the same way, which is what a seek does.
8722 assert_eq!(
8723 p.composite_span_at(15),
8724 Some(Span {
8725 start: 15,
8726 len: 5,
8727 from: Some((1, 10)),
8728 speed: Speed::NORMAL
8729 })
8730 );
8731 assert_eq!(p.composite_span_at(30), None, "past the end");
8732
8733 // A hole in V1 under V2's clip: black between the two, and black after
8734 // both run out (the audio lane is still holding the timeline open).
8735 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8736 let holed = vec![
8737 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
8738 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
8739 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8740 ];
8741 let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts");
8742 assert_eq!(
8743 p.composite_spans_from(0),
8744 vec![
8745 Span {
8746 start: 0,
8747 len: 5,
8748 from: Some((0, 0)),
8749 speed: Speed::NORMAL
8750 },
8751 Span {
8752 start: 5,
8753 len: 5,
8754 from: None,
8755 speed: Speed::NORMAL
8756 },
8757 Span {
8758 start: 10,
8759 len: 10,
8760 from: Some((1, 0)),
8761 speed: Speed::NORMAL
8762 },
8763 Span {
8764 start: 20,
8765 len: 10,
8766 from: None,
8767 speed: Speed::NORMAL
8768 },
8769 ]
8770 );
8771
8772 // One video lane: the composite *is* that lane, span for span -- the
8773 // promise every existing two-lane project rests on.
8774 let p = Project::single(FILE, 30);
8775 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
8776 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
8777 }
8778
8779 /// Every audio lane holding something gets a play list, and only those.
8780 #[test]
8781 fn audio_segments_cover_every_lane_that_holds_something() {
8782 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8783 let lanes = vec![
8784 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8785 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8786 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
8787 (LaneKind::Audio, Vec::new()),
8788 ];
8789 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
8790 let lists = p.audio_segments_from(0, FPS);
8791 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
8792 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
8793 // A2 is a gap up to frame 15, then the whole of source 1.
8794 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
8795
8796 // No audio lane holds anything: one all-gap list, so such a timeline
8797 // still plays silence against a master clock.
8798 let p = Project::from_parts(
8799 vec![Source::new(FILE, 0)],
8800 vec![
8801 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8802 (LaneKind::Audio, Vec::new()),
8803 ],
8804 vec![],
8805 vec![],
8806 )
8807 .expect("valid parts");
8808 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
8809 }
8810}