forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB3050ac9Tahinli3 months ago553 commits

project.rs8861 lines, 386.9 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::transform::TransformParams;
81use crate::eq::EqParams;
82use crate::limiter::{Limiter, db_to_linear};
83use crate::scale::FitPolicy;
84use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
85
86/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
87/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
88/// for every purpose but the honest one, which is that it is still a level and
89/// not a mute.
90pub const MIN_GAIN_DB: f32 = -60.0;
91/// ...and how far up. +12 dB is four times the amplitude, which is as much as
92/// a mix bus can take before the limiter is doing all the work.
93pub const MAX_GAIN_DB: f32 = 12.0;
94
95/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
98/// comparable nor exactly writable, and `.edith` has to read back the very
99/// number that was set. A thousandth is finer than any card can drag and coarser
100/// than any rounding anyone can hear.
101///
102/// The rate alone: the audio path time-stretches a speeded clip
103/// (`crate::stretch`), so its pitch stays where it was recorded while its
104/// seconds compress or stretch -- the tape effect this used to be is gone.
105/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
106/// [`Speed::MAX`] four times.
107#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
108pub struct Speed(u16);
109
110/// What [`Project::parts`] hands back: the comparable shape of everything an
111/// edit can change, for the sweep's undo round-trip. Test-only, like every
112/// accessor it exists for: the sweep lives behind `cfg(test)`.
113#[cfg(test)]
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct SweepParts(
116 pub(crate) usize,
117 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
118 pub(crate) Vec<Vec<SubClip>>,
119);
120
121impl Speed {
122 /// Real time -- what every clip is until something says otherwise, and the
123 /// value every path in this engine short-circuits on.
124 pub const NORMAL: Speed = Speed(1000);
125 pub const MIN: Speed = Speed(250);
126 pub const MAX: Speed = Speed(4000);
127
128 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
129 /// unrepresentable rather than merely refused: nothing downstream divides
130 /// by a speed that could be nothing.
131 pub fn from_permille(permille: u16) -> Self {
132 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
133 }
134
135 pub fn permille(self) -> u16 {
136 self.0
137 }
138
139 pub fn is_normal(self) -> bool {
140 self == Self::NORMAL
141 }
142
143 /// As a multiplier, for the sound worker and for a label.
144 pub fn as_f64(self) -> f64 {
145 f64::from(self.0) / 1000.
146 }
147
148 /// How many *timeline* frames `source` source frames occupy at this rate --
149 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
150 /// clip that occupied no frames would be an empty placement, which the lane
151 /// invariant forbids and which nothing could ever click on again.
152 pub fn frames(self, source: u32) -> u32 {
153 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
154 n.clamp(1, u64::from(u32::MAX)) as u32
155 }
156
157 /// The mapping itself: which source frame of a clip the `offset`th timeline
158 /// frame of it plays. Floored, so the first timeline frame is the clip's own
159 /// in-point at every rate.
160 pub fn source_at(self, offset: u32) -> u32 {
161 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
162 }
163
164 /// Its inverse, for a decoder's frames on their way back out: which timeline
165 /// frame of the clip the `offset`th *source* frame of it lands on.
166 ///
167 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
168 /// decoded frame with this and shows the newest whose stamp has come due, so
169 /// what is on screen at timeline offset `d` is the last source frame with
170 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
171 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
172 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
173 /// the two the same way would put the preview a frame off the export at some
174 /// speeds and a whole held frame off at slow ones -- drift that no test of
175 /// either side alone would catch.
176 pub fn timeline_at(self, offset: u32) -> u32 {
177 (u64::from(offset) * 1000)
178 .div_ceil(u64::from(self.0))
179 .min(u64::from(u32::MAX)) as u32
180 }
181
182 /// The longest source range that still *fits* in `frames` timeline frames at
183 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
184 /// any room narrower than the four timeline frames one source frame occupies.
185 ///
186 /// What a trim commits and what a hole-punch leaves behind: rounding could
187 /// otherwise hand back a range wider than the room, and a clip that outgrew
188 /// its room would overlap its neighbour -- the one thing a lane may never do.
189 /// `None` is not an error, it is "no remainder": the caller drops that piece
190 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
191 /// is `frames` itself, so nothing about an unspeeded edit changes.
192 pub fn fit(self, frames: u32) -> Option<u32> {
193 if frames == 0 || self.frames(1) > frames {
194 return None;
195 }
196 let mut src = self.source_at(frames).max(1);
197 // At most a step or two: `frames` is monotone in `src` and the rounding
198 // above can only overshoot by one source frame's worth.
199 while src > 1 && self.frames(src) > frames {
200 src -= 1;
201 }
202 Some(src)
203 }
204
205 /// How many timeline frames `source` source frames of head (or tail) are
206 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
207 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
208 /// empty, but the room in front of one may well be.
209 pub fn room(self, source: u32) -> u32 {
210 match source {
211 0 => 0,
212 n => self.frames(n),
213 }
214 }
215
216 /// How many timeline frames from `offset` on show the **same** source frame:
217 /// one at real time and faster, more when the clip is slowed. What an export
218 /// encodes without decoding the same picture twice, and the count that makes
219 /// its frame walk exactly as long as the span.
220 pub fn repeats(self, offset: u32, len: u32) -> u32 {
221 let want = self.source_at(offset);
222 (offset..len)
223 .take_while(|&t| self.source_at(t) == want)
224 .count() as u32
225 }
226
227 /// Where in the source a cut `offset` timeline frames into a clip of `len`
228 /// source frames falls -- and `None` when this rate cannot address that
229 /// frame at all.
230 ///
231 /// At half speed a clip of ten source frames is twenty timeline frames long
232 /// and every source frame is on screen twice, so a cut between the two
233 /// showings of one frame is not a cut in the *file*: taking it would leave
234 /// two halves whose lengths no longer add up to the clip that was cut --
235 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
236 /// the model stays exact and the front-end can say why. At real time every
237 /// interior frame answers, which is the path a project without speeds is on.
238 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
239 let src = self.source_at(offset);
240 (src > 0
241 && src < len
242 && self.frames(src) == offset
243 && self.frames(len - src) == self.frames(len) - offset)
244 .then_some(src)
245 }
246}
247
248impl Default for Speed {
249 fn default() -> Self {
250 Self::NORMAL
251 }
252}
253
254impl std::fmt::Display for Speed {
255 /// `2.00x` -- what a card prints and what a clip box is marked with.
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 write!(f, "{:.2}x", self.as_f64())
258 }
259}
260
261/// What a file's own frame rate is against the timeline's, as an exact
262/// rational: how many frames of the *file* one frame of the timeline is worth.
263///
264/// Every frame number in this module counts **timeline** frames -- a clip's
265/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
266/// timeline is as many frames long as the seconds it lasts, and every edit
267/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
268/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
269/// opens a worker with it and [`crate::export`] pulls pictures through it. The
270/// file's own numbering exists nowhere else.
271///
272/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
273/// export encodes at a timeline frame has to be the frame playback is holding
274/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
275/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
276///
277/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
278/// stays `800/1001` however far the timeline runs, where a rate rounded to
279/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
280/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
281///
282/// [`PlaybackSession`]: crate::PlaybackSession
283#[derive(Clone, Copy, PartialEq, Eq, Debug)]
284pub struct Rate {
285 /// Frames of the file...
286 source: u32,
287 /// ...per this many frames of the timeline it plays on. Never zero.
288 timeline: u32,
289}
290
291impl Rate {
292 /// A file shot at the timeline's own rate: every conversion below is the
293 /// identity, which is the path a single-rate project is on.
294 pub const REAL_TIME: Self = Self {
295 source: 1,
296 timeline: 1,
297 };
298
299 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
300 /// exactly.
301 ///
302 /// Both rates come out of a container as a division, so neither is ever the
303 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
304 /// already knows how to name one exactly -- it is the same pair the muxer
305 /// counts an export's frames in -- and this is that pair divided by that
306 /// pair, reduced. A rate no timescale can name is an `Err` in that
307 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
308 /// where a file carrying one is refused by name, beside the codec.
309 ///
310 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
311 /// timeline that had ever opened in this editor before mixed rates.
312 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
313 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
314 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
315 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
316 let num = u64::from(src_scale) * u64::from(tl_ticks);
317 let den = u64::from(src_ticks) * u64::from(tl_scale);
318 Ok(Self::reduced(num, den))
319 }
320
321 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
322 fn reduced(num: u64, den: u64) -> Self {
323 let g = gcd(num, den);
324 let (mut num, mut den) = (num / g, den / g);
325 // A ratio no pair of real frame rates produces, but the fields are `u32`
326 // so that every multiplication below fits a `u64` at any frame count.
327 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
328 (num, den) = (num.div_ceil(2), den.div_ceil(2));
329 }
330 Self {
331 source: num.max(1) as u32,
332 timeline: den.max(1) as u32,
333 }
334 }
335
336 /// The same file against a timeline that has itself been retimed: `self` is
337 /// its frames per frame of the old timeline and `k` is old frames per new
338 /// one, so this is its frames per frame of the *new* one -- exactly, without
339 /// going back through an `f64` fps that names neither rate
340 /// ([`crate::PlaybackSession::set_frame_rate`]).
341 pub fn then(self, k: Rate) -> Self {
342 Self::reduced(
343 u64::from(self.source) * u64::from(k.source),
344 u64::from(self.timeline) * u64::from(k.timeline),
345 )
346 }
347
348 pub fn is_real_time(self) -> bool {
349 self.source == self.timeline
350 }
351
352 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
353 /// is, given the timeline's, for a library row that names it.
354 pub fn as_f64(self) -> f64 {
355 f64::from(self.source) / f64::from(self.timeline)
356 }
357
358 /// Which frame of the file the `frame`th timeline-rate frame of it is:
359 /// floored, [`Speed::source_at`]'s half of the pair.
360 pub fn source_at(self, frame: u32) -> u32 {
361 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
362 .min(u64::from(u32::MAX)) as u32
363 }
364
365 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
366 /// timeline-rate frame that shows source frame `source_frame` -- which is
367 /// the stamp playback puts on a decoded picture, and, applied to a file's
368 /// frame *count*, how long that file is in timeline frames.
369 pub fn timeline_at(self, source_frame: u32) -> u32 {
370 (u64::from(source_frame) * u64::from(self.timeline))
371 .div_ceil(u64::from(self.source))
372 .min(u64::from(u32::MAX)) as u32
373 }
374}
375
376/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
377/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
378fn gcd(a: u64, b: u64) -> u64 {
379 match b {
380 0 => a.max(1),
381 b => gcd(b, a % b),
382 }
383}
384
385/// A half-open `[in_frame, out_frame)` range of frames of source
386/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
387/// Never empty.
388///
389/// Counted at the **timeline's** frame rate, not the file's: a source shot at
390/// another rate is converted at the decoder's door ([`Rate`]), so every edit
391/// here is frames of one clock.
392#[derive(Clone, Copy, PartialEq, Eq, Debug)]
393pub struct Clip {
394 /// Timeline frame the clip's first frame is shown at. Meaningless on a
395 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
396 /// with where the caller asked for.
397 pub start: u32,
398 pub in_frame: u32,
399 pub out_frame: u32,
400 /// Index into [`Project::sources`].
401 pub source: usize,
402 /// Group id: clips sharing one were split from the same take. `None` for a
403 /// clip that belongs to no group.
404 pub link: Option<u32>,
405 /// Index into the project's equalizer table
406 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
407 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
408 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
409 /// plain assignment. The table is append-only within a session, so an index
410 /// on a clipboard clip or inside an undo snapshot can never dangle.
411 pub eq: Option<u16>,
412 /// Index into the project's colour table
413 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
414 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
415 /// promises: `Copy`, append-only within a session, never dangling.
416 pub color: Option<u16>,
417 /// Index into the project's transform table
418 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
419 /// clip that plays at its fit policy's own placement. An index for
420 /// [`Clip::color`]'s reason and with the same promises.
421 pub transform: Option<u16>,
422 /// How this clip's picture meets a project canvas of another shape
423 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
424 /// two above: it is one byte with no parameters, so there is nothing for a
425 /// table to share, and a clip that is the project's own size never consults
426 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
427 /// where the aspect does not agree.
428 pub fit: FitPolicy,
429 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
430 /// eq and colour indexes: it is two bytes with nothing to share, and a table
431 /// would put a level of indirection between the mapping and the one number
432 /// every frame of it is divided by.
433 ///
434 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
435 /// the clip plays, so a trim and a split still address the file. What it
436 /// changes is how many *timeline* frames that range is spread over
437 /// ([`Clip::frames`]).
438 pub speed: Speed,
439}
440
441impl Clip {
442 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
443 /// reads out of its file -- not how long it is on the timeline, which is
444 /// [`Clip::frames`] and differs the moment it is speeded.
445 pub fn len(&self) -> u32 {
446 self.out_frame - self.in_frame
447 }
448
449 /// Timeline frames it occupies: its source range at its own speed, never
450 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
451 /// what it overlaps, how wide its box is -- is asked of this and not of
452 /// [`Clip::len`].
453 pub fn frames(&self) -> u32 {
454 self.speed.frames(self.len())
455 }
456
457 /// One past the last timeline frame it covers.
458 pub fn end(&self) -> u32 {
459 self.start + self.frames()
460 }
461}
462
463/// A file the timeline plays from, and *which* of its audio streams it plays:
464/// a file carrying one track per language is several sources, one per stream,
465/// sharing a path. Two entries differing only in the stream are two sources --
466/// they are what a clip names, and a clip plays exactly one stream.
467///
468/// The path is always canonical ([`Source::new`]), so the same file reached by
469/// two paths is one source.
470#[derive(Clone, Debug, PartialEq, Eq)]
471pub struct Source {
472 pub path: PathBuf,
473 /// Position among the file's audio tracks in file order, the numbering
474 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
475 /// single track, and for a silent one.
476 pub audio_stream: usize,
477}
478
479impl Source {
480 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
481 Self {
482 path: canonical(path.as_ref()),
483 audio_stream,
484 }
485 }
486}
487
488/// What a lane carries, which is what a *gap* in it means: black frames on a
489/// video lane, silence on an audio one, nothing over the picture on a subtitle
490/// one.
491#[derive(Clone, Copy, PartialEq, Eq, Debug)]
492pub enum LaneKind {
493 Video,
494 Audio,
495 /// Words over the picture, placed and trimmed like everything else
496 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
497 /// so a caption is dragged, cut, rippled and undone by the machinery every
498 /// other clip already goes through.
499 ///
500 /// It carries no [`Clip`] at all, and that is what keeps the media paths
501 /// free of it: [`Project::lane`] hands back an empty slice, so every
502 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
503 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
504 /// check it already had, [`Project::composite_span_at`] and
505 /// [`Project::audio_lanes`] never look at it, and the three doors that
506 /// could still put a picture on one -- [`Project::from_parts`],
507 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
508 Subtitle,
509}
510
511/// Which lane an operation acts on: a kind plus a 0-based position among the
512/// lanes of that kind, so [`Lane::V1`] is the first video lane and
513/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
514///
515/// A handle, not the lane itself. It stays meaningful while lanes are added,
516/// and one naming a lane that is not there reads as an empty lane and refuses
517/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
518/// bounds check of its own.
519#[derive(Clone, Copy, PartialEq, Eq, Debug)]
520pub struct Lane {
521 pub kind: LaneKind,
522 pub ord: usize,
523}
524
525impl Lane {
526 /// The first video lane: what a decoder plays and what an export renders.
527 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
528 /// The first audio lane: what the audio worker plays.
529 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
530 /// The first subtitle lane -- the one a project has only once something
531 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
532 /// alone.
533 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
534
535 pub const fn new(kind: LaneKind, ord: usize) -> Self {
536 Self { kind, ord }
537 }
538
539 /// `V1`, `A2`: how a lane is written in a header column and named in an
540 /// error about it.
541 pub fn label(self) -> String {
542 let kind = match self.kind {
543 LaneKind::Video => 'V',
544 LaneKind::Audio => 'A',
545 LaneKind::Subtitle => 'S',
546 };
547 format!("{kind}{}", self.ord + 1)
548 }
549}
550
551/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
552/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
553/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
554/// frames. Never empty at either end.
555///
556/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
557/// actually has, and placed by the same one number: the window is in the
558/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
559/// placement is in timeline frames like everything else on a lane. So the lane
560/// invariant is the lane's ([`subs_sorted_disjoint`] is
561/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
562/// else, and only the two calls that change a *duration* -- a trim, and the
563/// mapping out -- ever need the timeline's rate.
564///
565/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
566/// paste and an undo snapshot are a plain assignment and can never dangle.
567#[derive(Clone, Copy, PartialEq, Eq, Debug)]
568pub struct SubClip {
569 /// Timeline frame its first frame is shown at.
570 pub start: u32,
571 /// How many timeline frames it covers; `>= 1`. Held rather than derived
572 /// from the window because a [`Project`] has no frame rate -- the rate
573 /// enters at the door of the two calls that need it -- and every placement
574 /// question (where it ends, what it overlaps) is asked in frames.
575 pub frames: u32,
576 /// Index into [`Project::subtitles`]: *which* track's words these are.
577 pub track: usize,
578 /// The half-open window of that track it shows, in microseconds from the
579 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
580 /// timed in, so no conversion stands between a cue and the window that
581 /// keeps it.
582 pub in_us: i64,
583 pub out_us: i64,
584 /// Group id: `Some` exactly when a hand put this caption in a group with
585 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
586 /// no group, and what a cut cuts apart loses the one it had
587 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
588 /// clip is what makes the caption move, trim and delete with it.
589 pub link: Option<u32>,
590}
591
592impl SubClip {
593 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
594 /// what every overlap question is asked of.
595 pub fn end(&self) -> u32 {
596 self.start + self.frames
597 }
598
599 /// How much of its track it shows, in microseconds; `>= 1` by the
600 /// never-empty invariant.
601 pub fn window_us(&self) -> i64 {
602 self.out_us - self.in_us
603 }
604
605 /// Where in its window the timeline frame `frame` falls, in microseconds --
606 /// the cut a split, a ripple and a trim all land on.
607 ///
608 /// By proportion and not by the timeline's rate: the window and the frame
609 /// count measure the same stretch of time, so the fraction of the frames
610 /// before `frame` is the fraction of the microseconds before it. That is
611 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
612 /// without either of them learning an fps.
613 fn window_at(&self, frame: u32) -> i64 {
614 let into = i64::from(frame.saturating_sub(self.start));
615 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
616 }
617}
618
619/// One lane: what it is and what it holds. A struct rather than a bare
620/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
621/// compositing mode, a name -- and it belongs next to the clips it applies to.
622#[derive(Clone, Debug)]
623struct LaneData {
624 kind: LaneKind,
625 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
626 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
627 /// ever seeing a subtitle: they all read this list.
628 clips: Vec<Clip>,
629 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
630 /// empty on a video or audio one. Beside the clips rather than an enum over
631 /// them so that everything a lane *is* -- its place in the stack, its
632 /// label, its undo snapshot, its removal -- stays one code path for all
633 /// three kinds.
634 subs: Vec<SubClip>,
635 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
636 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
637 /// makes it a different thing from a clip's equalizer: it moves everything
638 /// on the track by the same amount, cuts included. Meaningless on a video
639 /// lane, where it is kept at 0 and asked by nothing.
640 gain_db: f32,
641}
642
643impl LaneData {
644 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
645 Self {
646 kind,
647 clips,
648 subs: Vec::new(),
649 gain_db: 0.0,
650 }
651 }
652
653 /// The two lanes a project starts with: `V1` then `A1`, in display order.
654 /// One place, because a freshly opened file is exactly this pair.
655 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
656 vec![
657 LaneData::new(LaneKind::Video, video),
658 LaneData::new(LaneKind::Audio, audio),
659 ]
660 }
661}
662
663/// The placements one group id names, split by the two lists a lane holds:
664/// what a drag, a trim and a delete each have to walk, now that a group may
665/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
666/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
667/// -- so the pairs are `(lane storage index, index into that lane's list)`.
668#[derive(Default)]
669struct Members {
670 clips: Vec<(usize, usize)>,
671 subs: Vec<(usize, usize)>,
672}
673
674impl Members {
675 /// Whether the group is the one placement and no more: what a lift leaves
676 /// behind, and what every whole-group question answers "not one" for.
677 fn alone(&self) -> bool {
678 self.clips.len() + self.subs.len() < 2
679 }
680}
681
682/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
683#[derive(Clone, Copy, PartialEq, Eq, Debug)]
684pub enum Edge {
685 /// Its first timeline frame; moving it changes where in the source the clip
686 /// starts reading, so the picture behind the edge slides with it.
687 Start,
688 /// One past its last timeline frame; moving it only says how much of the
689 /// source to keep.
690 End,
691}
692
693/// What a lane holds over one stretch of the timeline: either a placed clip or
694/// a gap. Returned already trimmed to the position it was asked about, so a
695/// caller can hand `len` straight to a decoder (or to a black-frame generator).
696#[derive(Clone, Copy, PartialEq, Eq, Debug)]
697pub struct Span {
698 /// Timeline frame the span starts at.
699 pub start: u32,
700 /// Frames it covers; `>= 1`.
701 pub len: u32,
702 /// `(source index, first source frame)`, or `None` for a gap -- which the
703 /// engine renders as black frames and as silence.
704 pub from: Option<(usize, u32)>,
705 /// The rate the clip this came off plays at ([`Clip::speed`]);
706 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
707 /// timeline frames whatever it says -- the speed is how many *source* frames
708 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
709 /// come back to the timeline.
710 pub speed: Speed,
711}
712
713impl Span {
714 /// One past the last timeline frame it covers.
715 pub fn end(&self) -> u32 {
716 self.start + self.len
717 }
718
719 /// How many source frames it reads: what a decoder is asked for and how wide
720 /// an audio window is. `len` at real time, and the one arithmetic both the
721 /// picture and the sound go through, so they cannot disagree about where a
722 /// speeded clip ends.
723 pub fn source_len(&self) -> u32 {
724 match self.from {
725 // The last timeline frame's own source frame is the last one needed
726 // -- never one more, which at a slow rate would read a frame the
727 // next clip owns and at a fast one would decode a picture nothing
728 // shows.
729 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
730 None => self.len,
731 }
732 }
733
734 /// Where a source frame of this span lands on the timeline: the stamp
735 /// playback puts on a decoded frame, through the ceil half of the pair
736 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
737 /// frame, so a frame before it stamps at the span's start.
738 pub fn timeline_at(&self, source_frame: u32) -> u32 {
739 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
740 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
741 }
742}
743
744/// What one speeded audio segment asks of the worker: how many source frames to
745/// consume per output frame, and how many seconds of timeline it has to fill.
746/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
747/// resampling at all.
748#[derive(Clone, Copy, PartialEq, Debug)]
749pub struct Stretch {
750 /// Source frames per output frame -- the speed as a multiplier.
751 pub step: f64,
752 /// What the segment owes the timeline, which is what it is padded or
753 /// trimmed to.
754 pub timeline_secs: f64,
755}
756
757/// What a save writes and a load takes back: the sources, every lane in
758/// display order with its kind, and the equalizer and colour tables their clips
759/// index into -- [`Project::without_orphan_sources`] out,
760/// [`Project::from_parts`] in.
761pub type Parts = (
762 Vec<Source>,
763 Vec<(LaneKind, Vec<Clip>)>,
764 Vec<EqParams>,
765 Vec<ColorParams>,
766 Vec<TransformParams>,
767);
768
769/// How many undo steps a project keeps. One gesture is one step, so 100 is past
770/// any chain a person walks back by hand, and the oldest step is dropped rather
771/// than the history growing without end: a snapshot is the whole lane list, so
772/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
773/// that grows for as long as the session lasts.
774const HISTORY_CAP: usize = 100;
775
776/// The edit list plus its undo history.
777#[derive(Clone, Debug)]
778pub struct Project {
779 /// Append-only: never popped, never reordered. See the module docs.
780 sources: Vec<Source>,
781 /// In display order, which is the order [`Lane::ord`] counts in: the nth
782 /// lane of a kind here is that kind's `ord` n. Never empty.
783 lanes: Vec<LaneData>,
784 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
785 eq: Vec<EqParams>,
786 /// The same, for [`Clip::color`].
787 color: Vec<ColorParams>,
788 /// The same, for [`Clip::transform`].
789 transform: Vec<TransformParams>,
790 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
791 /// whole lane list, so adding a lane undoes as well. Bounded by
792 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
793 history: Vec<Vec<LaneData>>,
794 /// Never rolled back by an undo: an id retired by an undone split must not
795 /// come back and group two clips that were never together.
796 next_link: u32,
797 /// The subtitle tracks this timeline shows, in the order they were added.
798 /// Not in the lane list and not in the history snapshots, for the reason
799 /// the limiter is not: which subtitles a project carries is a setting on
800 /// it, and it is saved as a *reference* to the file the cues came out of
801 /// ([`crate::subtitle`]).
802 subtitles: Vec<SubtitleTrack>,
803 /// The master limiter every lane's sound is summed *through*
804 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
805 /// is what the history snapshots hold: it is a setting on the mix, like the
806 /// project's resolution is a setting on the picture, and neither is an undo
807 /// step.
808 limiter: Limiter,
809 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
810 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
811 /// the resolution, and not in the lane snapshots for the same reason.
812 tone: crate::tonemap::Preset,
813}
814
815impl Project {
816 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
817 /// grouped -- the state of a freshly opened video, where the timeline is the
818 /// source. `frame_count` of 0 would break the never-empty invariant, so it
819 /// is clamped to one frame.
820 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
821 let clip = Clip {
822 start: 0,
823 in_frame: 0,
824 out_frame: frame_count.max(1),
825 source: 0,
826 link: Some(0),
827 eq: None,
828 color: None,
829 transform: None,
830 fit: FitPolicy::default(),
831 speed: Speed::NORMAL,
832 };
833 Self {
834 // A file is opened on its first audio stream: nothing has picked
835 // one yet, and every file with audio at all has that one.
836 sources: vec![Source::new(path, 0)],
837 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
838 eq: Vec::new(),
839 color: Vec::new(),
840 transform: Vec::new(),
841 history: Vec::new(),
842 next_link: 1,
843 subtitles: Vec::new(),
844 limiter: Limiter::default(),
845 tone: crate::tonemap::Preset::default(),
846 }
847 }
848
849 /// A project rebuilt from a saved edit list -- the load half of
850 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
851 /// an `ord` is a lane's position among the lanes of that kind, exactly as
852 /// [`Project::lanes`] hands them back. History is *not* saved, so
853 /// [`Project::undo`] is `false` until the first edit of the new session.
854 /// This is the one door untrusted parts come in through, so every invariant
855 /// every other constructor keeps is checked here, by name and in release:
856 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
857 /// or a colour) that is not there, a clip whose end overflows, a lane that is
858 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
859 /// below.
860 ///
861 /// A project whose lanes are all *empty* is not among them: an emptied
862 /// timeline is a project like any other -- it plays black and silent, it
863 /// saves, and it loads back. What a project cannot be is laneless, because
864 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
865 /// handle indexes into.
866 pub fn from_parts(
867 sources: Vec<Source>,
868 lanes: Vec<(LaneKind, Vec<Clip>)>,
869 eq: Vec<EqParams>,
870 color: Vec<ColorParams>,
871 transform: Vec<TransformParams>,
872 ) -> crate::Result<Self> {
873 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
874 return Err(format!("eq {bad} holds a band that is not a finite number").into());
875 }
876 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
877 return Err(format!("color {bad} holds a value that is not a finite number").into());
878 }
879 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
880 return Err(format!("transform {bad} holds a value that is not a finite number").into());
881 }
882 if lanes.is_empty() {
883 return Err("no lanes at all: that is not a project".into());
884 }
885 let lanes: Vec<LaneData> = lanes
886 .into_iter()
887 .map(|(kind, clips)| LaneData::new(kind, clips))
888 .collect();
889 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
890 let name = lane.label();
891 // A subtitle lane carries words and never a picture
892 // ([`LaneKind::Subtitle`]); a file that puts one there names a
893 // source on a lane that has nothing to play it with, and every
894 // media path below would then read a clip off a lane it does not
895 // know about.
896 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
897 return Err(format!(
898 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
899 data.clips.len()
900 )
901 .into());
902 }
903 for c in &data.clips {
904 if c.out_frame <= c.in_frame {
905 return Err(format!(
906 "{name} clip at {} plays the empty range [{}, {})",
907 c.start, c.in_frame, c.out_frame
908 )
909 .into());
910 }
911 if c.source >= sources.len() {
912 return Err(format!(
913 "{name} clip at {} names source {} of {}",
914 c.start,
915 c.source,
916 sources.len()
917 )
918 .into());
919 }
920 if c.start.checked_add(c.frames()).is_none() {
921 return Err(format!(
922 "{name} clip at {} runs past the last frame there is",
923 c.start
924 )
925 .into());
926 }
927 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
928 return Err(format!(
929 "{name} clip at {} names eq {} of {}",
930 c.start,
931 c.eq.unwrap_or_default(),
932 eq.len()
933 )
934 .into());
935 }
936 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
937 return Err(format!(
938 "{name} clip at {} names color {} of {}",
939 c.start,
940 c.color.unwrap_or_default(),
941 color.len()
942 )
943 .into());
944 }
945 if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) {
946 return Err(format!(
947 "{name} clip at {} names transform {} of {}",
948 c.start,
949 c.transform.unwrap_or_default(),
950 transform.len()
951 )
952 .into());
953 }
954 }
955 if !sorted_disjoint(&data.clips) {
956 return Err(format!("the {name} lane is out of order or overlaps itself").into());
957 }
958 }
959 links_are_consistent(&lanes)?;
960 // The counter sits past every id the file names, on either of a lane's
961 // lists: a v16 caption may carry the highest link there is, and a
962 // re-issued id would silently group it with the next placement that
963 // asks for one -- the loader refusing a save the editor just wrote.
964 let next_link = lanes
965 .iter()
966 .flat_map(|l| {
967 let clips = l.clips.iter().filter_map(|c| c.link);
968 let subs = l.subs.iter().filter_map(|s| s.link);
969 clips.chain(subs)
970 })
971 .max()
972 // Saturating so a crafted file cannot make the counter wrap: at the
973 // ceiling ids stop being fresh, which loses grouping, not memory.
974 .map_or(0, |m| m.saturating_add(1));
975 Ok(Self {
976 sources: sources
977 .iter()
978 .map(|s| Source::new(&s.path, s.audio_stream))
979 .collect(),
980 lanes,
981 eq,
982 color,
983 transform,
984 history: Vec::new(),
985 next_link,
986 subtitles: Vec::new(),
987 limiter: Limiter::default(),
988 tone: crate::tonemap::Preset::default(),
989 })
990 }
991
992 /// The first video lane -- what an export renders and what a single-lane
993 /// caller still means by "the clips".
994 pub fn clips(&self) -> &[Clip] {
995 self.lane(Lane::V1)
996 }
997
998 /// The clips of `lane`, or nothing at all for a lane that is not there.
999 pub fn lane(&self, lane: Lane) -> &[Clip] {
1000 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1001 }
1002
1003 /// Every lane's handle, in display order -- what a walk over "all lanes"
1004 /// iterates, and what a front-end lays out top to bottom.
1005 pub fn lanes(&self) -> Vec<Lane> {
1006 handles(&self.lanes)
1007 }
1008
1009 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1010 /// for every `ord` below it, and none at or above it.
1011 pub fn lane_count(&self, kind: LaneKind) -> usize {
1012 self.lanes.iter().filter(|l| l.kind == kind).count()
1013 }
1014
1015 /// Appends an empty lane of `kind` and hands back its handle. One undo
1016 /// step, because the lane list is state a front-end shows: an added lane
1017 /// that could not be taken back would be the one edit with no way out.
1018 /// Nothing plays differently until something is placed on it.
1019 ///
1020 /// An empty lane is a lane like any other -- so is a whole project of them
1021 /// ([`Project::from_parts`]); nothing plays until something is placed.
1022 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1023 self.snapshot();
1024 self.lanes.push(LaneData::new(kind, Vec::new()));
1025 Lane::new(kind, self.lane_count(kind) - 1)
1026 }
1027
1028 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1029 /// one undo step like it, which restores the lane where it stood.
1030 ///
1031 /// Refused, changing nothing, while the lane holds anything: the refusal
1032 /// names the clips (file and first frame), because a track removal that
1033 /// deleted takes with it would be the one edit nobody sees coming. Refused
1034 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1035 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1036 /// kind and *skips* a kind that is not there), so a project without one
1037 /// would swallow half of every file dropped on it, silently.
1038 ///
1039 /// The lanes below it move up one `ord`, so a handle a caller was holding
1040 /// (a selection, an open card) names the lane after it from here on -- the
1041 /// one thing a front-end owes this call.
1042 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1043 let Some(i) = self.index(lane) else {
1044 return Err(format!("there is no {} to remove", lane.label()).into());
1045 };
1046 // A subtitle lane is not in that rule: nothing lands on one by itself
1047 // -- a project starts without any and one is added when a caption is --
1048 // so the last of them comes off like any other empty track.
1049 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1050 return Err(format!(
1051 "{} is the only {} track: every import lands on it",
1052 lane.label(),
1053 match lane.kind {
1054 LaneKind::Video => "video",
1055 LaneKind::Audio => "audio",
1056 // Unreachable while the guard above lets the last subtitle
1057 // lane go, and its own word here so the sentence stays true
1058 // if that rule is ever relaxed.
1059 LaneKind::Subtitle => "subtitle",
1060 }
1061 )
1062 .into());
1063 }
1064 if !self.lanes[i].subs.is_empty() {
1065 // Three names and a count, exactly as the clips below get: the way
1066 // out of the refusal is the drag, so the words say so.
1067 let named: Vec<String> = self.lanes[i]
1068 .subs
1069 .iter()
1070 .take(3)
1071 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1072 .collect();
1073 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1074 0 => String::new(),
1075 n => format!(" and {n} more"),
1076 };
1077 return Err(format!(
1078 "{} still holds {}{rest}: delete those captions (or drag them to \
1079 another track) first",
1080 lane.label(),
1081 named.join(", ")
1082 )
1083 .into());
1084 }
1085 let clips = &self.lanes[i].clips;
1086 if !clips.is_empty() {
1087 // Three names and a count: a lane can hold forty clips and a
1088 // refusal nobody reads to the end says nothing at all.
1089 let named: Vec<String> = clips
1090 .iter()
1091 .take(3)
1092 .map(|c| {
1093 let name = self.sources.get(c.source).map_or_else(
1094 || format!("source {}", c.source),
1095 |s| s.path.display().to_string(),
1096 );
1097 format!("{name} at frame {}", c.start)
1098 })
1099 .collect();
1100 let rest = match clips.len().saturating_sub(named.len()) {
1101 0 => String::new(),
1102 n => format!(" and {n} more"),
1103 };
1104 return Err(format!(
1105 "{} still holds {}{rest}: delete those clips (or drag them to \
1106 another track) first",
1107 lane.label(),
1108 named.join(", ")
1109 )
1110 .into());
1111 }
1112 self.snapshot();
1113 self.lanes.remove(i);
1114 Ok(())
1115 }
1116
1117 /// Moves `lane` to display position `to` -- an index into
1118 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1119 /// the handle it answers to from now on. `None`, changing nothing and
1120 /// snapshotting nothing, for a lane that is not there, a position that is
1121 /// not, and a lane already standing in it.
1122 ///
1123 /// The whole track travels: its clips, its gain, its kind. Nothing is
1124 /// remapped, so no take changes lane and no group is broken -- this is the
1125 /// *order* of the lanes and nothing else, which is why one call is one undo
1126 /// step like an add or a removal.
1127 ///
1128 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1129 /// last video lane covering a frame, so moving one video lane past another
1130 /// changes which picture wins, in the preview and in an export alike. The
1131 /// audio lanes are summed and their sum does not care about order, so an
1132 /// audio track moved among the video ones is a rearrangement of the screen
1133 /// alone.
1134 ///
1135 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1136 /// position among the lanes of that kind), so a lane that crosses one of
1137 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1138 /// `V1`, clips and all -- while one that crosses only lanes of the other
1139 /// kind keeps its name. That is the returned handle: unchanged means every
1140 /// handle a caller holds still names the track it named before.
1141 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1142 let i = self.index(lane)?;
1143 if to >= self.lanes.len() || to == i {
1144 return None;
1145 }
1146 self.snapshot();
1147 let data = self.lanes.remove(i);
1148 self.lanes.insert(to, data);
1149 Some(handles(&self.lanes)[to])
1150 }
1151
1152 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1153 /// not there. The one place a handle becomes a position.
1154 fn index(&self, lane: Lane) -> Option<usize> {
1155 self.lanes
1156 .iter()
1157 .enumerate()
1158 .filter(|(_, l)| l.kind == lane.kind)
1159 .map(|(i, _)| i)
1160 .nth(lane.ord)
1161 }
1162
1163 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1164 let i = self.index(lane)?;
1165 Some(&mut self.lanes[i].clips)
1166 }
1167
1168 /// The files the clips index into, in import order; index 0 is the file the
1169 /// project was opened with.
1170 pub fn sources(&self) -> &[Source] {
1171 &self.sources
1172 }
1173
1174 /// The same list in the `(path, stream)` shape the audio engine indexes
1175 /// into -- [`crate::AudioSession::open_multi_streams`] and
1176 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1177 /// was placed with is the stream that plays *and* the stream that exports.
1178 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1179 self.sources
1180 .iter()
1181 .map(|s| (s.path.clone(), s.audio_stream))
1182 .collect()
1183 }
1184
1185 /// Index for `path` played on `audio_stream`, appending it if it is new.
1186 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1187 /// by two paths imports once and two streams of one file are two sources.
1188 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1189 /// no history: a source entry alone changes nothing playable.
1190 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1191 let source = Source::new(path, audio_stream);
1192 match self.sources.iter().position(|s| *s == source) {
1193 Some(idx) => idx,
1194 None => {
1195 self.sources.push(source);
1196 self.sources.len() - 1
1197 }
1198 }
1199 }
1200
1201 /// Append a whole-file clip of `source` to the end of every *media* lane,
1202 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1203 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1204 /// come in through [`Project::add_subtitles`], which is the palette.
1205 ///
1206 /// One history snapshot, so an import is one undo step, and undoing it
1207 /// leaves the (harmless) source entry behind, because indexes are forever.
1208 /// Refused for an unknown source index.
1209 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1210 if source >= self.sources.len() {
1211 return false;
1212 }
1213 self.snapshot();
1214 let start = self.timeline_frames();
1215 let clip = Clip {
1216 start,
1217 in_frame: 0,
1218 out_frame: frame_count.max(1),
1219 source,
1220 link: Some(self.new_link()),
1221 eq: None,
1222 color: None,
1223 fit: FitPolicy::default(),
1224 speed: Speed::NORMAL,
1225 };
1226 for data in self
1227 .lanes
1228 .iter_mut()
1229 .filter(|l| l.kind != LaneKind::Subtitle)
1230 {
1231 data.clips.push(clip);
1232 }
1233 true
1234 }
1235
1236 /// Drops a source entry -- the file a library row *is* -- and renumbers
1237 /// every clip that indexed past it, which is why this is more than a
1238 /// `Vec::remove`.
1239 ///
1240 /// Refused, changing nothing, while any clip still plays from it: the
1241 /// refusal names the lanes and how many clips each holds, so a caller can
1242 /// say what has to be deleted first. The *last* entry goes like any other
1243 /// -- a project may name no file at all, which is an empty library over an
1244 /// empty timeline (nothing can play, since a clip would have refused the
1245 /// removal). What a front-end does with that is its own decision: `edith`'s
1246 /// window goes back to the empty state it launches in, and
1247 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1248 /// refuses to write a project that names nothing, because no such file
1249 /// could be opened again.
1250 ///
1251 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1252 /// source index of its own -- a clipboard, which is the one thing outside
1253 /// this type that does -- has to fix it up or drop it, or a paste plays a
1254 /// different file. [`PlaybackSession::remove_source`] hands back the index
1255 /// that went for exactly that.
1256 ///
1257 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1258 /// snapshot older than the removal can name the very source being removed
1259 /// (delete a file's clips, then remove the file) and restoring it would
1260 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1261 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1262 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1263 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1264 /// exists) currently rules out.
1265 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1266 let Some(source) = self.sources.get(idx) else {
1267 return Err(format!("there is no source {idx} to remove").into());
1268 };
1269 let name = source.path.display().to_string();
1270 let used: Vec<String> = handles(&self.lanes)
1271 .into_iter()
1272 .zip(&self.lanes)
1273 .filter_map(
1274 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1275 0 => None,
1276 1 => Some(format!("{} (1 clip)", lane.label())),
1277 n => Some(format!("{} ({n} clips)", lane.label())),
1278 },
1279 )
1280 .collect();
1281 if !used.is_empty() {
1282 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1283 }
1284 self.sources.remove(idx);
1285 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1286 if c.source > idx {
1287 c.source -= 1;
1288 }
1289 }
1290 self.history.clear();
1291 Ok(())
1292 }
1293
1294 /// The sources a clip actually names, with the clips reindexed onto them
1295 /// -- what a save writes. Indexes are forever *inside* a session (see
1296 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1297 /// entry behind; writing that orphan to a project file would let a file
1298 /// nothing plays refuse a future load. New indexes are assigned in order of
1299 /// first use -- lane by lane, in display order -- so the same project always
1300 /// emits the same bytes.
1301 ///
1302 /// Every lane comes out, in display order and with its kind: that is what a
1303 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1304 /// takes back.
1305 ///
1306 /// The equalizer and colour tables are pruned the same way and for the same
1307 /// reason: an undone [`set_eq`](Project::set_eq) or
1308 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1309 /// and this is the one moment they can go -- the indexes that survive it are
1310 /// only the ones a clip names.
1311 ///
1312 /// One exception, and it is the emptied timeline's: a project no clip plays
1313 /// from still keeps its first source, if it has one. A file is what a
1314 /// reopened project scaffolds itself from -- the frame rate is written
1315 /// nowhere else -- so a save that pruned the last of them would write a
1316 /// project that cannot be loaded back at all.
1317 ///
1318 /// What comes out is *not* ordered by anything a reader may assume: first
1319 /// use, lane by lane, means the entry at index 0 can be a still or a song
1320 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1321 /// picks its rate and its audio reference by what a source *is*, never by
1322 /// where it sits.
1323 pub fn without_orphan_sources(&self) -> Parts {
1324 let mut moved = vec![None; self.sources.len()];
1325 let mut sources = Vec::new();
1326 let mut moved_eq = vec![None; self.eq.len()];
1327 let mut eq = Vec::new();
1328 let mut moved_color = vec![None; self.color.len()];
1329 let mut color = Vec::new();
1330 let mut moved_transform = vec![None; self.transform.len()];
1331 let mut transform = Vec::new();
1332 let mut lanes = self.lanes.clone();
1333 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1334 let old = c.source;
1335 c.source = match moved[old] {
1336 Some(new) => new,
1337 None => {
1338 sources.push(self.sources[old].clone());
1339 moved[old] = Some(sources.len() - 1);
1340 sources.len() - 1
1341 }
1342 };
1343 if let Some(old) = c.eq.map(usize::from) {
1344 c.eq = Some(match moved_eq[old] {
1345 Some(new) => new,
1346 None => {
1347 eq.push(self.eq[old].clone());
1348 let new = (eq.len() - 1) as u16;
1349 moved_eq[old] = Some(new);
1350 new
1351 }
1352 });
1353 }
1354 if let Some(old) = c.color.map(usize::from) {
1355 c.color = Some(match moved_color[old] {
1356 Some(new) => new,
1357 None => {
1358 color.push(self.color[old]);
1359 let new = (color.len() - 1) as u16;
1360 moved_color[old] = Some(new);
1361 new
1362 }
1363 });
1364 }
1365 if let Some(old) = c.transform.map(usize::from) {
1366 c.transform = Some(match moved_transform[old] {
1367 Some(new) => new,
1368 None => {
1369 transform.push(self.transform[old]);
1370 let new = (transform.len() - 1) as u16;
1371 moved_transform[old] = Some(new);
1372 new
1373 }
1374 });
1375 }
1376 }
1377 if sources.is_empty() {
1378 sources.extend(self.sources.first().cloned());
1379 }
1380 (
1381 sources,
1382 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1383 // comes out for one is an empty list, and its *place* in the display
1384 // order is what a save writes it for. What is on it travels beside
1385 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1386 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1387 eq,
1388 color,
1389 transform,
1390 )
1391 }
1392
1393 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1394 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1395 /// track moves by it, which is what makes it a different control from a
1396 /// clip's equalizer (one frequency range of one take) and from the master
1397 /// volume (what this machine monitors at, which no file carries).
1398 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1399 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1400 }
1401
1402 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1403 /// One undo step like every other edit -- it is in the lane list, so an
1404 /// undo restores it with the rest. `false`, and no history, for a lane that
1405 /// is not there, for a value that is not finite, and for one already set.
1406 ///
1407 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1408 /// a value nobody reads: words have no loudness, so a slider that appeared
1409 /// to move one would be a control with no effect. (A video lane's gain is
1410 /// meaningless in the same way but is kept settable: it is the pair `A1`
1411 /// carries for a take, and mixing reads it off the audio lane alone.)
1412 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1413 let Some(i) = self.index(lane) else {
1414 return false;
1415 };
1416 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1417 return false;
1418 }
1419 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1420 if self.lanes[i].gain_db == db {
1421 return false;
1422 }
1423 self.snapshot();
1424 self.lanes[i].gain_db = db;
1425 true
1426 }
1427
1428 /// Every lane's volume in dB, in display order -- what a save writes,
1429 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1430 ///
1431 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1432 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1433 /// one): a save zips the two lists, so a lane that is in one and not the
1434 /// other would hand every track below it the volume of the track above.
1435 pub fn lane_gains(&self) -> Vec<f32> {
1436 self.lanes.iter().map(|l| l.gain_db).collect()
1437 }
1438
1439 /// What is placed on every lane, in display order and in step with
1440 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1441 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1442 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1443 ///
1444 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1445 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1446 /// clip's source there is no orphan to prune and no index to move.
1447 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1448 self.lanes.iter().map(|l| l.subs.clone()).collect()
1449 }
1450
1451 /// The placements a *load* puts back, one list per lane in display order --
1452 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1453 /// same reason. Called *after*
1454 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1455 /// names.
1456 ///
1457 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1458 /// like it, by name and in release, because it is the same untrusted file:
1459 /// a placement on a lane that is not a subtitle lane, an empty span or an
1460 /// empty window, a track the palette does not have, a span running past the
1461 /// last frame there is, and a lane that is out of order or overlaps itself
1462 /// ([`place_sub`] refuses every one of those on the live timeline).
1463 ///
1464 /// [`place_sub`]: Project::place_sub
1465 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1466 let names = handles(&self.lanes);
1467 let palette = self.subtitles.len();
1468 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1469 let name = lane.label();
1470 if list.is_empty() {
1471 continue;
1472 }
1473 if data.kind != LaneKind::Subtitle {
1474 return Err(format!(
1475 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1476 subtitle track",
1477 list.len()
1478 )
1479 .into());
1480 }
1481 for s in &list {
1482 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1483 return Err(format!(
1484 "{name} caption at {} is empty: {} frames of [{}, {})",
1485 s.start, s.frames, s.in_us, s.out_us
1486 )
1487 .into());
1488 }
1489 if s.track >= palette {
1490 return Err(format!(
1491 "{name} caption at {} names subtitle track {} of {palette}",
1492 s.start, s.track
1493 )
1494 .into());
1495 }
1496 if s.start.checked_add(s.frames).is_none() {
1497 return Err(format!(
1498 "{name} caption at {} runs past the last frame there is",
1499 s.start
1500 )
1501 .into());
1502 }
1503 }
1504 if !subs_sorted_disjoint(&list) {
1505 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1506 }
1507 data.subs = list;
1508 // The counter also has to clear the ids these captions carry: this
1509 // is the door a load's placements come through, *after*
1510 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1511 // a hand-grouped caption may carry the highest id in the file.
1512 self.next_link = self.next_link.max(
1513 data.subs
1514 .iter()
1515 .filter_map(|s| s.link)
1516 .max()
1517 .map_or(0, |m| m.saturating_add(1)),
1518 );
1519 }
1520 Ok(self)
1521 }
1522
1523 /// The mix settings a *load* puts back: lane volumes in display order (a
1524 /// short list leaves the rest at unity) and the master limiter, both
1525 /// clamped as their setters clamp them.
1526 ///
1527 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1528 /// setters push an undo step, and a project that arrives one undo away from
1529 /// a state it was never in is a project whose first ctrl+z is a surprise.
1530 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1531 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1532 if db.is_finite() {
1533 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1534 }
1535 }
1536 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1537 self
1538 }
1539
1540 /// The HDR rendition a *load* puts back -- the same door
1541 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1542 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1543 self.tone = preset;
1544 self
1545 }
1546
1547 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1548 /// project setting, not a clip's: one picture, one look
1549 /// ([`crate::tonemap::Preset`]).
1550 pub fn tone(&self) -> crate::tonemap::Preset {
1551 self.tone
1552 }
1553
1554 /// Sets it. `false` for the one already in force, which is what keeps a
1555 /// re-pick of the current rendition from costing a reseek.
1556 ///
1557 /// corner-cut: not an undo step, for the reason the limiter and the project
1558 /// resolution are not -- it is not in the lane list the history snapshots.
1559 /// Upgrade path is the same one: a history entry holding the project's own
1560 /// settings beside the lanes.
1561 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1562 if self.tone == preset {
1563 return false;
1564 }
1565 self.tone = preset;
1566 true
1567 }
1568
1569 /// The subtitle tracks a *load* puts back, in the order they were saved --
1570 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1571 /// the same reason.
1572 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1573 self.subtitles = tracks;
1574 self
1575 }
1576
1577 /// What this timeline shows over the picture, in the order they were added:
1578 /// what a front-end lists and what a save writes.
1579 pub fn subtitles(&self) -> &[SubtitleTrack] {
1580 &self.subtitles
1581 }
1582
1583 /// Adds a track, unless the very same one -- same file, same track number
1584 /// inside it -- is already on the list. `false` for that repeat: importing
1585 /// the same `.srt` twice is one subtitle track, not two identical ones.
1586 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1587 if self
1588 .subtitles
1589 .iter()
1590 .any(|t| t.path == track.path && t.track == track.track)
1591 {
1592 return false;
1593 }
1594 self.subtitles.push(track.clone());
1595 true
1596 }
1597
1598 /// Takes the track at `idx` off the list -- what a row's own remove goes
1599 /// through, so whatever an import added can be taken back out. Refused by
1600 /// name for a row this project does not have, rather than a silent no-op:
1601 /// a front-end holding a stale index has picked the wrong row and needs to
1602 /// hear it.
1603 ///
1604 /// Every index past `idx` moves down by one, as [`remove_source`](
1605 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1606 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1607 /// it, or it names a different track afterwards. The placements on the
1608 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1609 /// index into this very list, so every one past `idx` is walked down with
1610 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1611 /// for its clips, for its reason.
1612 ///
1613 /// Refused, changing nothing, while anything placed on a subtitle lane
1614 /// plays *this* row: the placement would have to be deleted or retargeted,
1615 /// and either one is an edit nobody asked for. The refusal names the lane
1616 /// and the frame it is at, up to three of them --
1617 /// [`remove_source`](Project::remove_source) refuses the same way for the
1618 /// same silent corruption.
1619 ///
1620 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1621 /// history snapshots hold the lane list and subtitles are not on it
1622 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1623 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1624 /// door, which reads the subtitles of a file and nothing else -- and not a
1625 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1626 /// entry holding the project's own settings beside the lanes. The history
1627 /// is *cleared* rather than kept, as a source removal clears it: the
1628 /// snapshots hold the indexes as they were before the reindex, so an undo
1629 /// into one would put every placement past `idx` on the wrong track.
1630 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1631 if idx >= self.subtitles.len() {
1632 return Err(format!("there is no subtitle track {idx} to remove").into());
1633 }
1634 let placed: Vec<String> = handles(&self.lanes)
1635 .into_iter()
1636 .zip(&self.lanes)
1637 .flat_map(|(lane, data)| {
1638 data.subs
1639 .iter()
1640 .filter(move |s| s.track == idx)
1641 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1642 })
1643 .take(3)
1644 .collect();
1645 if !placed.is_empty() {
1646 return Err(format!(
1647 "{} is on the timeline ({}): delete those clips first",
1648 self.track_name(idx),
1649 placed.join(", ")
1650 )
1651 .into());
1652 }
1653 self.subtitles.remove(idx);
1654 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1655 if s.track > idx {
1656 s.track -= 1;
1657 }
1658 }
1659 self.history.clear();
1660 Ok(())
1661 }
1662
1663 /// What a refusal calls a palette row: the name the panel shows, and the
1664 /// index alone for a row that is not there.
1665 fn track_name(&self, track: usize) -> String {
1666 self.subtitles
1667 .get(track)
1668 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1669 }
1670
1671 /// The subtitle lanes in display order -- what a front-end lays out and
1672 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1673 /// [`audio_lanes`](Project::audio_lanes).
1674 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1675 self.lanes()
1676 .into_iter()
1677 .filter(|l| l.kind == LaneKind::Subtitle)
1678 .collect()
1679 }
1680
1681 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1682 /// for a subtitle track, and empty for every other lane and for one that is
1683 /// not there.
1684 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1685 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1686 }
1687
1688 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1689 /// twin, with one deliberate difference: it **refuses** an overlap instead
1690 /// of overwriting what it lands on.
1691 ///
1692 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1693 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1694 /// carries is a *window of a track* and where the hand let go, and the
1695 /// second of those is the argument. So a caller builds the placement once
1696 /// (from the palette row it dragged) and drops it at as many frames as it
1697 /// likes without rewriting the field each time.
1698 ///
1699 /// A picture placed over a picture hides it and the hidden one is still
1700 /// there to drag back out; two captions in one frame are two lines nobody
1701 /// asked to stack, and the words that lost are gone from the screen with
1702 /// nothing to show for it. So the refusal names the placement in the way,
1703 /// and the caller picks another frame or another lane -- which is what a
1704 /// second subtitle lane is for.
1705 ///
1706 /// One undo step on success, and none on any refusal: an empty window or an
1707 /// empty span, a track the palette does not have
1708 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1709 /// subtitle lane, a span that would run past the last frame there is, and
1710 /// the overlap above.
1711 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1712 if lane.kind != LaneKind::Subtitle {
1713 return Err(format!(
1714 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1715 the others",
1716 lane.label()
1717 )
1718 .into());
1719 }
1720 let Some(i) = self.index(lane) else {
1721 return Err(format!("there is no {} to place on", lane.label()).into());
1722 };
1723 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1724 return Err(format!(
1725 "that placement is empty: {} frames of [{}, {})",
1726 sub.frames, sub.in_us, sub.out_us
1727 )
1728 .into());
1729 }
1730 if sub.track >= self.subtitles.len() {
1731 return Err(format!(
1732 "it names subtitle track {} of {}",
1733 sub.track,
1734 self.subtitles.len()
1735 )
1736 .into());
1737 }
1738 // The placement belongs to no group, for [`place`]'s reason: a caption
1739 // dragged out of the palette arrives alone, and grouping it with what
1740 // is under it is a hand's decision ([`Project::group_all`]).
1741 let sub = SubClip {
1742 start: at,
1743 link: None,
1744 ..sub
1745 };
1746 if at.checked_add(sub.frames).is_none() {
1747 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1748 }
1749 if let Some(other) = self.lanes[i]
1750 .subs
1751 .iter()
1752 .find(|o| o.end() > sub.start && o.start < sub.end())
1753 {
1754 return Err(format!(
1755 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1756 on another subtitle track",
1757 lane.label(),
1758 other.start,
1759 other.start,
1760 other.end()
1761 )
1762 .into());
1763 }
1764 self.snapshot();
1765 let subs = &mut self.lanes[i].subs;
1766 let idx = subs.partition_point(|o| o.start < sub.start);
1767 subs.insert(idx, sub);
1768 debug_assert!(subs_sorted_disjoint(subs));
1769 Ok(())
1770 }
1771
1772 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1773 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1774 /// refused an overlap where that one clamps to it, for
1775 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1776 /// still and no picture under it that a landing would hide, so "as far as
1777 /// it goes" would silently be a frame nobody named.
1778 ///
1779 /// A caption *in* a group drags the group: one delta for every member --
1780 /// its clips and its other captions -- clamped to the room each of them
1781 /// has, exactly as a clip's drag always has. That is the point of putting
1782 /// a caption in a group: the words go where the picture goes.
1783 ///
1784 /// The window travels untouched: a caption dragged later says the same
1785 /// words later, exactly as a clip dragged later plays the same pictures
1786 /// later.
1787 ///
1788 /// One undo step on success; nothing changed and no step on a refusal --
1789 /// an index that is not there, a lane that is not a subtitle lane or is not
1790 /// there, and (for a caption in no group) an overlap. A drop that changes
1791 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1792 /// up and put it back has done nothing wrong, and a front-end showing every
1793 /// `Err` would say so.
1794 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1795 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1796 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1797 };
1798 if to.kind != LaneKind::Subtitle {
1799 return Err(format!(
1800 "{} is not a subtitle track: a caption cannot play on it",
1801 to.label()
1802 )
1803 .into());
1804 }
1805 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1806 return Err(format!("there is no {} to move onto", to.label()).into());
1807 };
1808 if (here, start) == (dest, sub.start) {
1809 // A pick-up-put-back: the drag ended where it began, which is not a
1810 // mistake to name -- `Ok`, and no undo step, because nothing
1811 // changed. A refusal here would toast a hand that did nothing.
1812 return Ok(());
1813 }
1814 if start.checked_add(sub.frames).is_none() {
1815 return Err(
1816 format!("a placement at frame {start} runs past the last frame there is").into(),
1817 );
1818 }
1819 // A grouped caption carries its group, clamped to the room the whole
1820 // group has rather than refused ([`Project::move_room]) -- one drag, one
1821 // delta, one undo step.
1822 let members = self.group_of(from, idx).expect("the subtitle was found");
1823 if !members.alone() {
1824 if members
1825 .subs
1826 .iter()
1827 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1828 {
1829 return Err(format!(
1830 "a group is one caption per track: {} already carries this group",
1831 to.label()
1832 )
1833 .into());
1834 }
1835 let want = i64::from(start) - i64::from(sub.start);
1836 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1837 return Err(format!(
1838 "another placement already covers those frames on {}",
1839 to.label()
1840 )
1841 .into());
1842 };
1843 let delta = want.clamp(lo, hi);
1844 self.snapshot();
1845 for &(l, i) in &members.clips {
1846 let c = &mut self.lanes[l].clips[i];
1847 c.start = (i64::from(c.start) + delta) as u32;
1848 }
1849 for &(l, i) in &members.subs {
1850 let s = &mut self.lanes[l].subs[i];
1851 s.start = (i64::from(s.start) + delta) as u32;
1852 }
1853 let moved = self.lanes[here].subs.remove(idx);
1854 let subs = &mut self.lanes[dest].subs;
1855 let at = subs.partition_point(|o| o.start < moved.start);
1856 subs.insert(at, moved);
1857 debug_assert!(subs_sorted_disjoint(subs));
1858 debug_assert!(members
1859 .clips
1860 .iter()
1861 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1862 return Ok(());
1863 }
1864 let moved = SubClip { start, ..sub };
1865 if let Some(other) = self.lanes[dest]
1866 .subs
1867 .iter()
1868 .enumerate()
1869 .find(|&(j, o)| {
1870 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
1871 })
1872 .map(|(_, o)| *o)
1873 {
1874 return Err(format!(
1875 "the {} subtitle at frame {} already covers [{}, {})",
1876 to.label(),
1877 other.start,
1878 other.start,
1879 other.end()
1880 )
1881 .into());
1882 }
1883 self.snapshot();
1884 self.lanes[here].subs.remove(idx);
1885 let subs = &mut self.lanes[dest].subs;
1886 let at = subs.partition_point(|o| o.start < moved.start);
1887 subs.insert(at, moved);
1888 debug_assert!(subs_sorted_disjoint(subs));
1889 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
1890 Ok(())
1891 }
1892
1893 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
1894 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
1895 /// pulling an edge past what is legal means "as far as it goes".
1896 ///
1897 /// The window follows the edge, in the seconds the frames are worth at
1898 /// `fps`: a head pulled in starts the caption later *in its track* (the
1899 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
1900 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
1901 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
1902 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
1903 /// needed here and nowhere else in this file, because a trim is the only
1904 /// edit that changes a *duration*.
1905 ///
1906 /// The walls: one frame always survives, an edge never crosses the
1907 /// neighbouring subtitle on its own lane, a head never walks back past the
1908 /// track's own start (`in_us` of 0), and a tail never runs past the last
1909 /// cue the track has -- which is the source length a media trim needs a
1910 /// caller's table for, and which this one can simply read.
1911 ///
1912 /// `Err`, with nothing changed and no undo step, for an index that is not
1913 /// there and an unusable `fps`. An edge that ends up where it already was
1914 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
1915 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
1916 /// reason: a drag that stops at a wall is not a mistake to report.
1917 pub fn trim_sub(
1918 &mut self,
1919 lane: Lane,
1920 idx: usize,
1921 edge: Edge,
1922 to: u32,
1923 fps: f64,
1924 ) -> crate::Result<()> {
1925 if !(fps.is_finite() && fps > 0.0) {
1926 return Err(format!("{fps} is not a frame rate to trim against").into());
1927 }
1928 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
1929 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
1930 };
1931 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
1932 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
1933 };
1934 let to = to.clamp(lo, hi);
1935 let at = match edge {
1936 Edge::Start => sub.start,
1937 Edge::End => sub.end(),
1938 };
1939 if to == at {
1940 // The edge is where it was asked to go -- either the hand did not
1941 // move it, or the clamp above stopped it at a wall it was already
1942 // standing against. Both are a drag that changed nothing: `Ok`, no
1943 // undo step, and no toast for a box that simply stopped moving.
1944 return Ok(());
1945 }
1946 self.snapshot();
1947 let members = self.group_of(lane, idx).expect("the subtitle was found");
1948 let i = self.index(lane).expect("the subtitle was found on it");
1949 let s = &mut self.lanes[i].subs[idx];
1950 match edge {
1951 // The words that stay are the words that were there, so the window
1952 // moves with the head -- a trim, not a slip.
1953 Edge::Start => {
1954 // Clamped to a window that is still a window: the walls above
1955 // are frames and the rounding between the two clocks is not
1956 // exact, and neither is a caller's hand-built placement.
1957 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
1958 .clamp(0, s.out_us - 1);
1959 s.frames = s.end() - to;
1960 s.start = to;
1961 }
1962 Edge::End => {
1963 s.out_us =
1964 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
1965 s.frames = to - s.start;
1966 }
1967 }
1968 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
1969 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
1970 // A caption in a group drags its group's edge with it, exactly as a
1971 // clip's trim does: one delta, each member clamped to its own room.
1972 // No source table to grow by, which only tightens how far a member may
1973 // follow -- never whether it may.
1974 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
1975 Ok(())
1976 }
1977
1978 /// How far that edge may travel, `(first, last)` timeline frame inclusive
1979 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
1980 /// drawing the box during a drag asks. `None` for an index that is not
1981 /// there.
1982 pub fn trim_sub_room(
1983 &self,
1984 lane: Lane,
1985 idx: usize,
1986 edge: Edge,
1987 fps: f64,
1988 ) -> Option<(u32, u32)> {
1989 let subs = self.sub_lane(lane);
1990 let s = *subs.get(idx)?;
1991 // How many timeline frames a stretch of the track is worth, which is
1992 // what turns its two walls -- its own start, and its last cue -- into
1993 // frames. A rate that is not a rate leaves the window where it is.
1994 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
1995 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
1996 false => 0,
1997 };
1998 Some(match edge {
1999 Edge::Start => (
2000 s.start
2001 .saturating_sub(frames_of(s.in_us))
2002 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2003 s.end() - 1,
2004 ),
2005 Edge::End => {
2006 // Out to the end of the track it reads, and never over the
2007 // subtitle behind it. A track the palette no longer has (or one
2008 // with no cues at all) may not grow, exactly as a source with no
2009 // entry in a media trim's table may not.
2010 let track_end = self
2011 .subtitles
2012 .get(s.track)
2013 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2014 .unwrap_or(s.out_us);
2015 (
2016 s.start + 1,
2017 s.start
2018 .saturating_add(frames_of(track_end - s.in_us).max(1))
2019 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2020 )
2021 }
2022 })
2023 }
2024
2025 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2026 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2027 /// `false` for an index that is not there (which a lane that is not a
2028 /// subtitle lane always is).
2029 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2030 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2031 return false;
2032 };
2033 self.snapshot();
2034 self.lanes[i].subs.remove(idx);
2035 true
2036 }
2037
2038 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2039 /// window of its track, clipped to that window and shifted to where the
2040 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2041 /// carried through the picture's spans -- this is its twin for a track that
2042 /// is placed on a lane of its own, and it is what a preview draws and what
2043 /// an export of the lane would write.
2044 ///
2045 /// Cut, not stretched: a cue half inside the window keeps the half that is
2046 /// inside, and a cue wholly outside it is gone -- the same rule the media
2047 /// spans follow. `fps` is the timeline's rate, needed here because a
2048 /// placement's *position* is in frames while its words are in microseconds.
2049 ///
2050 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2051 /// of their cues, no file opened), which is how a front-end asks it.
2052 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2053 if !(fps.is_finite() && fps > 0.0) {
2054 return Vec::new();
2055 }
2056 let mut out = Vec::new();
2057 for s in self.sub_lane(lane) {
2058 let Some(track) = self.subtitles.get(s.track) else {
2059 // A placement whose track was taken off the palette
2060 // ([`Project::remove_subtitles`]) shows nothing rather than
2061 // showing another track's words.
2062 continue;
2063 };
2064 // Where the placement's own first microsecond lands on the
2065 // timeline, and how many microseconds of timeline one microsecond
2066 // of the window is worth: the placement's own proportion, which a
2067 // group's re-rate changes (the frames compress, the window does
2068 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2069 // every cue lands where it always did; at 2x the words cross the
2070 // screen in half the time, cue for cue.
2071 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2072 let onto = |t: i64| {
2073 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2074 };
2075 for cue in &track.cues {
2076 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2077 if b <= a {
2078 continue; // wholly outside the window this placement keeps
2079 }
2080 out.push(SubtitleCue {
2081 start_us: onto(a),
2082 end_us: onto(b),
2083 text: cue.text.clone(),
2084 image: cue.image.clone(),
2085 });
2086 }
2087 }
2088 // The placements come in timeline order, but two lanes' worth (or a
2089 // track whose cues a window reordered) do not.
2090 out.sort_by_key(|cue| cue.start_us);
2091 out
2092 }
2093
2094 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2095 /// lanes is multiplied by on its way into the mix: the same lanes in the
2096 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2097 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2098 /// the bit-exact path.
2099 pub fn audio_gains(&self) -> Vec<f32> {
2100 self.audio_lanes()
2101 .into_iter()
2102 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2103 .collect()
2104 }
2105
2106 /// The master limiter the mix is summed through. A project setting, not a
2107 /// clip's and not a lane's: there is one mix.
2108 pub fn limiter(&self) -> Limiter {
2109 self.limiter
2110 }
2111
2112 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2113 /// for a setting already in force.
2114 ///
2115 /// corner-cut: not an undo step, for the reason the project resolution is not
2116 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2117 /// lane list the history snapshots. Upgrade path is a history entry that
2118 /// holds the mix settings beside the lanes.
2119 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2120 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2121 if self.limiter == limiter {
2122 return false;
2123 }
2124 self.limiter = limiter;
2125 true
2126 }
2127
2128 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2129 /// plays flat (and for an index that is not there) -- what a feeder and an
2130 /// export ask before they build an [`crate::eq::EqState`].
2131 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2132 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2133 }
2134
2135 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2136 /// take them off. One undo step, like every other edit. `false` -- and no
2137 /// history -- for an index that is not there and for params holding a value
2138 /// that is not finite, which is the one thing the file format could not
2139 /// write and read back.
2140 ///
2141 /// Settings equal to ones already in the table share their entry, so a
2142 /// project that puts the same curve on twenty clips writes it once.
2143 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2144 if idx >= self.lane(lane).len() {
2145 return false;
2146 }
2147 let slot = match params {
2148 None => None,
2149 Some(params) => {
2150 if !finite(&params) {
2151 return false;
2152 }
2153 Some(match self.eq.iter().position(|p| *p == params) {
2154 Some(at) => at as u16,
2155 // corner-cut: the table is append-only within a session (see
2156 // the module docs) and `Clip::eq` is a u16, so the 65535th
2157 // *distinct* setting of one session is refused rather than
2158 // silently aliased. Upgrade path if a UI ever drags a slider
2159 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2160 // snapshot the table into the history and compact it here.
2161 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2162 None => {
2163 self.eq.push(params);
2164 (self.eq.len() - 1) as u16
2165 }
2166 })
2167 }
2168 };
2169 self.snapshot();
2170 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2171 true
2172 }
2173
2174 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2175 /// ungraded (and for an index that is not there) -- what the renderer and
2176 /// the export ask before they call [`crate::color::apply_yuv`].
2177 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2178 self.color
2179 .get(usize::from(self.lane(lane).get(idx)?.color?))
2180 }
2181
2182 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2183 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2184 /// (and no history) for an index that is not there or a value that is not
2185 /// finite, and equal settings share a table entry.
2186 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2187 self.write_color(lane, idx, params, true)
2188 }
2189
2190 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2191 /// one pointer drag, whose first write (a plain `set_color`) already took the
2192 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2193 /// not one per pixel -- and undoing it lands where the hand picked it up.
2194 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2195 self.write_color(lane, idx, params, false)
2196 }
2197
2198 fn write_color(
2199 &mut self,
2200 lane: Lane,
2201 idx: usize,
2202 params: Option<ColorParams>,
2203 snapshot: bool,
2204 ) -> bool {
2205 if idx >= self.lane(lane).len() {
2206 return false;
2207 }
2208 let slot = match params {
2209 None => None,
2210 Some(params) => {
2211 if !color_finite(&params) {
2212 return false;
2213 }
2214 Some(match self.color.iter().position(|p| *p == params) {
2215 Some(at) => at as u16,
2216 // corner-cut: the 65535th *distinct* grade of one session is
2217 // refused rather than silently aliased, exactly as `set_eq`
2218 // refuses the 65535th curve; same upgrade path.
2219 None if self.color.len() >= usize::from(u16::MAX) => return false,
2220 None => {
2221 self.color.push(params);
2222 (self.color.len() - 1) as u16
2223 }
2224 })
2225 }
2226 };
2227 if snapshot {
2228 self.snapshot();
2229 }
2230 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2231 true
2232 }
2233
2234 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2235 /// policy's own placement (and for an index that is not there) -- what the
2236 /// renderer and the export ask before they place its picture.
2237 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2238 self.transform
2239 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2240 }
2241
2242 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2243 /// step, `false` (and no history) for an index that is not there or a
2244 /// value that is not finite, and equal settings share a table entry.
2245 pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool {
2246 self.write_transform(lane, idx, params, true)
2247 }
2248
2249 /// [`set_transform`](Self::set_transform) without the undo step, for
2250 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2251 /// one drag on a position/scale/rotate/crop control are one undo, not one
2252 /// per pixel.
2253 pub fn set_transform_live(
2254 &mut self,
2255 lane: Lane,
2256 idx: usize,
2257 params: Option<TransformParams>,
2258 ) -> bool {
2259 self.write_transform(lane, idx, params, false)
2260 }
2261
2262 fn write_transform(
2263 &mut self,
2264 lane: Lane,
2265 idx: usize,
2266 params: Option<TransformParams>,
2267 snapshot: bool,
2268 ) -> bool {
2269 if idx >= self.lane(lane).len() {
2270 return false;
2271 }
2272 let slot = match params {
2273 None => None,
2274 Some(params) => {
2275 if !transform_finite(&params) {
2276 return false;
2277 }
2278 Some(match self.transform.iter().position(|p| *p == params) {
2279 Some(at) => at as u16,
2280 // corner-cut: the 65535th *distinct* transform of one
2281 // session is refused rather than silently aliased,
2282 // exactly as `write_color` refuses the 65535th grade;
2283 // same upgrade path.
2284 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2285 None => {
2286 self.transform.push(params);
2287 (self.transform.len() - 1) as u16
2288 }
2289 })
2290 }
2291 };
2292 if snapshot {
2293 self.snapshot();
2294 }
2295 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2296 true
2297 }
2298
2299 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2300 /// index that is not there, which is what every clip starts at anyway.
2301 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2302 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2303 }
2304
2305 /// Sets it, for the clip **and its whole group**: a link is one span on
2306 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2307 /// from its sound would be a group no save could load. One snapshot, so the
2308 /// group's change is one [`Project::undo`].
2309 ///
2310 /// The source range is untouched -- a speed says how many timeline frames
2311 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2312 /// split still address the file afterwards.
2313 ///
2314 /// Refused, changing nothing and costing no undo step, when the clip would
2315 /// grow into the one after it on its own lane: slowing a clip down makes it
2316 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2317 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2318 /// something a user can go and fix. Also for an index that is not there.
2319 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2320 self.write_speed(lane, idx, speed, true)
2321 }
2322
2323 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2324 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2325 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2326 /// not one per rate it passed through -- exactly as
2327 /// [`set_color_live`](Self::set_color_live) is for a slider.
2328 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2329 self.write_speed(lane, idx, speed, false)
2330 }
2331
2332 fn write_speed(
2333 &mut self,
2334 lane: Lane,
2335 idx: usize,
2336 speed: Speed,
2337 snapshot: bool,
2338 ) -> crate::Result<()> {
2339 let Some(members) = self.group_of(lane, idx) else {
2340 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2341 };
2342 let labels = handles(&self.lanes);
2343 // The clip the hand is holding is the group's clock: everything else
2344 // in the group, caption members included, re-times by the ratio its new
2345 // rate gives its own frames. The clips take the rate itself; a caption
2346 // has none, so it takes the *ratio* -- its span on the timeline
2347 // compresses or stretches about the held clip's head, while the words
2348 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2349 // timeline moves, the track does not).
2350 let Some(held) = self.lane(lane).get(idx).copied() else {
2351 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2352 };
2353 // The same per-member piece `speeded_playhead` builds for this op,
2354 // asked here instead of read there -- a caption's length comes from
2355 // the map's own ends (`end - start`), never `round(len * ratio)`
2356 // separately, which is what let the two answers drift apart by a
2357 // frame.
2358 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2359 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2360 let retimed = |s: SubClip| {
2361 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2362 let start = map.apply(s.start);
2363 let end = map.apply(s.end()).max(start.saturating_add(1));
2364 SubClip { start, frames: end - start, ..s }
2365 };
2366 for &(l, i) in &members.clips {
2367 let clips = &self.lanes[l].clips;
2368 let mut moved = clips[i];
2369 moved.speed = speed;
2370 if let Some(next) = clips.get(i + 1)
2371 && moved.end() > next.start
2372 {
2373 let name = labels[l].label();
2374 return Err(format!(
2375 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2376 move it along, or trim this one first",
2377 moved.end(),
2378 next.start
2379 )
2380 .into());
2381 }
2382 }
2383 // ...and the captions, against their own lanes' captions: a stretch
2384 // that runs one into its neighbour is refused for the clip arm's
2385 // reason -- a lane may not overlap itself -- and by name like it.
2386 let subs: Vec<(usize, usize, SubClip)> = members
2387 .subs
2388 .iter()
2389 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2390 .collect();
2391 for &(l, i, moved) in &subs {
2392 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2393 if j != i && moved.start < other.end() && other.start < moved.end() {
2394 return Err(format!(
2395 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2396 starts at {}: move it along, or trim this one first",
2397 labels[l].label(),
2398 self.lanes[l].subs[i].start,
2399 moved.end(),
2400 other.start
2401 )
2402 .into());
2403 }
2404 }
2405 }
2406 if snapshot {
2407 self.snapshot();
2408 }
2409 for (l, i) in members.clips {
2410 self.lanes[l].clips[i].speed = speed;
2411 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2412 }
2413 for (l, i, moved) in subs {
2414 self.lanes[l].subs[i] = moved;
2415 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2416 }
2417 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2418 Ok(())
2419 }
2420
2421 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2422 /// playhead standing at `at` -- read off the geometry **before** the
2423 /// write, because the old ends are gone after it. The question a card
2424 /// asks as its bar moves: the picture under the cursor has to stay the
2425 /// picture under the cursor, or the scene changes with the rate.
2426 ///
2427 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2428 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2429 /// a clip member keeps its own start and re-fits its length at the new
2430 /// rate -- its **old** rate against the new one, which is what the bar's
2431 /// live samples ask about as much as a first press does; a caption
2432 /// member scales about the held clip's start by the held clip's own
2433 /// proportion; and a playhead outside every member's old extent stays
2434 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2435 /// (or the room a stretch takes) absorbs the difference, not the
2436 /// playhead. `None` for an index that is not there.
2437 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2438 let members = self.group_of(lane, idx)?;
2439 let held = self.lane(lane).get(idx).copied()?;
2440 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2441 for &(l, i) in members.clips.iter().chain(&members.subs) {
2442 let (span, map) = match self
2443 .lanes[l]
2444 .clips
2445 .get(i)
2446 .filter(|_| members.clips.contains(&(l, i)))
2447 {
2448 // The clip's own span, re-fitted at its own old rate: one
2449 // piece of the map, anchored where the clip itself is. The
2450 // new length is the same *source* frames at the new rate --
2451 // len divided by it, never multiplied.
2452 Some(c) => (
2453 (c.start, c.start + c.frames()),
2454 TimelineMap::piece(
2455 (c.start, c.start + c.frames()),
2456 (
2457 c.start,
2458 c.start + (c.len() as f64 / new).round() as u32,
2459 ),
2460 ),
2461 ),
2462 // The caption's span, scaled about the held clip's head by
2463 // the held clip's proportion -- the offset the group keeps.
2464 None => {
2465 let s = self.lanes[l].subs.get(i)?;
2466 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2467 (
2468 (s.start, s.end()),
2469 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2470 )
2471 }
2472 };
2473 // The piece owns only its own old span: outside it the playhead
2474 // is another member's question, or nobody's.
2475 if (span.0..span.1).contains(&at) {
2476 return Some(map.apply(at));
2477 }
2478 }
2479 Some(at)
2480 }
2481
2482 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2483 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2484 /// every clip starts at anyway.
2485 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2486 self.lane(lane)
2487 .get(idx)
2488 .map_or(FitPolicy::default(), |c| c.fit)
2489 }
2490
2491 /// Sets it. One undo step like every other edit, and `false` (with no
2492 /// history) for an index that is not there. Unlike an eq or a grade there is
2493 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2494 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2495 if idx >= self.lane(lane).len() {
2496 return false;
2497 }
2498 self.snapshot();
2499 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2500 true
2501 }
2502
2503 /// Every frame number on every lane rewritten onto a timeline counted at
2504 /// another rate: `k` is old timeline frames per new one, `counts` is how
2505 /// long each source is on the *new* timeline (indexed as
2506 /// [`Project::sources`] is), and the edit survives as the same seconds of
2507 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2508 /// the edit list, and the only thing that touches the frame numbers without
2509 /// being an edit anyone made.
2510 ///
2511 /// Every position -- a clip's start and its end alike -- goes through the
2512 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2513 /// stays a gap, and a take's picture and its sound land on the same frame on
2514 /// their two lanes: no lane can drift against another. A clip is then only
2515 /// ever made to *fit* the room its own start and end mapped to, never to
2516 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2517 /// below is the backstop for the one case that could: a slow clip so short
2518 /// that no source range fits its new room at all).
2519 ///
2520 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2521 /// onto the new grid, so a rate picked, unpicked and picked again is within
2522 /// a frame of where it started rather than back at it. Upgrade path is
2523 /// keeping the edit list at one reference rate and conforming on the way
2524 /// out, which every frame number in this module would then be measured in.
2525 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2526 for lane in &mut self.lanes {
2527 let mut cursor = 0;
2528 for clip in &mut lane.clips {
2529 let start = k.timeline_at(clip.start).max(cursor);
2530 // The room its own end mapped to -- never zero, since a clip is
2531 // never empty even on a grid too coarse to hold it.
2532 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2533 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2534 // Its footage, held inside the file's new length: a clip whose
2535 // out-point was the last frame of its source must not come out
2536 // of this naming a frame past the end -- that is a project that
2537 // would not open again ([`crate::PlaybackSession::open_project`]
2538 // refuses one by name).
2539 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2540 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2541 clip.start = start;
2542 clip.in_frame = in_frame;
2543 clip.out_frame = in_frame + len;
2544 cursor = clip.end();
2545 }
2546 // A subtitle's *window* is in microseconds and a rate change moves
2547 // no seconds, so only where it sits is remapped -- through the same
2548 // [`Rate::timeline_at`] every clip boundary goes through, so a
2549 // caption still starts on the frame its picture does.
2550 let mut cursor = 0;
2551 for sub in &mut lane.subs {
2552 let start = k.timeline_at(sub.start).max(cursor);
2553 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2554 sub.start = start;
2555 cursor = sub.end();
2556 }
2557 }
2558 }
2559
2560 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2561 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2562 ///
2563 /// A subtitle lane counts like any other: a caption placed past the last
2564 /// picture holds the timeline open under it, exactly as an `A2` running
2565 /// past `V1` does, rather than being silently clipped away by the length
2566 /// ([`crate::export::timeline_cues`] clips cues to this).
2567 pub fn timeline_frames(&self) -> u32 {
2568 self.lanes
2569 .iter()
2570 .filter_map(|l| match l.kind {
2571 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2572 _ => l.clips.last().map(Clip::end),
2573 })
2574 .max()
2575 .unwrap_or(0)
2576 }
2577
2578 /// The same, counting the *media* alone: where the last picture or sound
2579 /// runs out, with the captions over them ignored.
2580 ///
2581 /// What an export actually writes ends here -- the picture loop walks the
2582 /// composite spans and the file stops with them -- so this is the length a
2583 /// cue has to be inside of to be written at all (what
2584 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2585 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2586 /// thing is a picture or a sound, which is every timeline that has no
2587 /// caption hanging past the end of both.
2588 pub fn media_frames(&self) -> u32 {
2589 self.lanes
2590 .iter()
2591 .filter(|l| l.kind != LaneKind::Subtitle)
2592 .filter_map(|l| l.clips.last().map(Clip::end))
2593 .max()
2594 .unwrap_or(0)
2595 }
2596
2597 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2598 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2599 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2600 self.lane_spans(Lane::V1)
2601 }
2602
2603 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2604 // Timeline frames, not source ones: a box on a lane is as wide as the
2605 // clip is long *there*, which a speed halves or quadruples.
2606 self.lane(lane)
2607 .iter()
2608 .map(|c| (c.start, c.frames()))
2609 .collect()
2610 }
2611
2612 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2613 /// and past the end -- [`Project::span_at`] is the version that tells those
2614 /// two apart.
2615 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2616 let clips = self.lane(lane);
2617 let idx = at(clips, timeline_frame)?;
2618 Some((idx, source_frame(&clips[idx], timeline_frame)))
2619 }
2620
2621 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2622 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2623 self.map(Lane::V1, timeline_frame)
2624 }
2625
2626 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2627 /// it, or the gap running to the next clip (or to the end of the timeline,
2628 /// which is where a lane shorter than its neighbour keeps showing black).
2629 /// `None` at or past the end of the timeline, which is the only "nothing
2630 /// left" there is.
2631 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2632 let total = self.timeline_frames();
2633 if timeline_frame >= total {
2634 return None;
2635 }
2636 let clips = self.lane(lane);
2637 Some(match at(clips, timeline_frame) {
2638 Some(idx) => Span {
2639 start: timeline_frame,
2640 len: clips[idx].end() - timeline_frame,
2641 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2642 speed: clips[idx].speed,
2643 },
2644 None => Span {
2645 start: timeline_frame,
2646 speed: Speed::NORMAL,
2647 // The next placement, or the end of the timeline: a gap is
2648 // bounded by what comes after it, never by its own bookkeeping.
2649 len: clips
2650 .iter()
2651 .find(|c| c.start > timeline_frame)
2652 .map_or(total, |c| c.start)
2653 - timeline_frame,
2654 from: None,
2655 },
2656 })
2657 }
2658
2659 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2660 /// gaps included -- the whole play list, which is what an export walks.
2661 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2662 let mut out = Vec::new();
2663 let mut t = timeline_frame;
2664 while let Some(span) = self.span_at(lane, t) {
2665 t = span.end();
2666 out.push(span);
2667 }
2668 out
2669 }
2670
2671 /// What the *composite* shows from `timeline_frame` on -- the answer
2672 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2673 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2674 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2675 /// (the usual overlay convention). A frame no video lane covers is a gap,
2676 /// which is black however many lanes are above or below it.
2677 ///
2678 /// No blending, so exactly one lane is visible at a time and the composite
2679 /// is itself a span list -- which is why one decoder plays it, the same one
2680 /// a single-lane timeline uses, rather than N running at once.
2681 ///
2682 /// The span is cut short wherever a *higher* lane's clip starts, because
2683 /// from that frame on a different lane wins; that is what makes walking
2684 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2685 ///
2686 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2687 /// lanes would then be visible in one frame and the caller needs a decoder
2688 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2689 /// (this same walk, per lane) feeding N decoders.
2690 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2691 let total = self.timeline_frames();
2692 if timeline_frame >= total {
2693 return None;
2694 }
2695 let video = self.video_lanes();
2696 // The last covering lane is the winner; only the lanes above it can
2697 // interrupt what it shows.
2698 let winner = video
2699 .iter()
2700 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2701 let (from, speed, until) = match winner {
2702 Some(i) => {
2703 let clips = self.lane(video[i]);
2704 let idx = at(clips, timeline_frame).expect("just found above");
2705 (
2706 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2707 clips[idx].speed,
2708 clips[idx].end(),
2709 )
2710 }
2711 // Nothing covers it: black until something above the floor starts.
2712 None => (None, Speed::NORMAL, total),
2713 };
2714 let takeover = video[winner.map_or(0, |i| i + 1)..]
2715 .iter()
2716 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
2717 .map(|c| c.start)
2718 .min();
2719 Some(Span {
2720 start: timeline_frame,
2721 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
2722 from,
2723 speed,
2724 })
2725 }
2726
2727 /// The video lanes in display order, topmost last -- the order the composite
2728 /// rule counts in.
2729 fn video_lanes(&self) -> Vec<Lane> {
2730 self.lanes()
2731 .into_iter()
2732 .filter(|l| l.kind == LaneKind::Video)
2733 .collect()
2734 }
2735
2736 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
2737 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
2738 /// index on that lane. `None` over a gap and past the end. What a front-end
2739 /// asks to act on "the clip on screen" without re-deriving the rule.
2740 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
2741 let video = self.video_lanes();
2742 let winner = video
2743 .iter()
2744 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
2745 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
2746 }
2747
2748 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
2749 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
2750 /// answers "the clip on screen"; this answers it per lane, which is what
2751 /// walking the lanes for something to select needs.
2752 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
2753 at(self.lane(lane), timeline_frame)
2754 }
2755
2756 /// How the composite is graded at `timeline_frame`, so the picture playback
2757 /// converts and the one an export encodes are graded from one answer.
2758 /// `None` over a gap (black is black) and for a clip nobody has graded,
2759 /// which is the byte-identical path everywhere.
2760 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
2761 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2762 self.color_of(lane, idx)
2763 }
2764
2765 /// [`composite_color_at`](Self::composite_color_at)'s twin for
2766 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
2767 /// policy's own placement.
2768 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
2769 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2770 self.transform_of(lane, idx)
2771 }
2772
2773 /// How the composite meets the project canvas at `timeline_frame`, so the
2774 /// picture playback composes and the one an export encodes are placed from
2775 /// one answer. `Fit` over a gap, where black is already the canvas.
2776 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
2777 self.composite_clip_at(timeline_frame)
2778 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
2779 }
2780
2781 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
2782 /// viewer sees from `timeline_frame` to the end, in order. What an export
2783 /// encodes and what playback walks at a clip boundary.
2784 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
2785 let mut out = Vec::new();
2786 let mut t = timeline_frame;
2787 while let Some(span) = self.composite_span_at(t) {
2788 t = span.end();
2789 out.push(span);
2790 }
2791 out
2792 }
2793
2794 /// Split every lane at `timeline_frame`, so that frame becomes the first
2795 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
2796 /// (`false`, no change) when no lane has a clip to split there -- at a
2797 /// placement's own start, in a gap, and past the end -- all of which would
2798 /// produce an empty clip or nothing at all.
2799 ///
2800 /// Lanes' halves share an id only where they are the *same* span: the lanes
2801 /// are edited apart, so the clip being cut here may start (or end)
2802 /// somewhere else on another lane, and a group id whose clips disagree
2803 /// about their span is not one take (see [`links_are_consistent`], which
2804 /// refuses to load one).
2805 ///
2806 /// Metadata only: no mapping changes, in any lane.
2807 pub fn split(&mut self, timeline_frame: u32) -> bool {
2808 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
2809 }
2810
2811 /// [`split`](Project::split), with the snapshot optional and the lanes
2812 /// named: a batch that has already taken a snapshot
2813 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
2814 /// region and must still be one undo press, and a *scoped* batch must not
2815 /// cut a lane it was told to leave alone.
2816 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
2817 let cut: Vec<Option<Clip>> = self
2818 .lanes
2819 .iter()
2820 .enumerate()
2821 .map(|(i, l)| {
2822 on.contains(&i)
2823 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
2824 .flatten()
2825 })
2826 .collect();
2827 // The same question on the subtitle lanes, in their own arithmetic: a
2828 // razor cuts the captions with the picture, and a frame where only a
2829 // caption can be cut is still a cut.
2830 let cut_subs: Vec<bool> = self
2831 .lanes
2832 .iter()
2833 .enumerate()
2834 .map(|(i, l)| {
2835 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
2836 })
2837 .collect();
2838 // The links the captions carry, read before the room is opened below
2839 // -- `sub_open_room` takes the id off both halves, exactly as
2840 // `open_room` does for a clip, and the split hands the halves theirs
2841 // back afterwards.
2842 let sub_orig: Vec<Option<u32>> = self
2843 .lanes
2844 .iter()
2845 .zip(&cut_subs)
2846 .map(|(l, &cut)| {
2847 cut.then(|| {
2848 l.subs
2849 .iter()
2850 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
2851 .and_then(|s| s.link)
2852 })
2853 .flatten()
2854 })
2855 .collect();
2856 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
2857 return false;
2858 }
2859 if snapshot {
2860 self.snapshot();
2861 }
2862 for (data, _) in self
2863 .lanes
2864 .iter_mut()
2865 .zip(&cut_subs)
2866 .filter(|&(_, &cut)| cut)
2867 {
2868 // A split is room of no width: the halves keep their windows by
2869 // proportion and nothing moves.
2870 sub_open_room(&mut data.subs, timeline_frame, 0);
2871 debug_assert!(subs_sorted_disjoint(&data.subs));
2872 }
2873 // Each side is its own question, and the answer is the group the clip
2874 // already carried: the left half *keeps* its take's id -- the take the
2875 // frames before the cut still are -- and the right halves of one take
2876 // share one fresh id of their own, clips and captions alike. A lane
2877 // holding no group (a `place`ment, a caption nobody grouped) comes out
2878 // of the cut holding none, which is what it went in with. The captions'
2879 // own links were drawn above, before the room opened.
2880 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
2881 let mut distinct: Vec<u32> = Vec::new();
2882 for id in orig.iter().chain(&sub_orig).flatten() {
2883 if !distinct.contains(id) {
2884 distinct.push(*id);
2885 }
2886 }
2887 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
2888 let right_of =
2889 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
2890 for (l, data) in self.lanes.iter_mut().enumerate() {
2891 if !cut_subs[l] {
2892 continue;
2893 }
2894 // The pair the razor just made: they touch at the frame it cut.
2895 if let Some(idx) = data
2896 .subs
2897 .iter()
2898 .position(|s| s.end() == timeline_frame)
2899 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
2900 {
2901 data.subs[idx].link = sub_orig[l];
2902 data.subs[idx + 1].link = right_of(sub_orig[l]);
2903 }
2904 }
2905 for (data_i, data) in self.lanes.iter_mut().enumerate() {
2906 // The lanes this call was not scoped to are not cut, whatever their
2907 // own clips would allow.
2908 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
2909 continue;
2910 };
2911 let mut tail = data.clips[idx];
2912 // Where the cut lands *in the file*, which is the clip's own rate
2913 // away from where it lands on the timeline. Both halves keep the
2914 // speed, and `splittable` has already refused any frame at which
2915 // the two would not add up to the one being cut.
2916 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
2917 tail.start = timeline_frame;
2918 tail.link = right_of(orig[data_i]);
2919 data.clips[idx].out_frame = tail.in_frame;
2920 data.clips[idx].link = orig[data_i];
2921 data.clips.insert(idx + 1, tail);
2922 }
2923 true
2924 }
2925
2926 /// The inverse of [`split`](Project::split): rejoin the placements that meet
2927 /// at `timeline_frame` in every lane and put the result back in one group.
2928 /// Only what a split could have produced is rejoined -- the two sides must
2929 /// touch on the timeline *and* be consecutive frames of the same source --
2930 /// so the clip list comes back exactly as it was and traversal with it.
2931 /// `false` when no lane has such a pair. The rejoined placement keeps the
2932 /// **left** half's id, which is the take the split left on it: rejoining a
2933 /// cut take puts the take back, id and all.
2934 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
2935 // What each lane would end up covering, if it joins here at all.
2936 let joined: Vec<Option<(u32, u32)>> = self
2937 .lanes
2938 .iter()
2939 .map(|l| {
2940 joinable(&l.clips, timeline_frame)
2941 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
2942 })
2943 .collect();
2944 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
2945 let join_subs: Vec<Option<usize>> = self
2946 .lanes
2947 .iter()
2948 .map(|l| sub_joinable(&l.subs, timeline_frame))
2949 .collect();
2950 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
2951 return false;
2952 }
2953 self.snapshot();
2954 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
2955 if let Some(idx) = sub {
2956 data.subs[idx].frames += data.subs[idx + 1].frames;
2957 data.subs[idx].out_us = data.subs[idx + 1].out_us;
2958 data.subs.remove(idx + 1);
2959 debug_assert!(subs_sorted_disjoint(&data.subs));
2960 }
2961 let Some(idx) = joinable(&data.clips, timeline_frame) else {
2962 continue;
2963 };
2964 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
2965 data.clips.remove(idx + 1);
2966 }
2967 true
2968 }
2969
2970 /// Take the placement at `idx` of `lane` out of its group: every clip and
2971 /// every caption carrying its id -- on however many lanes -- is handed an
2972 /// id of its own, so from here on each half moves, trims and is deleted
2973 /// alone. The music video whose sound is to be cut against its picture
2974 /// starts here, and so does the caption that has to come off the picture it
2975 /// was pinned to.
2976 ///
2977 /// An id of its own rather than none at all: a half no other lane is grouped
2978 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
2979 /// (see [`links_are_consistent`]), and it is what a front-end already draws
2980 /// as detached. `None` would instead say "was never part of a take", which
2981 /// is what a one-lane [`place`](Project::place) means.
2982 ///
2983 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
2984 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
2985 /// the group back. Refused (`false`, nothing changed) for an index that is
2986 /// not there, a placement in no group at all, and one whose group has no
2987 /// other half -- that one is already detached, and a refusal must not cost
2988 /// an undo step.
2989 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
2990 let Some(members) = self.group_of(lane, idx) else {
2991 return false;
2992 };
2993 if members.alone() {
2994 return false;
2995 }
2996 let Some(id) = self
2997 .lane(lane)
2998 .get(idx)
2999 .and_then(|c| c.link)
3000 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3001 else {
3002 return false;
3003 };
3004 self.snapshot();
3005 // Drawn before the walk: `new_link` takes the whole project, and the
3006 // walk holds the lanes.
3007 let count = members.clips.len() + members.subs.len();
3008 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3009 for data in &mut self.lanes {
3010 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3011 c.link = fresh.pop();
3012 }
3013 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3014 s.link = fresh.pop();
3015 }
3016 }
3017 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3018 true
3019 }
3020
3021 /// Put two clips on two lanes into one group, so what moves one moves the
3022 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3023 /// how a picture is regrouped with sound it was never opened with. Whatever
3024 /// either of them was grouped with comes along: those clips cover this same
3025 /// span already, so the result is one group and not two overlapping ones.
3026 ///
3027 /// Same frames or nothing: a group id names **one span** on however many
3028 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3029 /// clips that do not cover the same frames cannot be one take, and the
3030 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3031 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3032 /// mean, not the rule.
3033 ///
3034 /// Metadata only, one snapshot. The error says what is wrong, because
3035 /// `false` would not: a bad index, one lane twice (a group is at most one
3036 /// clip per lane), spans that disagree, and a pair that is already one take
3037 /// -- nothing changes, and none of them costs an undo step.
3038 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3039 if a == b {
3040 return Err(format!(
3041 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3042 a.label()
3043 )
3044 .into());
3045 }
3046 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3047 p.lane(lane)
3048 .get(idx)
3049 .copied()
3050 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3051 };
3052 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3053 if (x.start, x.end()) != (y.start, y.end()) {
3054 return Err(format!(
3055 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3056 a.label(),
3057 x.start,
3058 x.end(),
3059 b.label(),
3060 y.start,
3061 y.end()
3062 )
3063 .into());
3064 }
3065 if x.link.is_some() && x.link == y.link {
3066 return Err("those two are one take already".into());
3067 }
3068 self.snapshot();
3069 let id = self.new_link();
3070 // Every clip either of them was grouped with, by the same rule: all of
3071 // them cover this span, so one id over the lot stays consistent.
3072 let old = [x.link, y.link];
3073 for data in &mut self.lanes {
3074 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3075 if old.contains(&c.link) {
3076 c.link = Some(id);
3077 }
3078 }
3079 }
3080 // And the two themselves, which a `place` may have left in no group.
3081 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3082 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3083 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3084 Ok(())
3085 }
3086
3087 /// Put every placement the picks name into one group -- the group a hand
3088 /// builds with ctrl-click and a menu: the picture, its sound and the
3089 /// caption over it, on as many lanes as the picks name. What any of them
3090 /// was already grouped with rides along (one group, not two sharing a
3091 /// member), and the members keep their own spans: a group is one id over
3092 /// one placement per lane, and the offsets between them are what the group
3093 /// preserves -- a drag, a trim and a delete all move the members *by the
3094 /// same distance*, not to the same frames.
3095 ///
3096 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3097 /// and the refusal says which lane -- and a pick that names nothing is
3098 /// refused with its own words. At least two picks, or there is nothing to
3099 /// group.
3100 ///
3101 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3102 /// apart again. None of the refusals changes anything or costs an undo
3103 /// step.
3104 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3105 if picks.len() < 2 {
3106 return Err("a group is two placements or more: pick another one first".into());
3107 }
3108 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3109 for &(lane, idx) in picks {
3110 if seen.contains(&lane) {
3111 return Err(format!(
3112 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3113 track",
3114 lane.label()
3115 )
3116 .into());
3117 }
3118 seen.push(lane);
3119 let there = if lane.kind == LaneKind::Subtitle {
3120 idx < self.sub_lane(lane).len()
3121 } else {
3122 idx < self.lane(lane).len()
3123 };
3124 if !there {
3125 let what = if lane.kind == LaneKind::Subtitle {
3126 "subtitle"
3127 } else {
3128 "clip"
3129 };
3130 return Err(
3131 format!("there is no {what} {idx} on {}", lane.label()).into()
3132 );
3133 }
3134 }
3135 let links: Vec<Option<u32>> = picks
3136 .iter()
3137 .map(|&(lane, idx)| {
3138 if lane.kind == LaneKind::Subtitle {
3139 self.sub_lane(lane)[idx].link
3140 } else {
3141 self.lane(lane)[idx].link
3142 }
3143 })
3144 .collect();
3145 // The picks are already one per lane (`seen`, above), but a pick's
3146 // *existing* group can carry a second member onto a lane another
3147 // pick (or another existing group in the merge) already occupies --
3148 // two captions on one sub lane, say, each grouped with a different
3149 // clip before this call. Merging both in would leave that lane with
3150 // two members of one id, which `links_are_consistent` may never see:
3151 // refused by name, before anything moves, rather than a group closed
3152 // broken.
3153 let labels = handles(&self.lanes);
3154 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3155 for (li, data) in self.lanes.iter().enumerate() {
3156 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3157 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3158 if n > 0 {
3159 per_lane.insert(li, n as u32);
3160 }
3161 }
3162 // A pick that carries no link of its own is invisible to the scan
3163 // above (there is no `Some` to match): it still claims its lane.
3164 for &(lane, _) in picks {
3165 let li = self.index(lane).expect("checked above");
3166 per_lane.entry(li).or_insert(0);
3167 if !self.lanes[li]
3168 .clips
3169 .iter()
3170 .any(|c| c.link.is_some() && links.contains(&c.link))
3171 && !self.lanes[li]
3172 .subs
3173 .iter()
3174 .any(|s| s.link.is_some() && links.contains(&s.link))
3175 {
3176 *per_lane.get_mut(&li).expect("just inserted") += 1;
3177 }
3178 }
3179 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3180 return Err(format!(
3181 "a group is one placement per lane: merging these groups would put two on {}",
3182 labels[li].label()
3183 )
3184 .into());
3185 }
3186 self.snapshot();
3187 let id = self.new_link();
3188 // Whatever any pick was grouped with comes along, for [`group`]'s
3189 // reason -- one id over the lot, not two groups sharing a member.
3190 for data in &mut self.lanes {
3191 for c in data.clips.iter_mut() {
3192 if c.link.is_some() && links.contains(&c.link) {
3193 c.link = Some(id);
3194 }
3195 }
3196 for s in data.subs.iter_mut() {
3197 if s.link.is_some() && links.contains(&s.link) {
3198 s.link = Some(id);
3199 }
3200 }
3201 }
3202 // And the picks themselves, which a `place` may have left in no group.
3203 // The lane seats are read before the walk, which holds the lanes.
3204 let seats: Vec<(usize, bool)> = picks
3205 .iter()
3206 .map(|&(lane, _)| {
3207 (
3208 self.index(lane).expect("checked above"),
3209 lane.kind == LaneKind::Subtitle,
3210 )
3211 })
3212 .collect();
3213 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3214 let _ = lane;
3215 if sub {
3216 self.lanes[at].subs[idx].link = Some(id);
3217 } else {
3218 self.lanes[at].clips[idx].link = Some(id);
3219 }
3220 }
3221 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3222 Ok(())
3223 }
3224
3225 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3226 /// lands on and leaving every other clip exactly where it is -- the
3227 /// per-lane paste. Anything already there is trimmed away (and split in two
3228 /// if `clip` lands inside it), which is what keeps the lane sorted and
3229 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3230 /// gap. Refused only for an empty `clip`.
3231 ///
3232 /// The placement belongs to no group: a clipboard clip carries the link id
3233 /// of the take it was copied from, and placing it twice -- or placing a copy
3234 /// back over the clip it came from -- would put that id on two clips of one
3235 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3236 /// `None` rather than a fresh id because a one-lane placement has nothing on
3237 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3238 /// become a group again.
3239 ///
3240 /// Refused for an empty `clip`, for a lane that is not there, and for a
3241 /// subtitle lane, which carries no picture and no sound
3242 /// ([`Project::place_sub`] is its door).
3243 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3244 if clip.out_frame <= clip.in_frame
3245 || lane.kind == LaneKind::Subtitle
3246 || self.index(lane).is_none()
3247 {
3248 return false;
3249 }
3250 self.snapshot();
3251 let clip = Clip {
3252 start: timeline_frame,
3253 link: None,
3254 ..clip
3255 };
3256 self.insert_over(lane, clip);
3257 true
3258 }
3259
3260 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3261 /// one grouped take -- what a picture let go over a further video track
3262 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3263 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3264 /// this half a file with sound landed on a layer silent, and the only way to
3265 /// hear it was to drop it a second time on an audio lane.
3266 ///
3267 /// Both halves overwrite what they land on and neither ripples, exactly as
3268 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3269 /// nothing under it moves. One history snapshot for the pair, the added lane
3270 /// included, so one [`Project::undo`] takes the whole placement back. The two
3271 /// carry one link, which is what makes them one take to a drag, a trim and a
3272 /// save.
3273 ///
3274 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3275 /// there or is not a video lane: sound placed alone is
3276 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3277 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3278 if clip.out_frame <= clip.in_frame
3279 || lane.kind != LaneKind::Video
3280 || self.index(lane).is_none()
3281 {
3282 return false;
3283 }
3284 self.snapshot();
3285 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3286 // an ord names a lane only while every ord below it does.
3287 while self.lane_count(LaneKind::Audio) <= lane.ord {
3288 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3289 }
3290 let clip = Clip {
3291 start: timeline_frame,
3292 link: Some(self.new_link()),
3293 ..clip
3294 };
3295 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3296 self.insert_over(half, clip);
3297 }
3298 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3299 true
3300 }
3301
3302 /// `clip` into `lane` at its own start, over whatever it lands on: the
3303 /// insert both placement doors make, which is what keeps a lane sorted and
3304 /// disjoint. The caller has checked that the lane is there.
3305 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3306 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3307 clear(clips, clip.start, clip.end());
3308 let idx = clips.partition_point(|c| c.start < clip.start);
3309 clips.insert(idx, clip);
3310 debug_assert!(sorted_disjoint(clips));
3311 }
3312
3313 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3314 /// frame `start`: the drag that rearranges takes, along a track and across
3315 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3316 /// was. `start` at the clip's own is the pure lane change.
3317 ///
3318 /// The whole group travels the same distance, each half on the lane it
3319 /// already sits on -- a link means "these cover one span on however many
3320 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3321 /// sound would be a group no save could load. Only the dragged half changes
3322 /// lane, and that is not a desync: a link names no lane at all.
3323 ///
3324 /// `start` is **clamped**, never refused, to the room the group has: no
3325 /// member crosses a neighbour on the lane it lands on, exactly as
3326 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3327 /// dragging past a neighbour means "as far as it goes", and butting up
3328 /// against the take next door is how clips are laid end to end. The
3329 /// tightest member's wall wins, so a sound half boxed in between two others
3330 /// holds its picture still.
3331 ///
3332 /// Refused, changing nothing and costing no undo step, for a lane that is
3333 /// not there, an index that is not there, a move across *kinds* (a picture
3334 /// cannot play on an audio lane, and the save it wrote would not open
3335 /// again), a head let go *inside* another clip or into a gap too narrow to
3336 /// hold this one -- a move that overwrote what it landed on would destroy a
3337 /// take the pointer never named, which is what [`place`](Project::place)
3338 /// may do and a drag may not -- a half let go onto the lane its own partner
3339 /// is on, and a drop that changes neither lane nor frame, which is a clip
3340 /// picked up and put back down, i.e. a click.
3341 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3342 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3343 return false;
3344 };
3345 if from.kind != to.kind {
3346 return false;
3347 }
3348 let members = self.group_of(from, idx).expect("the clip was found");
3349 let held = self.index(from).expect("the clip was found on it");
3350 // The two halves of one group would land on one span of one lane, which
3351 // is the one thing a link may never mean. Refused rather than clamped:
3352 // the partner moves the same distance, so there is no room for it
3353 // anywhere on that lane.
3354 if dest != held
3355 && members
3356 .clips
3357 .iter()
3358 .chain(&members.subs)
3359 .any(|&(l, _)| l == dest)
3360 {
3361 return false;
3362 }
3363 let want = i64::from(start) - i64::from(clip.start);
3364 // How far the group may travel, in timeline frames and signed: every
3365 // member -- the clips and any caption grouped with them -- narrows it
3366 // to the gap it is landing in, and what is left is what the pointer is
3367 // clamped to.
3368 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3369 return false;
3370 };
3371 if lo > hi {
3372 return false;
3373 }
3374 let delta = want.clamp(lo, hi);
3375 if delta == 0 && dest == held {
3376 return false;
3377 }
3378 self.snapshot();
3379 for &(l, i) in &members.clips {
3380 let c = &mut self.lanes[l].clips[i];
3381 // In range by the walls above, which are `u32` frames throughout.
3382 c.start = (i64::from(c.start) + delta) as u32;
3383 }
3384 for &(l, i) in &members.subs {
3385 let s = &mut self.lanes[l].subs[i];
3386 s.start = (i64::from(s.start) + delta) as u32;
3387 }
3388 if dest != held {
3389 let clip = self.lanes[held].clips.remove(idx);
3390 let clips = &mut self.lanes[dest].clips;
3391 let at = clips.partition_point(|c| c.start < clip.start);
3392 clips.insert(at, clip);
3393 }
3394 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3395 debug_assert!(members
3396 .clips
3397 .iter()
3398 .chain(&members.subs)
3399 .all(|&(l, _)| {
3400 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3401 }));
3402 true
3403 }
3404
3405 /// How far a group drag may travel, `(least, most)` in timeline frames and
3406 /// signed: every member narrows the range to the gap it is landing in --
3407 /// the clips against their lanes' clips and the captions against their
3408 /// lanes' captions -- and what is left is what the pointer is clamped to.
3409 /// `travelling` names the one member that changes lane, if any: the clip a
3410 /// hand is carrying onto another track, whose walls are read on the lane it
3411 /// is let go over at the frame the pointer named. `None` when a member has
3412 /// no gap to land in at all.
3413 fn move_room(
3414 &self,
3415 members: &Members,
3416 travelling: Option<(usize, usize, usize, u32)>,
3417 ) -> Option<(i64, i64)> {
3418 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3419 for &(l, i) in members.clips.iter().chain(&members.subs) {
3420 let sub = members.subs.contains(&(l, i));
3421 let (start, frames) = match self.lanes[l]
3422 .clips
3423 .get(i)
3424 .filter(|_| !sub)
3425 .map(|c| (c.start, c.frames()))
3426 {
3427 Some(pair) => pair,
3428 None => {
3429 let s = self.lanes[l].subs.get(i)?;
3430 (s.start, s.frames)
3431 }
3432 };
3433 let land = travelling
3434 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3435 .map_or(l, |(_, _, dest, _)| dest);
3436 // Which gap this member's walls are read off: its own place on the
3437 // lane it stays on, and the frame the pointer named on the lane it
3438 // is let go over. A clip's neighbours are the clips of the lane it
3439 // lands on and a caption's are its captions -- the two lists of one
3440 // lane never meet.
3441 let at = match travelling {
3442 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3443 _ => start,
3444 };
3445 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3446 let neighbours: Vec<(u32, u32)> = if sub {
3447 self.lanes[land]
3448 .subs
3449 .iter()
3450 .map(|s| (s.start, s.end()))
3451 .collect()
3452 } else {
3453 self.lanes[land]
3454 .clips
3455 .iter()
3456 .map(|c| (c.start, c.end()))
3457 .collect()
3458 };
3459 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3460 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3461 continue;
3462 }
3463 if *other_start <= at && at < *other_end {
3464 // A head let go inside another placement, which a clamp
3465 // has no answer for: the drop is refused.
3466 return None;
3467 }
3468 match other_end <= &at {
3469 true => wall_lo = wall_lo.max(*other_end),
3470 false => wall_hi = wall_hi.min(*other_start),
3471 }
3472 }
3473 if wall_hi - wall_lo < frames {
3474 return None;
3475 }
3476 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3477 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3478 }
3479 Some((lo, hi))
3480 }
3481
3482 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3483 /// the drag on a clip's end that makes it play more or less of its source.
3484 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3485 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3486 /// is room that was already empty. One snapshot, so a whole drag is one
3487 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3488 /// sample. Changes the timeline->source mapping: the caller must reseek.
3489 ///
3490 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3491 /// exactly what they played before, which is what makes this a trim and not
3492 /// a slip.
3493 ///
3494 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3495 /// legal means "as far as it goes", and stopping the box there is the
3496 /// affordance. The walls are: one frame of clip always survives, an edge
3497 /// never crosses the neighbouring clip on its own lane, an in-point never
3498 /// walks back past the source's first frame, and an out-point never runs
3499 /// past `source_frames[clip.source]` -- the caller's table of how long each
3500 /// source actually is ([`Project`] does not know, and a clip ending past its
3501 /// file's last frame is a save that will not open again; see
3502 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3503 /// there may not grow at all.
3504 ///
3505 /// Linked placements trim *together*, by one delta: every member's same
3506 /// edge moves the distance the dragged one did, clamped to the room its
3507 /// own walls leave -- offsets between the members of a hand-built group
3508 /// survive the trim, exactly as they survive a drag.
3509 ///
3510 /// `false`, changing nothing and costing no undo step, for an index that is
3511 /// not there and for an edge that is already where it was asked to go.
3512 pub fn trim(
3513 &mut self,
3514 lane: Lane,
3515 idx: usize,
3516 edge: Edge,
3517 to: u32,
3518 source_frames: &[u32],
3519 ) -> bool {
3520 let (Some((lo, hi)), Some(clip)) = (
3521 self.trim_room(lane, idx, edge, source_frames),
3522 self.lane(lane).get(idx).copied(),
3523 ) else {
3524 return false;
3525 };
3526 let to = to.clamp(lo, hi);
3527 let at = match edge {
3528 Edge::Start => clip.start,
3529 Edge::End => clip.end(),
3530 };
3531 if to == at {
3532 return false;
3533 }
3534 // Worked out before anything moves: at a slow rate a room can be too
3535 // narrow to hold even one source frame ([`Speed::fit`]), and the
3536 // dragged clip refusing to fit must refuse the whole gesture rather
3537 // than be given a range wider than its room -- which is the overlap
3538 // the lane invariant exists to forbid. The walls below leave that room,
3539 // so this is the backstop for a project that came in through another
3540 // door.
3541 let room = match edge {
3542 // The frames that stay play what they played, so what survives is
3543 // measured from the *end*.
3544 Edge::Start => clip.end() - to,
3545 Edge::End => to - clip.start,
3546 };
3547 let Some(keep) = clip.speed.fit(room) else {
3548 return false;
3549 };
3550 let members = self.group_of(lane, idx).expect("checked above");
3551 self.snapshot();
3552 let still = self.is_still(&clip);
3553 let held = self.index(lane).expect("checked above");
3554 let c = &mut self.lanes[held].clips[idx];
3555 match edge {
3556 // A still has no earlier frame to walk an in-point back to --
3557 // every frame of it is the same picture -- so its head grows
3558 // *forward*: the range it plays is however long the new room is,
3559 // anchored at the source's frame 0. Bounded by `lo`, which is where
3560 // the cap in `source_frames` is applied.
3561 Edge::Start if still => {
3562 c.in_frame = 0;
3563 c.out_frame = keep;
3564 c.start = to;
3565 }
3566 Edge::Start => {
3567 // Non-negative by `lo`, which is what keeps the in-point on the
3568 // source.
3569 c.in_frame = c.out_frame - keep.min(c.out_frame);
3570 c.start = to;
3571 }
3572 // Never wider than the room the edge was clamped to: see
3573 // [`Speed::fit`].
3574 Edge::End => c.out_frame = c.in_frame + keep,
3575 }
3576 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3577 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3578 true
3579 }
3580
3581 /// The rest of a group after one member's `edge` has moved by `delta`:
3582 /// every other member's same edge moves the same distance, clamped to the
3583 /// room its own walls leave -- a clip's against its lane and its source,
3584 /// a caption's against its own lane, its window following by the
3585 /// placement's own proportion. The undo step is the caller's: this is the
3586 // second half of one edit, not an edit of its own.
3587 fn follow_group(
3588 &mut self,
3589 members: &Members,
3590 dragged: &(usize, usize),
3591 edge: Edge,
3592 delta: i64,
3593 source_frames: &[u32],
3594 ) {
3595 for &(l, i) in &members.clips {
3596 if (l, i) == *dragged {
3597 continue;
3598 }
3599 let c = self.lanes[l].clips[i];
3600 let at = match edge {
3601 Edge::Start => c.start,
3602 Edge::End => c.end(),
3603 };
3604 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3605 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3606 if to == at {
3607 continue;
3608 }
3609 let room = match edge {
3610 Edge::Start => c.end() - to,
3611 Edge::End => to - c.start,
3612 };
3613 let Some(keep) = c.speed.fit(room) else {
3614 continue;
3615 };
3616 let still = self.is_still(&self.lanes[l].clips[i]);
3617 let c = &mut self.lanes[l].clips[i];
3618 match edge {
3619 Edge::Start if still => {
3620 c.in_frame = 0;
3621 c.out_frame = keep;
3622 c.start = to;
3623 }
3624 Edge::Start => {
3625 c.in_frame = c.out_frame - keep.min(c.out_frame);
3626 c.start = to;
3627 }
3628 Edge::End => c.out_frame = c.in_frame + keep,
3629 }
3630 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3631 }
3632 for &(l, i) in &members.subs {
3633 if (l, i) == *dragged {
3634 continue;
3635 }
3636 let s = self.lanes[l].subs[i];
3637 let at = match edge {
3638 Edge::Start => s.start,
3639 Edge::End => s.end(),
3640 };
3641 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3642 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3643 if to == at {
3644 continue;
3645 }
3646 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3647 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3648 }
3649 }
3650
3651 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3652 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3653 /// What a front-end drawing the box *during* a drag asks, so the live width
3654 /// is the width the release will commit and an edge stops under the pointer
3655 /// rather than snapping back. The **clip's own** walls: the rest of its
3656 /// group follows by the same delta within their own ([`follow_group`]), so
3657 /// what is drawn for the dragged edge is what its own clip will commit.
3658 /// `None` for an index that is not there.
3659 pub fn trim_room(
3660 &self,
3661 lane: Lane,
3662 idx: usize,
3663 edge: Edge,
3664 source_frames: &[u32],
3665 ) -> Option<(u32, u32)> {
3666 let l = self.index(lane)?;
3667 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3668 }
3669
3670 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3671 /// its lane's storage index: the one wall computation, asked for the clip
3672 /// itself and for each member a group trim carries.
3673 fn clip_room(
3674 &self,
3675 l: usize,
3676 i: usize,
3677 edge: Edge,
3678 source_frames: &[u32],
3679 ) -> (u32, u32) {
3680 let clips = &self.lanes[l].clips;
3681 let c = clips[i];
3682 let (lo, hi) = match edge {
3683 Edge::Start => (
3684 // Back to the source's own first frame -- as many *timeline*
3685 // frames as that head is worth at the clip's rate, which at
3686 // real time is the head itself -- and never over the clip in
3687 // front of it. Saturating because a clip may hold *more*
3688 // head than the timeline has room for -- a ripple delete
3689 // slides a clip back to frame 0 with its in-point wherever
3690 // the cut left it -- and frame 0 is the other wall.
3691 //
3692 // A still is measured from its *tail* instead: it has no
3693 // in-point worth the name (every frame the same picture), so
3694 // its head reaches exactly as far as its tail does -- out to
3695 // the length the caller's table gives it, whole. Measured
3696 // from the in-point it would have no head room at all, which
3697 // is a placed picture whose left edge cannot be dragged out.
3698 // No entry in the table means no growth, as it does at the
3699 // other end.
3700 if self.is_still(&c) {
3701 c.end().saturating_sub(
3702 c.speed
3703 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
3704 )
3705 } else {
3706 c.start.saturating_sub(c.speed.room(c.in_frame))
3707 }
3708 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
3709 // One *frame of clip* always survives, and at a rate below
3710 // real time one frame of clip is several frames of timeline
3711 // ([`Speed::room`]): an edge dragged closer than that would
3712 // ask for a range no source frame fits in. At real time this
3713 // is `end - 1`, unchanged.
3714 c.end() - c.speed.room(1),
3715 ),
3716 Edge::End => (
3717 // ...and the same wall from the other end: the shortest this
3718 // clip can be is the room one source frame of it takes.
3719 c.start + c.speed.room(1),
3720 // Out to whatever is left of the source -- again in timeline
3721 // frames, at this clip's rate -- and never over the clip
3722 // behind it.
3723 c.start
3724 .saturating_add(
3725 c.speed.room(
3726 source_frames
3727 .get(c.source)
3728 .copied()
3729 .unwrap_or(c.out_frame)
3730 .saturating_sub(c.in_frame),
3731 ),
3732 )
3733 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
3734 ),
3735 };
3736 // `hi.max(lo)`: for a clip the invariants hold for, the range always
3737 // contains the edge's own place, and a caller's wrong `source_frames`
3738 // must not become an empty range (or a panicking `clamp`) here.
3739 (lo, hi.max(lo))
3740 }
3741
3742 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
3743 /// every frame is the same picture, so which frame of it a clip's in-point
3744 /// names is not a question -- what [`Project::trim`] lets grow at either
3745 /// end. `false` for a source that is not there.
3746 fn is_still(&self, clip: &Clip) -> bool {
3747 self.sources
3748 .get(clip.source)
3749 .is_some_and(|s| crate::is_image(&s.path))
3750 }
3751
3752 /// The placements that move as one with the one at `idx` of `lane` --
3753 /// itself and whatever carries its link, on the media lanes and the
3754 /// subtitle ones alike. `None` for an index that is not there.
3755 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
3756 let sub = lane.kind == LaneKind::Subtitle;
3757 let link = if sub {
3758 self.sub_lane(lane).get(idx)?.link
3759 } else {
3760 self.lane(lane).get(idx)?.link
3761 };
3762 let mut members = Members::default();
3763 match link {
3764 Some(link) => {
3765 for (l, data) in self.lanes.iter().enumerate() {
3766 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
3767 members.clips.push((l, i));
3768 }
3769 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
3770 members.subs.push((l, i));
3771 }
3772 }
3773 }
3774 None => {
3775 let l = self.index(lane).expect("the placement was found on it");
3776 if sub {
3777 members.subs.push((l, idx));
3778 } else {
3779 members.clips.push((l, idx));
3780 }
3781 }
3782 }
3783 Some(members)
3784 }
3785
3786 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
3787 /// new group, pushing everything from there on later by its length in
3788 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
3789 /// the clip it lands in is split around it; past the end of the timeline it
3790 /// goes down where it was asked for, with black in front of it -- which is
3791 /// what a library row let go on the open bed means, and what the ghost under
3792 /// the pointer promised. A clipboard means "put it here", not "here and
3793 /// black in front", and clamps to the end at its own door
3794 /// ([`crate::PlaybackSession::paste_at`]).
3795 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
3796 ///
3797 /// `V1` and `A1` and no other lane, because a take is one picture and one
3798 /// sound: copying it onto every lane there is would play the same audio
3799 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
3800 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
3801 /// video lane it is a clip that decodes to nothing, and a save carrying one
3802 /// does not open again -- and a still image ([`crate::is_image`]) reaches
3803 /// `V1` only, for the mirror of that reason. The room is still opened on
3804 /// every media lane, or the lanes it was not inserted into would slide out
3805 /// of step with the ones it was -- and the subtitle lanes are left alone:
3806 /// the words keep their own clock, and a caption that should travel with a
3807 /// clip is what a group is for.
3808 ///
3809 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
3810 /// Changes the timeline->source mapping: the caller must reseek. Refused for
3811 /// an empty `clip` and for one naming a source that is not there (both of
3812 /// which the public fields let a caller build), and for a paste whose ripple
3813 /// would push a clip past the last frame there is -- nothing is changed by
3814 /// any of them.
3815 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
3816 let Some(source) = self.sources.get(clip.source) else {
3817 return false;
3818 };
3819 if clip.out_frame <= clip.in_frame {
3820 return false;
3821 }
3822 let audio_only = crate::is_audio(&source.path);
3823 // ...and its mirror: a still is a picture and no sound, so a copy of one
3824 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
3825 // worker tries to demux -- which silences the *whole session*, not just
3826 // that clip -- and a save the engine's own `open_project` then refuses.
3827 let picture_only = crate::is_image(&source.path);
3828 // The frame it was asked for and no other: a row let go on the empty
3829 // bed past the last clip lands *there*, under the ghost that promised
3830 // it, with black in front. Clamping to the end here made every drop on
3831 // open bed an append -- the clipboard's rule, applied to a hand that
3832 // had named a place.
3833 let at = timeline_frame;
3834 // The room it takes on the timeline, which its speed decides -- not the
3835 // source range it reads.
3836 let len = clip.frames();
3837 // Room for it: `open_room` adds `len` to every start from `at` on, and a
3838 // hand-written file may hold a clip that ends at the very last frame
3839 // (`edith::check` permits `start + len == u32::MAX`). Refused here
3840 // rather than wrapped there -- a wrapped start lands *behind* the clip
3841 // it belongs after, which is an overlap no save will read back.
3842 if at.checked_add(len).is_none()
3843 || self
3844 .lanes
3845 .iter()
3846 .flat_map(|l| &l.clips)
3847 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
3848 {
3849 return false;
3850 }
3851 // ...and room *to open*: the paste splits whatever it lands inside of,
3852 // and a speeded clip can only be cut where its own rate has a source
3853 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
3854 // of one, which is the overlap a lane may never hold. At real time every
3855 // frame answers, so this cannot refuse an unspeeded paste.
3856 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
3857 if self
3858 .lanes
3859 .iter()
3860 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
3861 {
3862 return false;
3863 }
3864 self.snapshot();
3865 let clip = Clip {
3866 start: at,
3867 link: Some(self.new_link()),
3868 ..clip
3869 };
3870 // Only lanes that can play the source: a file with no picture belongs on
3871 // an audio lane and nowhere else, exactly as `place_stream_at` decides
3872 // it for an import. On a video lane it would decode to nothing, and the
3873 // save it wrote would not open again.
3874 let kinds: &[LaneKind] = match (audio_only, picture_only) {
3875 (true, _) => &[LaneKind::Audio],
3876 (_, true) => &[LaneKind::Video],
3877 _ => &[LaneKind::Video, LaneKind::Audio],
3878 };
3879 let takes: Vec<usize> = kinds
3880 .iter()
3881 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
3882 .collect();
3883 for (i, data) in self.lanes.iter_mut().enumerate() {
3884 open_room(&mut data.clips, at, len);
3885 // The subtitle lanes are NOT touched: a paste inserts media, and
3886 // the words keep their own clock. Opening room here used to split
3887 // a caption the paste landed inside and slide the rest behind it
3888 // -- "a caption that stayed put while the picture moved on no
3889 // longer says the same thing" -- but a caption pinned to nothing
3890 // (and a video arriving on a timeline of words alone) has no
3891 // picture to follow, and the split did to the words what no hand
3892 // asked for. A caption that should travel with a clip is what a
3893 // group is for, and a group moves as one.
3894 if takes.contains(&i) {
3895 let idx = data.clips.partition_point(|c| c.start < at);
3896 data.clips.insert(idx, clip);
3897 }
3898 debug_assert!(sorted_disjoint(&data.clips));
3899 debug_assert!(subs_sorted_disjoint(&data.subs));
3900 }
3901 true
3902 }
3903
3904 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
3905 /// silence, and nothing else moves. Refused only for an out-of-range index
3906 /// (which a lane that is not there always is) -- lifting the last placement
3907 /// there is leaves an *empty* timeline, which is a state the project holds
3908 /// like any other and an undo brings back.
3909 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
3910 if idx >= self.lane(lane).len() {
3911 return false;
3912 }
3913 self.snapshot();
3914 self.lane_mut(lane).expect("checked above").remove(idx);
3915 true
3916 }
3917
3918 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
3919 /// the hole: everything after slides back by `len`. The rippling delete --
3920 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
3921 /// empty range; a delete that leaves nothing behind empties the timeline,
3922 /// which is a state like any other and one undo away.
3923 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
3924 if len == 0 {
3925 return false;
3926 }
3927 // Nothing reaches past `at`: there is nothing to cut and nothing to
3928 // slide back, and a delete that changes nothing must not cost an undo
3929 // step (see [`snapshot`](Project::snapshot)).
3930 if !self
3931 .lanes
3932 .iter()
3933 .flat_map(|l| &l.clips)
3934 .any(|c| c.end() > at)
3935 {
3936 return false;
3937 }
3938 self.snapshot();
3939 let on = all_lanes(&self.lanes);
3940 ripple(&mut self.lanes, &on, at, len);
3941 true
3942 }
3943
3944 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
3945 /// out of the lanes in `scope` and close each hole, as one edit: the
3946 /// jumpcut a silence scan asks for ([`crate::silence`]).
3947 ///
3948 /// A lane that is not in `scope` **does not move**, which is the whole
3949 /// point of the parameter: the silences of a podcast track come out
3950 /// without the music track under it sliding. `scope` is an arbitrary set of
3951 /// lanes and not a kind or a range, so a caller with its own idea of what
3952 /// is selected (a take, a track, everything) says it in lanes and nothing
3953 /// here has to learn about selection.
3954 ///
3955 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
3956 /// reason this exists rather than a caller's loop over
3957 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
3958 /// undo press, not forty. Cut back to front, so a region's frames still
3959 /// mean what the caller measured while the ones before it are cut.
3960 ///
3961 /// The list is sorted and overlapping entries are merged before anything is
3962 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
3963 /// other's frames. Refused, with no undo step, for an empty list, for a
3964 /// scope naming no lane that is there, and -- by name -- when the scope
3965 /// would take one half of a take with it
3966 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
3967 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
3968 let regions = tidy(regions);
3969 let on = self.scoped(scope)?;
3970 let Some(&(first, _)) = regions.first() else {
3971 return Err("nothing to cut".into());
3972 };
3973 self.scope_holds_takes_whole(&on, first)?;
3974 self.snapshot();
3975 for &(at, len) in regions.iter().rev() {
3976 ripple(&mut self.lanes, &on, at, len);
3977 }
3978 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3979 Ok(())
3980 }
3981
3982 /// The storage indices of `scope`, which is what every batch below walks.
3983 /// `Err` for a scope that names nothing there rather than a silent no-op:
3984 /// an edit asked for on a lane that is not there did not happen, and the
3985 /// caller has to hear so.
3986 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
3987 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
3988 match on.is_empty() {
3989 true => Err("no track to work on".into()),
3990 false => Ok(on),
3991 }
3992 }
3993
3994 /// The law a scoped ripple lives under: **a group travels as one**, so a
3995 /// batch that moves one half of a take and not the other would leave the
3996 /// halves disagreeing about where they stand -- an offset no hand asked
3997 /// for, and the reason the take's lanes have to be scoped together.
3998 ///
3999 /// Refused by name rather than widened silently. Widening would edit a
4000 /// track the user did not scope, which is exactly the surprise scoping
4001 /// exists to end; a front-end that wants the take is free to *say* the
4002 /// take's lanes, and to name them in what it tells the user afterwards.
4003 ///
4004 /// Only from `from` on: a take sitting entirely before the first cut does
4005 /// not move, so it is not this rule's business.
4006 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4007 let labels = handles(&self.lanes);
4008 // The halves of a group are on either of a lane's lists, and the
4009 // refusal names whichever sits outside the scope -- a clip like it
4010 // always has, and a caption now that a group may hold one.
4011 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4012 let Some(id) = link else {
4013 return Ok(());
4014 };
4015 for (j, data) in self.lanes.iter().enumerate() {
4016 if on.contains(&j) {
4017 continue;
4018 }
4019 let clip = data.clips.iter().find(|o| o.link == Some(id));
4020 let sub = data.subs.iter().find(|s| s.link == Some(id));
4021 if let Some(half) = clip {
4022 return Err(format!(
4023 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4024 moving one track of a take would pull it apart -- take the whole take, \
4025 or detach them first",
4026 labels[j].label(),
4027 half.start
4028 )
4029 .into());
4030 }
4031 if let Some(half) = sub {
4032 return Err(format!(
4033 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4034 moving one track of a take would pull it apart -- take the whole take, \
4035 or detach them first",
4036 labels[j].label(),
4037 half.start
4038 )
4039 .into());
4040 }
4041 }
4042 Ok(())
4043 };
4044 for &i in on {
4045 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4046 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4047 }
4048 // A caption before the first cut does not move, so it is not this
4049 // rule's business -- exactly the clip test's own line.
4050 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4051 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4052 }
4053 }
4054 Ok(())
4055 }
4056
4057 /// Play every one of `regions` at `speed` instead of cutting it: each is
4058 /// split out of whatever covers it, re-rated, and the room it no longer
4059 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4060 /// does not ripple, and a hole where a silence shrank is the one thing this
4061 /// must not leave. One snapshot for the lot, like
4062 /// [`cut_regions`](Project::cut_regions).
4063 ///
4064 /// The rate is **absolute**, not a multiplier on what is there: running it
4065 /// twice over the same stretch leaves it at `speed`, not at `speed`
4066 /// squared, so a second pass over an already-cut timeline changes nothing.
4067 ///
4068 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4069 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4070 ///
4071 /// Refused by name, with nothing changed and no undo step, when:
4072 ///
4073 /// * the scope would take one half of a take with it
4074 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4075 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4076 /// shrink by different amounts and the ripple would pull them apart,
4077 /// which is what cutting does not suffer and why delete mode has no such
4078 /// refusal;
4079 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4080 /// piece could not be split out exactly;
4081 /// * two lanes' pieces would end up different lengths, which is a group
4082 /// whose halves disagree about their span (the refusal
4083 /// [`write_speed`](Project::write_speed) already makes, in its words);
4084 /// * the region would grow rather than shrink, i.e. it already plays faster
4085 /// than `speed`.
4086 pub fn speed_regions(
4087 &mut self,
4088 regions: &[(u32, u32)],
4089 speed: Speed,
4090 scope: &[Lane],
4091 ) -> crate::Result<()> {
4092 let regions = tidy(regions);
4093 let on = self.scoped(scope)?;
4094 let Some(&(first, _)) = regions.first() else {
4095 return Err("nothing to speed up".into());
4096 };
4097 self.scope_holds_takes_whole(&on, first)?;
4098 let labels = handles(&self.lanes);
4099 // Before anything is touched, because this is the refusal a person can
4100 // act on: a clip that laps over the edge of a silence has to be trimmed
4101 // (or the silences cut instead), and saying so after a rollback would
4102 // be saying it about a timeline that already looks different.
4103 for &(at, len) in &regions {
4104 for &l in &on {
4105 for c in &self.lanes[l].clips {
4106 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4107 {
4108 return Err(format!(
4109 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4110 speeding it up would pull the lanes apart -- trim it first, or cut the \
4111 silences out instead",
4112 labels[l].label(),
4113 c.start,
4114 at + len
4115 )
4116 .into());
4117 }
4118 }
4119 }
4120 }
4121 // The rest is checked as it is built: a split's own arithmetic is what
4122 // says whether a rate can address an edge. So the snapshot is taken
4123 // first and *rolled back* on a refusal -- one undo either way, and a
4124 // refusal still costs no step (`undo` pops the one just pushed).
4125 self.snapshot();
4126 for &(at, len) in regions.iter().rev() {
4127 self.write_split(at, false, &on);
4128 self.write_split(at + len, false, &on);
4129 let mut room: Option<(Lane, u32)> = None;
4130 let mut refused = None;
4131 for &l in &on {
4132 let clips = &self.lanes[l].clips;
4133 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4134 if (c.start, c.end()) != (at, at + len) {
4135 // *Which* edge did not come off: a rate that cannot
4136 // address the end of the silence is not a rate that
4137 // cannot address its start, and naming the wrong frame
4138 // sends the user looking in the wrong place.
4139 let edge = match c.start == at {
4140 true => at + len,
4141 false => at,
4142 };
4143 refused = Some(format!(
4144 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4145 detach it, or put it back to 1.00x first",
4146 labels[l].label(),
4147 c.start,
4148 c.speed
4149 ));
4150 continue;
4151 }
4152 let after = speed.frames(c.len());
4153 match room {
4154 None => room = Some((labels[l], after)),
4155 Some((first, n)) if n != after => {
4156 refused = Some(format!(
4157 "at {speed} the {} half of the silence at frame {at} would cover \
4158 {after} frames and the {} half {n}: they are one take and a take \
4159 is one span -- detach them first",
4160 labels[l].label(),
4161 first.label()
4162 ));
4163 }
4164 Some(_) => {}
4165 }
4166 }
4167 }
4168 let shrunk = match (refused, room) {
4169 (Some(e), _) => {
4170 self.undo();
4171 return Err(e.into());
4172 }
4173 // A gap on every lane: nothing to re-rate, and nothing to close.
4174 (None, None) => continue,
4175 (None, Some((_, after))) => after,
4176 };
4177 // The region's new length, on every scoped lane alike.
4178 let after = shrunk;
4179 let Some(delta) = len.checked_sub(shrunk) else {
4180 self.undo();
4181 return Err(format!(
4182 "the silence at frame {at} already plays faster than {speed}: \
4183 at that rate it would be {shrunk} frames instead of {len}"
4184 )
4185 .into());
4186 };
4187 for &l in &on {
4188 for c in &mut self.lanes[l].clips {
4189 if c.start == at && c.end() == at + len {
4190 c.speed = speed;
4191 } else if c.start >= at + len {
4192 c.start -= delta;
4193 }
4194 }
4195 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4196 // The captions on a scoped lane travel with the region's time:
4197 // a piece inside it plays in `after` frames instead of `len`
4198 // -- same words on less timeline, its window untouched, for
4199 // [`write_speed`]'s reason -- and everything behind the region
4200 // slides up by what the region gave back.
4201 //
4202 // The pieces inside re-time by their *boundaries*, not each
4203 // on its own: rounding one piece's start and its neighbour's
4204 // start apart can land both on the same frame (two one-frame
4205 // cues of a thirty-frame region at 2x both want frame 15), so
4206 // the mapped boundaries are walked in order and forced apart
4207 // -- each piece at least one frame, none past the region's own
4208 // new end, where the first follower lands exactly. A rounding
4209 // artifact is clamped, not refused: nothing about the words
4210 // asked for an overlap.
4211 let share = f64::from(after) / f64::from(len).max(1.);
4212 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4213 let mut prev = at;
4214 let subs = &mut self.lanes[l].subs;
4215 for i in 0..subs.len() {
4216 let s = subs[i];
4217 if s.start >= at + len {
4218 subs[i].start = s.start - delta;
4219 } else if s.start >= at && s.end() <= at + len {
4220 let mut start = map(s.start).max(prev);
4221 let end = map(s.end()).max(start + 1).min(at + after);
4222 start = start.min(end - 1);
4223 subs[i].start = start;
4224 subs[i].frames = end - start;
4225 prev = end;
4226 }
4227 }
4228 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4229 }
4230 }
4231 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4232 Ok(())
4233 }
4234
4235 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4236 /// -- the whole-group delete a single-lane front-end means. `false` for a
4237 /// bad index. Changes the mapping: the caller must reseek.
4238 pub fn delete(&mut self, idx: usize) -> bool {
4239 self.delete_in(Lane::V1, idx)
4240 }
4241
4242 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4243 /// in no group (or a group of one, which is the same thing to a delete) is
4244 /// what it always was: its own span cut out of *every* lane, so the
4245 /// timeline closes up under it. A clip in a group takes the group with it,
4246 /// each member by its **own** span and on its **own** lane -- the members
4247 /// keep their offsets, so their spans may disagree, and the lanes may end
4248 /// up out of step with each other, which is inherent to a hand-built group
4249 /// and one undo away. Every member -- clips and captions alike -- goes by
4250 /// the same law: its own span out of its own lane, hole closed; a caption
4251 /// in no group keeps the lift that leaves a gap, which is its own door's
4252 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4253 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4254 /// index, and for a lane that is not there. Changes the mapping: the
4255 /// caller must reseek.
4256 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4257 let Some(members) = self.group_of(lane, idx) else {
4258 return false;
4259 };
4260 if !members.alone() {
4261 return self.delete_members(&members);
4262 }
4263 let Some(clip) = self.lane(lane).get(idx).copied() else {
4264 return false;
4265 };
4266 self.ripple_delete(clip.start, clip.frames())
4267 }
4268
4269 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4270 /// caption in no group lifts, exactly as its own key always made it
4271 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4272 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4273 /// span out of its own lane, hole closed, captions and clips alike.
4274 /// `false` for a bad index.
4275 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4276 let Some(members) = self.group_of(lane, idx) else {
4277 return false;
4278 };
4279 if !members.alone() {
4280 return self.delete_members(&members);
4281 }
4282 self.lift_sub(lane, idx)
4283 }
4284
4285 /// The one whole-group delete both doors land in: every member's own span
4286 /// cut out of its own lane and the hole closed there -- clips and
4287 /// captions by the same law -- and nothing else on another lane moves,
4288 /// which is what keeps one member's ripple from dragging another
4289 /// member's lane out from under it. One snapshot, one undo step.
4290 fn delete_members(&mut self, members: &Members) -> bool {
4291 self.snapshot();
4292 for &(l, i) in &members.clips {
4293 let c = self.lanes[l].clips[i];
4294 ripple(&mut self.lanes, &[l], c.start, c.frames());
4295 }
4296 // The captions go by the same law their clip siblings do -- the span
4297 // out of its own lane, the hole closed -- and not by the lift a
4298 // *lone* caption's delete is: deleted with its group, the words after
4299 // it slide up with everything else, or the lane the group emptied is
4300 // the one lane the delete left a hole in. `ripple` is the one
4301 // mechanism (it clears the span and shifts the rest, clips and
4302 // captions alike); a sub lane holds no clips, so its other list is
4303 // untouched.
4304 for &(l, i) in &members.subs {
4305 let s = self.lanes[l].subs[i];
4306 ripple(&mut self.lanes, &[l], s.start, s.frames);
4307 }
4308 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4309 true
4310 }
4311
4312 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4313 #[cfg(test)]
4314 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4315 self.lane(lane)
4316 }
4317
4318 /// How many undo steps are stacked: what the sweep asks so "one op, one
4319 /// snapshot" is a count and not a guess.
4320 #[cfg(test)]
4321 pub(crate) fn history_len(&self) -> usize {
4322 self.history.len()
4323 }
4324
4325 /// Every part of the project that an edit can change, as comparable
4326 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4327 #[cfg(test)]
4328 pub(crate) fn parts(&self) -> SweepParts {
4329 SweepParts(
4330 self.sources.len(),
4331 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4332 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4333 )
4334 }
4335
4336 /// Restore every lane from before the last successful edit -- the clips and
4337 /// the lane list both. `false` when there is nothing left to undo.
4338 pub fn undo(&mut self) -> bool {
4339 match self.history.pop() {
4340 Some(prev) => {
4341 self.lanes = prev;
4342 true
4343 }
4344 None => false,
4345 }
4346 }
4347
4348 /// The project an export renders from: everything a render reads, with the
4349 /// undo history left behind. An export never walks the history back, and
4350 /// cloning it costs a copy of every lane list in the session -- this is
4351 /// taken on the UI thread, so it clones the lanes and the sources alone.
4352 pub fn export_snapshot(&self) -> Self {
4353 Self {
4354 sources: self.sources.clone(),
4355 lanes: self.lanes.clone(),
4356 eq: self.eq.clone(),
4357 color: self.color.clone(),
4358 history: Vec::new(),
4359 next_link: self.next_link,
4360 subtitles: self.subtitles.clone(),
4361 limiter: self.limiter,
4362 tone: self.tone,
4363 }
4364 }
4365
4366 /// Half-open `(source, start, end)` segments in *source* seconds, from
4367 /// `timeline_frame` to the end of the timeline -- the play list for the
4368 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4369 /// worker synthesises that many seconds of silence, which is what keeps the
4370 /// audio master clock counting across a hole instead of stalling on it.
4371 /// The first entry is partial when the position is mid-clip. Empty when the
4372 /// position is past the end or `fps` is not usable.
4373 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4374 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4375 }
4376
4377 /// [`segments_from`](Project::segments_from) for a named lane.
4378 pub fn lane_segments_from(
4379 &self,
4380 lane: Lane,
4381 timeline_frame: u32,
4382 fps: f64,
4383 ) -> Vec<(Option<usize>, f64, f64)> {
4384 if !(fps.is_finite() && fps > 0.0) {
4385 return Vec::new();
4386 }
4387 self.spans_from(lane, timeline_frame)
4388 .iter()
4389 .map(|span| match span.from {
4390 // A clip's window is in *source* seconds: where in the file it
4391 // reads from, which a delete before it never shifts. How many
4392 // source frames that is, is the span's own arithmetic -- at a
4393 // speed it is not the timeline length ([`Span::source_len`]).
4394 Some((source, in_frame)) => (
4395 Some(source),
4396 f64::from(in_frame) / fps,
4397 f64::from(in_frame + span.source_len()) / fps,
4398 ),
4399 // A gap has no file, so all it can say is how long it is.
4400 None => (None, 0.0, f64::from(span.len) / fps),
4401 })
4402 .collect()
4403 }
4404
4405 /// One play list per audio lane that *holds* something, in display order --
4406 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4407 /// what an export asks how many lanes it would have to mix.
4408 ///
4409 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4410 /// audio lane at all) still yields one all-gap list, so it plays silence
4411 /// against a master clock exactly as it did before there were lanes to
4412 /// count. Lanes with nothing on them are left out rather than mixed in as
4413 /// silence: they would cost a decode thread each and add zero.
4414 pub fn audio_segments_from(
4415 &self,
4416 timeline_frame: u32,
4417 fps: f64,
4418 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4419 self.audio_lanes()
4420 .into_iter()
4421 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4422 .collect()
4423 }
4424
4425 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4426 /// builds a play list for, in the same order. Public because everything
4427 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4428 /// which lane an mp4 export would copy -- has to read the very list the
4429 /// sound comes off, or the two answers drift apart (which is exactly how an
4430 /// `A2`-only project once exported silently, ledger).
4431 pub fn audio_lanes(&self) -> Vec<Lane> {
4432 let lanes: Vec<Lane> = self
4433 .lanes()
4434 .into_iter()
4435 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
4436 .collect();
4437 match lanes.is_empty() {
4438 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
4439 // no sound still plays silence against the master clock.
4440 true => vec![Lane::A1],
4441 false => lanes,
4442 }
4443 }
4444
4445 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
4446 /// segments plays at, and how long the timeline gives it: the same lanes in
4447 /// the same order, one entry per segment, `None` for a segment at real time
4448 /// -- which is every segment of a project nobody has speeded, and the path
4449 /// the audio worker leaves bit-identical.
4450 ///
4451 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
4452 /// the segment tuple is what every opener and a dozen tests speak, and a
4453 /// rate is not part of *which samples* a segment names.
4454 ///
4455 /// The seconds are what makes a resample exact: a segment's own window
4456 /// resolves to whole source frames, and dividing that by the rate would
4457 /// leave each clip a fraction of a frame short or long -- a drift that grows
4458 /// clip by clip. Told how much timeline it owes, the worker pads or trims
4459 /// the last few samples of each segment instead, so the sound stays locked
4460 /// to the picture however many speeded cuts it walks through.
4461 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
4462 self.audio_lanes()
4463 .into_iter()
4464 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
4465 .collect()
4466 }
4467
4468 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
4469 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4470 /// same walk, same `fps` refusal.
4471 pub fn lane_speeds_from(
4472 &self,
4473 lane: Lane,
4474 timeline_frame: u32,
4475 fps: f64,
4476 ) -> Vec<Option<Stretch>> {
4477 if !(fps.is_finite() && fps > 0.0) {
4478 return Vec::new();
4479 }
4480 self.spans_from(lane, timeline_frame)
4481 .iter()
4482 .map(|span| {
4483 (!span.speed.is_normal()).then(|| Stretch {
4484 step: span.speed.as_f64(),
4485 timeline_secs: f64::from(span.len) / fps,
4486 })
4487 })
4488 .collect()
4489 }
4490
4491 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
4492 /// segments plays through: the same lanes in the same order, one entry per
4493 /// segment, `None` where the segment is a gap or its clip plays flat.
4494 ///
4495 /// A parallel list rather than a fourth element of the segment tuple: that
4496 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
4497 /// and an effect is not part of *which samples* a segment names. A short
4498 /// list therefore means "flat from here on" rather than a length mismatch --
4499 /// see [`crate::AudioSession::open_mixed_streams_eq`].
4500 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
4501 self.audio_lanes()
4502 .into_iter()
4503 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
4504 .collect()
4505 }
4506
4507 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
4508 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4509 /// same walk, same `fps` refusal, so the two lists cannot come out different
4510 /// lengths.
4511 pub fn lane_eqs_from(
4512 &self,
4513 lane: Lane,
4514 timeline_frame: u32,
4515 fps: f64,
4516 ) -> Vec<Option<EqParams>> {
4517 if !(fps.is_finite() && fps > 0.0) {
4518 return Vec::new();
4519 }
4520 self.spans_from(lane, timeline_frame)
4521 .iter()
4522 // A span off a clip covers that clip's frames and no others, so its
4523 // own start names the clip -- the index a [`Span`] does not carry.
4524 .map(|span| {
4525 self.map(lane, span.start)
4526 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
4527 })
4528 .collect()
4529 }
4530
4531 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
4532 /// it has decided it will succeed -- a refusal must not cost an undo step.
4533 fn snapshot(&mut self) {
4534 if self.history.len() == HISTORY_CAP {
4535 self.history.remove(0);
4536 }
4537 self.history.push(self.lanes.clone());
4538 }
4539
4540 fn new_link(&mut self) -> u32 {
4541 let id = self.next_link;
4542 self.next_link = self.next_link.saturating_add(1);
4543 id
4544 }
4545
4546}
4547
4548/// The handle of every lane, in storage order -- the one definition of what
4549/// [`Lane::ord`] counts.
4550fn handles(lanes: &[LaneData]) -> Vec<Lane> {
4551 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
4552 lanes
4553 .iter()
4554 .map(|l| match l.kind {
4555 LaneKind::Video => {
4556 video += 1;
4557 Lane::new(LaneKind::Video, video - 1)
4558 }
4559 LaneKind::Audio => {
4560 audio += 1;
4561 Lane::new(LaneKind::Audio, audio - 1)
4562 }
4563 LaneKind::Subtitle => {
4564 subtitle += 1;
4565 Lane::new(LaneKind::Subtitle, subtitle - 1)
4566 }
4567 })
4568 .collect()
4569}
4570
4571/// The one law a caption re-time scales by: frame `f` moves about the held
4572/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
4573/// commits it, [`Project::speeded_playhead`] previews it -- both build their
4574/// [`TimelineMap`] piece from this single answer so the two cannot drift
4575/// apart by a frame the way they once did.
4576fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
4577 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
4578 .round()
4579 .clamp(0., f64::from(u32::MAX)) as u32
4580}
4581
4582/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
4583/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
4584/// a speed cannot be applied twice or forgotten in one of them.
4585fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
4586 // Clamped inside the clip's own range: rounding at a slow rate can put the
4587 // last timeline frame of a clip a frame past its out-point, and a source
4588 // frame outside the range is one the next clip owns.
4589 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
4590}
4591
4592/// Index of the clip covering `frame`, or `None` for a gap or past the end.
4593/// Binary search: the sorted-disjoint invariant is what makes it legal.
4594fn at(clips: &[Clip], frame: u32) -> Option<usize> {
4595 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
4596 (frame < clips[idx].end()).then_some(idx)
4597}
4598
4599/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
4600/// there would cut in two. A placement's own first frame is not inside it.
4601fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
4602 let idx = at(clips, frame)?;
4603 // ...and, on a speeded clip, one its rate can actually address
4604 // ([`Speed::split_at`]): a cut between two showings of one source frame
4605 // would leave halves that no longer add up to the clip that was cut.
4606 (frame > clips[idx].start)
4607 .then_some(idx)
4608 .filter(|&idx| split_source(&clips[idx], frame).is_some())
4609}
4610
4611/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
4612/// rate cannot address that frame.
4613fn split_source(c: &Clip, frame: u32) -> Option<u32> {
4614 c.speed
4615 .split_at(c.len(), frame - c.start)
4616 .map(|src| c.in_frame + src)
4617}
4618
4619/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
4620/// rejoin: they must touch there, and be consecutive frames of one source.
4621fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
4622 let idx = clips.iter().position(|c| c.end() == frame)?;
4623 let next = clips.get(idx + 1)?;
4624 let joined = clips[idx].len() + next.len();
4625 (next.start == frame
4626 && next.source == clips[idx].source
4627 && next.in_frame == clips[idx].out_frame
4628 // ...at one rate, and one that puts the rejoined clip back in exactly
4629 // the room the two took up: what a split could have produced, which is
4630 // all this undoes.
4631 && next.speed == clips[idx].speed
4632 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
4633 .then_some(idx)
4634}
4635
4636/// The lane invariant: sorted by `start`, no two placements overlapping, no
4637/// empty placement. Checked at every constructor and asserted after every
4638/// mutation -- the offset model is only tractable while it holds.
4639/// The one thing an equalizer setting may not be: a value the text format
4640/// cannot write and read back as itself. Checked wherever params come in, so
4641/// what an edit produces is always what a save writes and a load reads.
4642fn finite(params: &EqParams) -> bool {
4643 params
4644 .bands
4645 .iter()
4646 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
4647}
4648
4649/// The same for a colour grade: [`crate::color`] itself falls back to identity
4650/// on a non-finite value, but a value that cannot be written and read back as
4651/// itself has no business reaching the model.
4652fn color_finite(p: &ColorParams) -> bool {
4653 p.brightness.is_finite()
4654 && p.contrast.is_finite()
4655 && p.saturation.is_finite()
4656 && p.tint.is_finite()
4657}
4658
4659fn sorted_disjoint(clips: &[Clip]) -> bool {
4660 clips.iter().all(|c| c.out_frame > c.in_frame)
4661 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
4662}
4663
4664/// The very same invariant on a subtitle lane, in that lane's own two units:
4665/// sorted by `start`, no two placements overlapping, no empty placement at
4666/// either end. Asserted after every mutation, exactly as its twin is.
4667fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
4668 subs.iter()
4669 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
4670 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
4671}
4672
4673/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
4674/// the one conversion between a lane's clock and a cue's, and `0` for a rate
4675/// that is not one (every caller of this has already refused such a rate).
4676fn us_of(frames: i64, fps: f64) -> i64 {
4677 match fps.is_finite() && fps > 0.0 {
4678 true => ((frames as f64) / fps * 1e6).round() as i64,
4679 false => 0,
4680 }
4681}
4682
4683/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
4684/// dropping what is inside the hole, splitting what straddles it and trimming
4685/// what overlaps an edge. The windows follow the cut by proportion
4686/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
4687fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
4688 let mut out = Vec::with_capacity(subs.len() + 1);
4689 for s in subs.drain(..) {
4690 if s.end() <= start || s.start >= end {
4691 out.push(s);
4692 continue;
4693 }
4694 if s.start < start {
4695 out.push(SubClip {
4696 frames: start - s.start,
4697 out_us: s.window_at(start),
4698 // Both pieces lose the group id, for [`clear`]'s reason: one
4699 // id on two boxes of one lane is the one thing it may never
4700 // mean.
4701 link: None,
4702 ..s
4703 });
4704 }
4705 if s.end() > end {
4706 out.push(SubClip {
4707 start: end,
4708 frames: s.end() - end,
4709 in_us: s.window_at(end),
4710 link: None,
4711 ..s
4712 });
4713 }
4714 }
4715 *subs = out;
4716}
4717
4718/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
4719/// `len`, splitting a placement that straddles `at` so the two halves end up on
4720/// either side of the hole. A `len` of 0 is that split alone, which is what a
4721/// [`Project::split`] over a subtitle lane is.
4722fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
4723 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
4724 let s = subs[idx];
4725 let cut = s.window_at(at);
4726 subs[idx] = SubClip {
4727 frames: at - s.start,
4728 out_us: cut,
4729 link: None,
4730 ..s
4731 };
4732 subs.insert(
4733 idx + 1,
4734 SubClip {
4735 start: at,
4736 frames: s.end() - at,
4737 in_us: cut,
4738 link: None,
4739 ..s
4740 },
4741 );
4742 }
4743 for s in subs.iter_mut().filter(|s| s.start >= at) {
4744 s.start += len;
4745 }
4746}
4747
4748/// [`joinable`] for a subtitle lane: the first of the two placements a
4749/// [`Project::regroup`] at `frame` would rejoin. What a split could have
4750/// produced and nothing else -- they touch on the timeline, they read the same
4751/// track, and the second one's window carries on where the first's stopped.
4752fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
4753 let idx = subs.iter().position(|s| s.end() == frame)?;
4754 let next = subs.get(idx + 1)?;
4755 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
4756 .then_some(idx)
4757}
4758
4759/// How far one `edge` of the caption at `idx` may travel against its own lane's
4760/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
4761/// rate, which a caption *following* a group's trim does not have to be exact
4762/// about -- its own walls, its own one surviving frame, and nothing that needs
4763/// a clock.
4764fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
4765 let s = &subs[idx];
4766 match edge {
4767 Edge::Start => (
4768 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
4769 s.end() - 1,
4770 ),
4771 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
4772 }
4773}
4774
4775/// Move one `edge` of `s` to timeline frame `to`, its window following by the
4776/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
4777/// forwards and backwards. The caption a group's trim is carrying has no rate
4778/// of its own and needs none: what one frame of it is worth in microseconds is
4779/// the window it already shows over the frames it already takes.
4780fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
4781 let per_frame = s.window_us() / i64::from(s.frames.max(1));
4782 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
4783 match edge {
4784 Edge::Start => {
4785 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
4786 s.frames = s.end() - to;
4787 s.start = to;
4788 }
4789 Edge::End => {
4790 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
4791 s.frames = to - s.start;
4792 }
4793 }
4794 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
4795}
4796
4797/// The grouping invariant, checked in release at [`Project::from_parts`] and
4798/// asserted by the tests after every edit: a link id names **at most one**
4799/// placement per lane -- a clip on a media lane or a caption on a subtitle
4800/// one, whichever carries it. That is all "these move together" can mean now
4801/// that a group is assembled by hand: the members keep their own spans and
4802/// their own offsets, and what binds them is the id alone.
4803///
4804/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
4805/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
4806/// placements of one group may cover different frames -- the offset-preserving
4807/// group a hand builds with [`Project::group_all`], which a drag moves by one
4808/// delta rather than by one span.
4809///
4810/// A link no other lane carries is legal and is not an error: lifting one half
4811/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
4812/// timeline has to load again.
4813/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
4814/// asked by the sweep suite's universal law.
4815#[cfg(test)]
4816pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
4817 links_are_consistent(&p.lanes)
4818}
4819
4820fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
4821 let handles = handles(lanes);
4822 for (data, lane) in lanes.iter().zip(&handles) {
4823 for (i, c) in data.clips.iter().enumerate() {
4824 let Some(id) = c.link else { continue };
4825 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
4826 return Err(
4827 format!("link {id} names two clips in the {} lane", lane.label()).into(),
4828 );
4829 }
4830 }
4831 // ...and the same for the captions, in their own list on the same lane:
4832 // a subtitle lane holds no `Clip`, so this is the only list a caption's
4833 // id could be doubled on.
4834 for (i, s) in data.subs.iter().enumerate() {
4835 let Some(id) = s.link else { continue };
4836 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
4837 return Err(format!(
4838 "link {id} names two captions in the {} lane",
4839 lane.label()
4840 )
4841 .into());
4842 }
4843 }
4844 }
4845 Ok(())
4846}
4847
4848/// Removes the timeline frames `[start, end)` from `clips`: placements inside
4849/// it go, one straddling it is split in two, one overlapping an edge is
4850/// trimmed. Source frames follow the trim, so what is left plays what it always
4851/// played. Leaves the lane sorted and disjoint.
4852///
4853/// A piece the hole cut is no longer the take its group id names -- and both
4854/// halves of a straddled placement carrying that id would be the same id twice
4855/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
4856fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
4857 let mut out = Vec::with_capacity(clips.len() + 1);
4858 for c in clips.drain(..) {
4859 // Disjoint from the hole: untouched.
4860 if c.end() <= start || c.start >= end {
4861 out.push(c);
4862 continue;
4863 }
4864 // The head that survives in front of the hole -- as much source as fits
4865 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
4866 // which at real time is that room itself. Never *more*: a head that
4867 // outgrew its room would reach into the hole it is being cut out of,
4868 // which is exactly the overlap a slow clip punched at a frame its rate
4869 // cannot address used to leave (at 0.25x a single source frame is four
4870 // timeline frames, and three frames of room hold none of it). `None`
4871 // there means no remainder at all, and the piece simply goes.
4872 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
4873 && c.start < start
4874 {
4875 out.push(Clip {
4876 out_frame: c.in_frame + keep.min(c.len()),
4877 link: None,
4878 ..c
4879 });
4880 }
4881 // ...and the tail behind it, which keeps reading up to where it would
4882 // have: measured from its out-point for the head's reason, so what it
4883 // occupies still ends where the whole clip did -- and dropped whole on
4884 // the same `None`.
4885 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
4886 && c.end() > end
4887 {
4888 out.push(Clip {
4889 start: end,
4890 in_frame: c.out_frame - keep.min(c.len()),
4891 link: None,
4892 ..c
4893 });
4894 }
4895 }
4896 *clips = out;
4897}
4898
4899/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
4900/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
4901/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
4902/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
4903/// the caller.
4904fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
4905 for &i in on {
4906 let clips = &mut lanes[i].clips;
4907 clear(clips, at, at + len);
4908 for c in clips.iter_mut().filter(|c| c.start >= at) {
4909 c.start -= len;
4910 }
4911 debug_assert!(sorted_disjoint(clips));
4912 // The subtitle lanes close the hole with everything else: a caption
4913 // left standing where the picture it belongs to was cut out is the
4914 // desync a lane model exists to make impossible.
4915 let subs = &mut lanes[i].subs;
4916 sub_clear(subs, at, at + len);
4917 for s in subs.iter_mut().filter(|s| s.start >= at) {
4918 s.start -= len;
4919 }
4920 debug_assert!(subs_sorted_disjoint(subs));
4921 }
4922}
4923
4924/// Every lane, as the index list the two above take: what "the whole timeline"
4925/// is spelled as, and the scope [`Project::ripple_delete`] and
4926/// [`Project::split`] have always had.
4927fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
4928 (0..lanes.len()).collect()
4929}
4930
4931/// A caller's region list as a batch may use it: sorted by start, empty entries
4932/// dropped, and touching or overlapping entries merged into one.
4933///
4934/// Overlapping regions are the one thing a batch cannot take -- cutting the
4935/// second would cut frames the first already moved -- and a detector handing
4936/// back two that touch means one silence, not two cuts. Merged rather than
4937/// refused: this is arithmetic on a preview, not a user's mistake.
4938fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
4939 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
4940 sorted.sort_by_key(|&(at, _)| at);
4941 let mut out: Vec<(u32, u32)> = Vec::new();
4942 for (at, len) in sorted {
4943 let end = at.saturating_add(len);
4944 match out.last_mut() {
4945 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
4946 _ => out.push((at, len)),
4947 }
4948 }
4949 out
4950}
4951
4952/// Slides everything from `at` on later by `len`, splitting a placement that
4953/// straddles `at` so the two halves end up on either side of the hole. The
4954/// insert half of a rippling paste. The two halves lose the group id for the
4955/// reason [`clear`] gives.
4956fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
4957 if let Some(idx) = splittable(clips, at) {
4958 let mut tail = clips[idx];
4959 // The cut in *source* frames, at the clip's own rate. `splittable` has
4960 // already refused a frame the rate cannot address, which is why
4961 // [`Project::paste`] refuses one too rather than opening room inside a
4962 // clip that cannot be cut there.
4963 tail.in_frame = split_source(&tail, at).expect("splittable said so");
4964 tail.start = at;
4965 tail.link = None;
4966 clips[idx].out_frame = tail.in_frame;
4967 clips[idx].link = None;
4968 clips.insert(idx + 1, tail);
4969 }
4970 for c in clips.iter_mut().filter(|c| c.start >= at) {
4971 c.start += len;
4972 }
4973}
4974
4975/// Absolute, symlink-resolved when the file is reachable; the path as given
4976/// when it is not -- an unreadable path still deserves an index, it simply
4977/// dedups by spelling.
4978pub(crate) fn canonical(path: &Path) -> PathBuf {
4979 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
4980}
4981
4982#[cfg(test)]
4983mod tests {
4984 use super::*;
4985
4986 const FPS: f64 = 30.0;
4987 /// Never opened -- `Project` is pure data, so a path that does not exist is
4988 /// simply a path that dedups by spelling.
4989 const FILE: &str = "/nonexistent/a.mp4";
4990 const FILE2: &str = "/nonexistent/b.mp4";
4991
4992 /// A contiguous placement, group id ignored: what most assertions compare.
4993 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
4994 Clip {
4995 start,
4996 in_frame,
4997 out_frame,
4998 source,
4999 link: None,
5000 eq: None,
5001 color: None,
5002 fit: FitPolicy::default(),
5003 speed: Speed::NORMAL,
5004 }
5005 }
5006
5007 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5008 /// apart -- which is what makes the table's dedup and its prune visible.
5009 fn band_at(n: u32) -> EqParams {
5010 EqParams {
5011 bands: vec![crate::eq::Band {
5012 freq_hz: 1000.0,
5013 gain_db: f64::from(n) as f32 * 1.5,
5014 q: 0.707,
5015 kind: crate::eq::BandKind::Peak,
5016 }],
5017 }
5018 }
5019
5020 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5021 /// for the colour table.
5022 fn grade_at(n: u32) -> ColorParams {
5023 ColorParams {
5024 brightness: f64::from(n) as f32 * 0.05,
5025 ..Default::default()
5026 }
5027 }
5028
5029 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5030 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5031 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5032 }
5033
5034 /// Every lane with its group ids blanked, for comparing shape.
5035 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5036 p.lanes()
5037 .into_iter()
5038 .map(|l| {
5039 p.lane(l)
5040 .iter()
5041 .map(|c| Clip { link: None, ..*c })
5042 .collect()
5043 })
5044 .collect()
5045 }
5046
5047 /// The *source frame* every timeline frame reads, per lane -- the traversal
5048 /// a player performs. Deliberately not the clip index: a split changes which
5049 /// clip a frame belongs to, and nothing else.
5050 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
5051 (0..p.timeline_frames() + 2)
5052 .map(|f| {
5053 p.lanes()
5054 .into_iter()
5055 .map(|l| p.map(l, f).map(|(_, source)| source))
5056 .collect()
5057 })
5058 .collect()
5059 }
5060
5061 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
5062 /// fixture. Built through `split` so the constructor path is exercised too.
5063 fn three() -> Project {
5064 let mut p = Project::single(FILE, 9);
5065 assert!(p.split(3));
5066 assert!(p.split(5));
5067 assert_eq!(
5068 shape(&p),
5069 [
5070 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5071 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5072 ]
5073 );
5074 p
5075 }
5076
5077 #[test]
5078 fn single_is_the_whole_file_on_both_lanes() {
5079 let p = Project::single(FILE, 150);
5080 assert_eq!(p.clips().len(), 1);
5081 assert_eq!(p.lane(Lane::A1).len(), 1);
5082 assert_eq!(p.timeline_frames(), 150);
5083 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5084 // grouped: video and audio carry the same link
5085 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5086 assert!(p.clips()[0].link.is_some());
5087 // degenerate mapping: timeline == source
5088 assert_eq!(p.map_timeline(0), Some((0, 0)));
5089 assert_eq!(p.map_timeline(149), Some((0, 149)));
5090 assert_eq!(p.map_timeline(150), None);
5091 // never-empty invariant survives a bogus frame count
5092 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5093 }
5094
5095 #[test]
5096 fn split_cuts_every_lane_and_regroups_it_back() {
5097 let mut p = Project::single(FILE, 9);
5098 let before = traversal(&p);
5099 let before_shape = shape(&p);
5100
5101 assert!(p.split(4));
5102 for l in p.lanes() {
5103 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5104 }
5105 // The two sides are two groups, one per side, matching across the lanes.
5106 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5107 assert_eq!(v[0].link, a[0].link);
5108 assert_eq!(v[1].link, a[1].link);
5109 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5110 // A split changes no mapping, in either lane.
5111 assert_eq!(traversal(&p), before, "a split moves nothing");
5112
5113 assert!(p.regroup(4), "the inverse rejoins them");
5114 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5115 assert_eq!(traversal(&p), before);
5116 assert_eq!(
5117 p.lane(Lane::V1)[0].link,
5118 p.lane(Lane::A1)[0].link,
5119 "and the rejoined clip is one group again"
5120 );
5121 }
5122
5123 /// The music video's own path: the take comes apart into halves that carry
5124 /// ids of their own, one undo puts it back, and two clips over the same
5125 /// frames become one take again by hand.
5126 #[test]
5127 fn a_take_comes_apart_and_goes_back_together() {
5128 let mut p = Project::single(FILE, 9);
5129 let one = p.clips()[0].link.expect("a fresh project is one take");
5130 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5131
5132 // A third lane in the same group -- and the merge case with it: a
5133 // placement is in no group, and grouping it in leaves *one* group.
5134 let v2 = p.add_lane(LaneKind::Video);
5135 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5136 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
5137 p.group(Lane::V1, 0, v2, 0)
5138 .expect("the same frames, one lane over");
5139 let id = p.clips()[0].link.expect("still a group");
5140 assert!(
5141 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5142 "one id over the three, not two groups sharing a span"
5143 );
5144 links_are_consistent(&p.lanes).expect("one id, one span");
5145
5146 // Detached by the sound: every half of the group, not only the two.
5147 assert!(p.ungroup(Lane::A1, 0));
5148 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
5149 assert!(
5150 ids.iter().all(Option::is_some),
5151 "a half keeps an id of its own"
5152 );
5153 assert!(
5154 ids.iter()
5155 .enumerate()
5156 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
5157 "and no two halves are the same group any more: {ids:?}"
5158 );
5159 links_are_consistent(&p.lanes).expect("a lone id is legal");
5160
5161 // One snapshot for the whole detach.
5162 assert!(p.undo());
5163 assert!(
5164 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5165 "one undo puts the whole group back"
5166 );
5167
5168 // And back together by hand: the two the pointer named, and only them.
5169 assert!(p.ungroup(Lane::V1, 0));
5170 p.group(Lane::V1, 0, Lane::A1, 0)
5171 .expect("both cover [0, 9)");
5172 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
5173 assert_ne!(
5174 p.lane(v2)[0].link,
5175 p.lane(Lane::V1)[0].link,
5176 "the third half stayed detached"
5177 );
5178 links_are_consistent(&p.lanes).expect("one id, one span");
5179 }
5180
5181 /// What a group may not be, and what a detach has nothing to take apart --
5182 /// none of which may cost an undo step.
5183 #[test]
5184 fn a_group_is_one_span_and_one_clip_per_lane() {
5185 let mut p = three();
5186 let before = shape(&p);
5187 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
5188
5189 assert!(
5190 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
5191 "two clips of one lane are never one take"
5192 );
5193 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
5194 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
5195 assert!(
5196 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
5197 "{spans}"
5198 );
5199 assert!(
5200 spans.contains("trim them to matching bounds first"),
5201 "{spans}"
5202 );
5203 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
5204
5205 // A half nothing else is grouped with is already detached, a placement
5206 // is in no group at all, and an index that is not there has nothing to
5207 // detach either.
5208 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
5209 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
5210 assert!(p.lift(Lane::A1, 0));
5211 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
5212 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
5213
5214 // Two undos, one per edit: not one of the refusals pushed a snapshot.
5215 assert!(p.undo());
5216 assert!(p.undo());
5217 assert_eq!(shape(&p), before);
5218 }
5219
5220 /// Where a re-rate puts a playhead: the scene under the cursor stays the
5221 /// scene under the cursor, measured the way a viewer would -- the source
5222 /// frame playing at the playhead is the same frame after the write, at
5223 /// every playhead position the re-rate can catch one.
5224 #[test]
5225 fn a_re_rate_keeps_the_frame_under_the_playhead() {
5226 let caption = |start: u32, frames: u32| SubClip {
5227 start,
5228 frames,
5229 track: 0,
5230 in_us: 0,
5231 out_us: i64::from(frames) * 1_000_000,
5232 link: None,
5233 };
5234 let track = || SubtitleTrack {
5235 path: FILE.into(),
5236 track: None,
5237 language: "eng".into(),
5238 name: String::new(),
5239 label: "eng".into(),
5240 cues: Vec::new(),
5241 bitmap: false,
5242 refused: None,
5243 };
5244 // A group of a 300-frame clip and a caption offset 30 frames into it.
5245 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
5246 let s1 = p.add_lane(LaneKind::Subtitle);
5247 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
5248 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5249
5250 // The frame playing at `at`: which clip, and which source frame of it.
5251 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
5252 p.span_at(Lane::V1, at)
5253 .and_then(|s| s.from.map(|(source, from)| (source, from)))
5254 };
5255
5256 // Inside the held clip: the source frame under the playhead is the
5257 // same one after the re-rate, at 2x and at half speed both.
5258 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
5259 let at = 120;
5260 let before = playing(&p, at).expect("a clip under the playhead");
5261 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
5262 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
5263 .expect("room for it");
5264 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
5265 assert_eq!(before, after, "{what}: the same source frame plays");
5266 // ...and the write itself is untouched by the question.
5267 assert!(p.undo(), "{what}: one step back");
5268 }
5269
5270 // Past the group -- the clip ends at 300 and the caption at 270, so
5271 // from 300 on nothing is re-timed under the playhead: unmoved.
5272 for at in [300u32, 301, 1_000] {
5273 assert_eq!(
5274 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
5275 Some(at),
5276 "at {at}: outside every member, unmoved"
5277 );
5278 }
5279 // The boundary is exact: the held clip's own last frame (299) maps
5280 // to its new one (149 -- the last frame inside [0, 150), where the
5281 // shrunken clip's last source frame plays), and its first stays put.
5282 assert_eq!(
5283 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
5284 Some(149)
5285 );
5286 assert_eq!(
5287 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
5288 Some(0)
5289 );
5290 // A spot the caption shares with the clip maps by the clip (it is
5291 // what is *playing* there): the held clip's own proportion, which on
5292 // this fixture is also its head.
5293 assert_eq!(
5294 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
5295 Some(45),
5296 "the clip under the caption owns the spot"
5297 );
5298 }
5299
5300 /// A playhead inside another clip member of the group: that member keeps
5301 /// its own head, so the mapping is by its proportion and not the held
5302 /// clip's -- and the frame under the cursor is still the frame that was.
5303 #[test]
5304 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
5305 let mut p = Project::single(FILE, 300);
5306 // A second clip, grouped with the first but starting 300 later: the
5307 // head the group shares and its own differ by exactly that.
5308 let v2 = p.add_lane(LaneKind::Video);
5309 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
5310 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
5311 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
5312
5313 let at = 450; // inside the second member, 150 past its head
5314 let before = p.span_at(v2, at).and_then(|s| s.from);
5315 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
5316 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5317 .expect("room for it");
5318 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
5319 assert_eq!(before, after, "the second member's own frame plays");
5320 // ...and the mapping itself: 150 past its head halves, the head stays.
5321 assert_eq!(mapped, Some(375));
5322 }
5323
5324 /// The link counter a load seeds sits past every id the file names,
5325 /// captions included: a hand-grouped caption may carry the highest id there
5326 /// is, and a counter that read the clips alone would hand it to the next
5327 /// group that asked -- silently grouping the caption with clips it never
5328 /// met.
5329 #[test]
5330 fn the_link_counter_sits_past_a_caption_only_id() {
5331 let track = || SubtitleTrack {
5332 path: FILE.into(),
5333 track: None,
5334 language: "eng".into(),
5335 name: String::new(),
5336 label: "eng".into(),
5337 cues: Vec::new(),
5338 bitmap: false,
5339 refused: None,
5340 };
5341 let mut p = Project::single(FILE, 9);
5342 p.add_lane(LaneKind::Subtitle);
5343 let caption = SubClip {
5344 start: 0,
5345 frames: 6,
5346 track: 0,
5347 in_us: 0,
5348 out_us: 6_000_000,
5349 // The highest id in the file, and only a caption carries it.
5350 link: Some(1),
5351 };
5352 let mut p = p
5353 .with_subtitles(vec![track()])
5354 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
5355 .expect("a caption may carry the file's highest id");
5356
5357 // A new group on lanes the caption is not on mints the next id -- which
5358 // must not be the caption's.
5359 let v2 = p.add_lane(LaneKind::Video);
5360 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5361 p.group_all(&[(Lane::V1, 0), (v2, 0)])
5362 .expect("the clips group");
5363 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
5364 assert_ne!(
5365 minted,
5366 1,
5367 "the caption's id is not re-issued to clips"
5368 );
5369 assert_eq!(
5370 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
5371 Some(1),
5372 "the caption keeps its own group"
5373 );
5374 assert!(links_are_consistent(&p.lanes).is_ok());
5375 }
5376
5377 /// A rate re-times the caption members of the group by the ratio it gives
5378 /// the held clip: the span on the timeline compresses about the held clip's
5379 /// head, the words' own window untouched -- and one undo puts it back.
5380 #[test]
5381 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
5382 let caption = |start: u32, frames: u32| SubClip {
5383 start,
5384 frames,
5385 track: 0,
5386 in_us: 0,
5387 out_us: i64::from(frames) * 1_000_000,
5388 link: None,
5389 };
5390 let track = || SubtitleTrack {
5391 path: FILE.into(),
5392 track: None,
5393 language: "eng".into(),
5394 name: String::new(),
5395 label: "eng".into(),
5396 cues: Vec::new(),
5397 bitmap: false,
5398 refused: None,
5399 };
5400 let grouped = || {
5401 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5402 let s1 = p.add_lane(LaneKind::Subtitle);
5403 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5404 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5405 (p, s1)
5406 };
5407
5408 // An aligned take, doubled: the caption plays in half the frames.
5409 let (mut p, s1) = grouped();
5410 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5411 .expect("room for it");
5412 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
5413 let s = p.sub_lane(s1)[0];
5414 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
5415 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
5416 assert!(links_are_consistent(&p.lanes).is_ok());
5417 assert!(p.undo());
5418 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
5419
5420 // An offset group, slowed to half: the caption's *offset from the held
5421 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
5422 // 0.5x, and still ends where the clip does.
5423 let (mut p, s1) = grouped();
5424 p.lift_sub(s1, 0);
5425 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
5426 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5427 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
5428 .expect("room for it");
5429 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
5430 let s = p.sub_lane(s1)[0];
5431 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
5432 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
5433
5434 // A stretch that runs the caption into its neighbour is refused, by
5435 // lane and frame, and costs no undo step.
5436 let (mut p, s1) = grouped();
5437 p.lift_sub(s1, 0);
5438 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5439 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
5440 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5441 let history = p.history.len();
5442 let err = p
5443 .set_speed(Lane::V1, 0, Speed::from_permille(500))
5444 .unwrap_err()
5445 .to_string();
5446 assert!(
5447 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
5448 "{err}"
5449 );
5450 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
5451 }
5452
5453 /// The silence scan's speed-up re-times the captions on a scoped lane with
5454 /// everything else: the piece inside the region plays in the region's new
5455 /// frames, and what sits behind the region slides up with the clips.
5456 #[test]
5457 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
5458 let caption = |start: u32, frames: u32| SubClip {
5459 start,
5460 frames,
5461 track: 0,
5462 in_us: 0,
5463 out_us: i64::from(frames) * 1_000_000,
5464 link: None,
5465 };
5466 let track = || SubtitleTrack {
5467 path: FILE.into(),
5468 track: None,
5469 language: "eng".into(),
5470 name: String::new(),
5471 label: "eng".into(),
5472 cues: Vec::new(),
5473 bitmap: false,
5474 refused: None,
5475 };
5476 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5477 let s1 = p.add_lane(LaneKind::Subtitle);
5478 // Words over the region [30, 60) and words behind it.
5479 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5480 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
5481
5482 // The region [30, 60) plays at 4x: 30 frames become 8, everything
5483 // behind slides up 22.
5484 // The scope is what the card's Take row says, caption lane included.
5485 p.speed_regions(
5486 &[(30, 30)],
5487 Speed::from_permille(4000),
5488 &[Lane::V1, Lane::A1, s1],
5489 )
5490 .expect("the region speeds up");
5491 let subs = p.sub_lane(s1);
5492 assert_eq!(
5493 (subs[0].start, subs[0].frames),
5494 (30, 8),
5495 "the piece inside plays in the region's new frames"
5496 );
5497 assert_eq!(
5498 (subs[1].start, subs[1].frames),
5499 (38, 30),
5500 "the piece behind slides up by what the region gave back"
5501 );
5502 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
5503 }
5504
5505 /// [`Project::speeded_playhead`]'s caption arm fires only when the
5506 /// playhead is inside a caption member and outside every clip member --
5507 /// a shape every other fixture avoids by keeping its caption inside the
5508 /// held clip. Here the caption overhangs the clip's tail, and the
5509 /// playhead standing in that overhang is answered by the caption's own
5510 /// piece: it scales about the held clip's head by the held clip's own
5511 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
5512 #[test]
5513 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
5514 let caption = |start: u32, frames: u32| SubClip {
5515 start,
5516 frames,
5517 track: 0,
5518 in_us: 0,
5519 out_us: i64::from(frames) * 1_000_000,
5520 link: None,
5521 };
5522 let track = || SubtitleTrack {
5523 path: FILE.into(),
5524 track: None,
5525 language: "eng".into(),
5526 name: String::new(),
5527 label: "eng".into(),
5528 cues: Vec::new(),
5529 bitmap: false,
5530 refused: None,
5531 };
5532 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5533 let s1 = p.add_lane(LaneKind::Subtitle);
5534 // The caption spans [80, 100) -- ten frames past the clip's own end
5535 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
5536 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
5537 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5538 // At 2x the clip halves to 45 frames; the overhang frame 95, which
5539 // no clip member's old span reaches, is the caption's own question:
5540 // half of 95 is 47.5, rounded to 48.
5541 assert_eq!(
5542 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
5543 Some(48),
5544 "the overhang frame answers through the caption's own piece"
5545 );
5546 }
5547
5548 /// `write_speed` and `speeded_playhead` are two questions of the SAME
5549 /// map ([`map`]'s architecture law): a caption's landed span comes from
5550 /// the map's own ends, and the playhead standing at the caption's own
5551 /// last frame before the write has to land exactly where the write put
5552 /// it -- across clip lengths and rates that round differently, and an
5553 /// odd-length caption straddling the clip's own tail edge, the corner
5554 /// where `write_speed` used to answer a frame short.
5555 #[test]
5556 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
5557 let caption = |start: u32, frames: u32| SubClip {
5558 start,
5559 frames,
5560 track: 0,
5561 in_us: 0,
5562 out_us: i64::from(frames) * 1_000_000,
5563 link: None,
5564 };
5565 let track = || SubtitleTrack {
5566 path: FILE.into(),
5567 track: None,
5568 language: "eng".into(),
5569 name: String::new(),
5570 label: "eng".into(),
5571 cues: Vec::new(),
5572 bitmap: false,
5573 refused: None,
5574 };
5575 for &len in &[90u32, 91, 177, 300, 301] {
5576 for &permille in &[500u16, 2000, 2500, 3000] {
5577 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
5578 let s1 = p.add_lane(LaneKind::Subtitle);
5579 // An odd-length caption straddling the clip's tail edge: its
5580 // own last frame lands past the held clip.
5581 let c_start = len.saturating_sub(3);
5582 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
5583 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5584 let speed = Speed::from_permille(permille);
5585 let last = c_start + 7 - 1;
5586 let mapped = p
5587 .speeded_playhead(Lane::V1, 0, speed, last)
5588 .expect("the caption is there");
5589 if p.set_speed(Lane::V1, 0, speed).is_err() {
5590 continue; // a refusal changes nothing: not this law's cell
5591 }
5592 let landed = p.sub_lane(s1)[0];
5593 if permille >= 1000 {
5594 // A speed-up compresses the timeline: many old frames
5595 // share one new frame, so the caption's own last old
5596 // frame lands flush with the write's own boundary --
5597 // the exact law [`write_speed`]'s worked drift-fix case
5598 // is stated against.
5599 assert_eq!(
5600 mapped,
5601 landed.end() - 1,
5602 "len {len} permille {permille}: the playhead at the caption's own \
5603 last frame lands where the write actually put it"
5604 );
5605 } else {
5606 // A slow-down expands it: one old frame becomes several
5607 // new ones, and `apply` answers where that frame's own
5608 // block *starts*, not where the caption's last new
5609 // frame (the end of that same block) sits -- a
5610 // one-frame gap inherent to the piece's own semantics,
5611 // not a drift between the two callers. Both still have
5612 // to agree the answer sits inside the caption the write
5613 // actually landed.
5614 assert!(
5615 (landed.start..landed.end()).contains(&mapped),
5616 "len {len} permille {permille}: the playhead lands inside the \
5617 caption the write actually put ({landed:?}), got {mapped}"
5618 );
5619 }
5620 }
5621 }
5622 }
5623
5624 /// A grouped caption's cues re-time with its clip: the placement's window
5625 /// crossed the timeline at its own proportion before any rate, and a
5626 /// re-rate changes that proportion (the frames compress, the window does
5627 /// not). A cue eight seconds into a window played at 2x crosses the screen
5628 /// four seconds in -- and at unity every cue lands exactly where it always
5629 /// did, byte for byte.
5630 #[test]
5631 fn a_grouped_captions_cues_re_time_with_its_clip() {
5632 let track = SubtitleTrack {
5633 path: FILE.into(),
5634 track: None,
5635 language: "eng".into(),
5636 name: String::new(),
5637 label: "eng".into(),
5638 cues: vec![crate::subtitle::Cue {
5639 start_us: 8_000_000,
5640 end_us: 9_000_000,
5641 text: "late line".into(),
5642 image: None,
5643 }],
5644 bitmap: false,
5645 refused: None,
5646 };
5647 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
5648 let s1 = p.add_lane(LaneKind::Subtitle);
5649 // Ten seconds of the track over ten seconds of timeline: unity.
5650 p.place_sub(
5651 s1,
5652 0,
5653 SubClip {
5654 start: 0,
5655 frames: 300,
5656 track: 0,
5657 in_us: 0,
5658 out_us: 10_000_000,
5659 link: None,
5660 },
5661 )
5662 .expect("placed");
5663
5664 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
5665 let unity = p.sub_lane_cues(s1, FPS);
5666 assert_eq!(
5667 unity
5668 .iter()
5669 .map(|c| (c.start_us, c.end_us, &*c.text))
5670 .collect::<Vec<_>>(),
5671 [(8_000_000, 9_000_000, "late line")],
5672 "a unity placement maps exactly as it always did"
5673 );
5674
5675 // Grouped with the clip and re-rated to 2x: the same window now crosses
5676 // in half the time, so the cue at 8s of it lands 4s in.
5677 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5678 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5679 .expect("room for it");
5680 let re_timed = p.sub_lane_cues(s1, FPS);
5681 assert_eq!(
5682 re_timed
5683 .iter()
5684 .map(|c| (c.start_us, c.end_us))
5685 .collect::<Vec<_>>(),
5686 [(4_000_000, 4_500_000)],
5687 "the cue crosses with the clip's new rate"
5688 );
5689 }
5690
5691 /// A video arriving on a timeline of words mutates none of them: the
5692 /// import's rippling insert used to open room on the subtitle lanes too,
5693 /// splitting a caption it landed inside and sliding the rest behind the
5694 /// video -- the hand asked for an add, and got a cut it never made. The
5695 /// words keep their own clock; co-travel is what a group is for.
5696 #[test]
5697 fn an_arriving_clip_never_touches_the_captions() {
5698 let caption = |start: u32, frames: u32| SubClip {
5699 start,
5700 frames,
5701 track: 0,
5702 in_us: i64::from(start) * 1_000_000 / 30,
5703 out_us: i64::from(start + frames) * 1_000_000 / 30,
5704 link: None,
5705 };
5706 let track = || SubtitleTrack {
5707 path: FILE.into(),
5708 track: None,
5709 language: "eng".into(),
5710 name: String::new(),
5711 label: "eng".into(),
5712 cues: Vec::new(),
5713 bitmap: false,
5714 refused: None,
5715 };
5716 // A timeline of words alone: 60 frames of caption, no media clips.
5717 let mut p = Project::single(FILE, 60)
5718 .with_subtitles(vec![track()]);
5719 for l in [Lane::V1, Lane::A1] {
5720 while !p.lane(l).is_empty() {
5721 p.lift(l, 0);
5722 }
5723 }
5724 let s1 = p.add_lane(LaneKind::Subtitle);
5725 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
5726 let before = p.sub_lane(s1).to_vec();
5727
5728 // The video lands BEFORE the caption's span: nothing moves.
5729 let vid = clip(0, 0, 30, 0);
5730 assert!(p.paste(0, vid), "the video goes down at the head");
5731 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
5732
5733 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
5734 // byte the placement the hand made.
5735 assert!(p.paste(15, vid), "a second video lands inside the caption");
5736 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
5737 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
5738 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
5739 assert!(links_are_consistent(&p.lanes).is_ok());
5740 }
5741
5742 /// The region's caption pieces re-time by mapped boundaries forced apart:
5743 /// rounding start and length independently can land two cues on one frame,
5744 /// and the artifact is clamped -- one frame each, in order, none past the
5745 /// region's new end -- never an overlap on the lane.
5746 #[test]
5747 fn a_regions_caption_pieces_never_round_onto_one_another() {
5748 let caption = |start: u32, frames: u32| SubClip {
5749 start,
5750 frames,
5751 track: 0,
5752 in_us: 0,
5753 out_us: i64::from(frames) * 1_000_000,
5754 link: None,
5755 };
5756 let track = |n| SubtitleTrack {
5757 path: FILE.into(),
5758 track: None,
5759 language: "eng".into(),
5760 name: String::new(),
5761 label: format!("eng{n}"),
5762 cues: Vec::new(),
5763 bitmap: false,
5764 refused: None,
5765 };
5766 // Three lanes, one repro shape each: adjacent one-frame cues, a
5767 // three-frame pair, and the region's last cue against the first
5768 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
5769 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
5770 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
5771 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
5772 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
5773 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
5774 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
5775 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
5776 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
5777
5778 let mut scope = vec![Lane::V1, Lane::A1];
5779 scope.extend(lanes.iter().copied());
5780 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
5781 .expect("the region speeds up");
5782 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
5783 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
5784 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
5785 };
5786 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
5787 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
5788 // and the walk pushes the second to where the first ends.
5789 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
5790 // The last cue of the region ends exactly where the region now does
5791 // (frame 15), and the caption behind it lands on that same frame:
5792 // touching, never overlapping.
5793 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
5794 for &lane in &lanes {
5795 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
5796 }
5797 }
5798
5799 /// The scope law names a caption half too: a scoped cut that would move one
5800 // track of a group whose caption sits outside the scope is refused.
5801 #[test]
5802 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
5803 let caption = |start: u32, frames: u32| SubClip {
5804 start,
5805 frames,
5806 track: 0,
5807 in_us: 0,
5808 out_us: i64::from(frames) * 1_000_000,
5809 link: None,
5810 };
5811 let track = || SubtitleTrack {
5812 path: FILE.into(),
5813 track: None,
5814 language: "eng".into(),
5815 name: String::new(),
5816 label: "eng".into(),
5817 cues: Vec::new(),
5818 bitmap: false,
5819 refused: None,
5820 };
5821 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5822 let s1 = p.add_lane(LaneKind::Subtitle);
5823 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5824 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5825
5826 // The subtitle lane is not in the scope, so the group's caption half
5827 // sits outside it: refused, in the law's own words.
5828 let err = p
5829 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
5830 .unwrap_err()
5831 .to_string();
5832 assert!(
5833 err.contains("is one take with the S1 caption at frame 0"),
5834 "{err}"
5835 );
5836
5837 // ...and with the caption's lane in the scope, the cut carries it:
5838 // the words over the hole go, and the words behind slide up.
5839 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
5840 .expect("the whole group is in the scope");
5841 let subs = p.sub_lane(s1);
5842 assert_eq!(
5843 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
5844 [(0, 10), (10, 75)],
5845 "the caption is cut and shifted with the clips"
5846 );
5847 }
5848
5849 /// The caption a hand groups: `group_all` over clips *and* a caption, the
5850 /// mates riding along, the offsets kept, the refusals in words.
5851 #[test]
5852 fn a_hand_built_group_holds_clips_and_a_caption() {
5853 let caption = |start: u32, frames: u32| SubClip {
5854 start,
5855 frames,
5856 track: 0,
5857 in_us: 0,
5858 out_us: i64::from(frames) * 1_000_000,
5859 link: None,
5860 };
5861 let track = || SubtitleTrack {
5862 path: FILE.into(),
5863 track: None,
5864 language: "eng".into(),
5865 name: String::new(),
5866 label: "eng".into(),
5867 cues: Vec::new(),
5868 bitmap: false,
5869 refused: None,
5870 };
5871 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5872 let v2 = p.add_lane(LaneKind::Video);
5873 let s1 = p.add_lane(LaneKind::Subtitle);
5874 // A layer at its own offset, and a caption over the head of the take.
5875 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
5876 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
5877
5878 // Too few, one lane twice, and an index that is not there: words, no
5879 // snapshot.
5880 let history = p.history.len();
5881 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
5882 assert!(p
5883 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
5884 .unwrap_err()
5885 .to_string()
5886 .contains("V1 is picked twice"));
5887 assert!(p
5888 .group_all(&[(Lane::V1, 0), (s1, 9)])
5889 .unwrap_err()
5890 .to_string()
5891 .contains("no subtitle 9"));
5892 assert_eq!(p.history.len(), history, "refusals cost no undo step");
5893
5894 // The group: the picture, the layer, and the caption -- and the sound
5895 // the picture was already grouped with comes along unasked.
5896 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
5897 .expect("three picks, three lanes");
5898 let id = p.lane(Lane::V1)[0].link.expect("grouped");
5899 for lane in [Lane::V1, Lane::A1, v2] {
5900 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
5901 }
5902 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
5903 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
5904 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
5905 assert!(links_are_consistent(&p.lanes).is_ok());
5906 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
5907
5908 // ...and one undo takes it apart again.
5909 assert!(p.undo());
5910 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
5911
5912 // Detach names a caption like it names a clip: every member an id of
5913 // its own, which is never `None` (see `ungroup`).
5914 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
5915 assert!(p.ungroup(s1, 0));
5916 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
5917 assert!(loose_sub.is_some() && loose_clip.is_some());
5918 assert_ne!(loose_sub, loose_clip);
5919 assert!(links_are_consistent(&p.lanes).is_ok());
5920 }
5921
5922 /// Two captions on one sub lane, each already grouped with a *different*
5923 /// clip: `group_all` over both those clips would merge the two existing
5924 /// groups into one id and leave both captions on `s1` carrying it --
5925 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
5926 /// group closes. Refused by name, and nothing moves.
5927 #[test]
5928 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
5929 let caption = |start: u32, frames: u32| SubClip {
5930 start,
5931 frames,
5932 track: 0,
5933 in_us: 0,
5934 out_us: i64::from(frames) * 1_000_000,
5935 link: None,
5936 };
5937 let track = || SubtitleTrack {
5938 path: FILE.into(),
5939 track: None,
5940 language: "eng".into(),
5941 name: String::new(),
5942 label: "eng".into(),
5943 cues: Vec::new(),
5944 bitmap: false,
5945 refused: None,
5946 };
5947 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5948 let v2 = p.add_lane(LaneKind::Video);
5949 let s1 = p.add_lane(LaneKind::Subtitle);
5950 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
5951 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
5952 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5953 // V1 grouped with the first caption, v2 with the second -- two
5954 // separate groups, each already one member per lane.
5955 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5956 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
5957 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
5958
5959 let history = p.history.len();
5960 let err = p
5961 .group_all(&[(Lane::V1, 0), (v2, 0)])
5962 .unwrap_err()
5963 .to_string();
5964 assert!(err.contains("one placement per lane"), "{err}");
5965 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
5966 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
5967 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
5968 assert!(links_are_consistent(&p.lanes).is_ok());
5969 }
5970
5971 /// A split hands the caption of a group the same ids it hands the clips:
5972 /// the left halves keep the group, the right halves share a fresh one.
5973 #[test]
5974 fn a_split_cuts_a_grouped_caption_with_its_clips() {
5975 let caption = |start: u32, frames: u32| SubClip {
5976 start,
5977 frames,
5978 track: 0,
5979 in_us: 0,
5980 out_us: i64::from(frames) * 1_000_000,
5981 link: None,
5982 };
5983 let track = || SubtitleTrack {
5984 path: FILE.into(),
5985 track: None,
5986 language: "eng".into(),
5987 name: String::new(),
5988 label: "eng".into(),
5989 cues: Vec::new(),
5990 bitmap: false,
5991 refused: None,
5992 };
5993 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5994 let s1 = p.add_lane(LaneKind::Subtitle);
5995 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
5996 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5997 let take = p.lane(Lane::V1)[0].link.expect("the group id");
5998
5999 assert!(p.split(4));
6000 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
6001 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
6002 assert_eq!(left.frames, 4);
6003 assert_eq!(
6004 right.link,
6005 p.lane(Lane::V1)[1].link,
6006 "the caption's tail shares the clips' fresh id"
6007 );
6008 assert_ne!(right.link, Some(take));
6009 assert!(links_are_consistent(&p.lanes).is_ok());
6010
6011 // Regroup at the seam restores the take, caption included.
6012 assert!(p.regroup(4));
6013 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
6014 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
6015 }
6016
6017 /// Deleting a member of a hand-built group takes the group: every
6018 /// member's own span out of its own lane, hole closed -- the lanes may
6019 /// end up out of step, which is what one undo restores together.
6020 #[test]
6021 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
6022 let caption = |start: u32, frames: u32| SubClip {
6023 start,
6024 frames,
6025 track: 0,
6026 in_us: 0,
6027 out_us: i64::from(frames) * 1_000_000,
6028 link: None,
6029 };
6030 let track = || SubtitleTrack {
6031 path: FILE.into(),
6032 track: None,
6033 language: "eng".into(),
6034 name: String::new(),
6035 label: "eng".into(),
6036 cues: Vec::new(),
6037 bitmap: false,
6038 refused: None,
6039 };
6040 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6041 let s1 = p.add_lane(LaneKind::Subtitle);
6042 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6043 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6044 // A neighbour on a lane the group does not touch.
6045 let v2 = p.add_lane(LaneKind::Video);
6046 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
6047
6048 // By the picture or by the caption, the same whole-group delete.
6049 assert!(p.delete_sub_in(s1, 0));
6050 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
6051 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
6052 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
6053 assert!(links_are_consistent(&p.lanes).is_ok());
6054 assert!(p.undo(), "one step puts the group back");
6055 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
6056 }
6057
6058 /// The delete law, one statement for every anchor: a caption deleted
6059 /// WITH its group ripples its lane exactly as its clip siblings do --
6060 /// the hole closes and what follows slides up -- while a caption lifted
6061 /// alone leaves its gap, as it always has. And the delete of a grouped
6062 /// clip takes the group from whichever member was clicked.
6063 #[test]
6064 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
6065 let caption = |start: u32, frames: u32| SubClip {
6066 start,
6067 frames,
6068 track: 0,
6069 in_us: 0,
6070 out_us: i64::from(frames) * 1_000_000,
6071 link: None,
6072 };
6073 let track = || SubtitleTrack {
6074 path: FILE.into(),
6075 track: None,
6076 language: "eng".into(),
6077 name: String::new(),
6078 label: "eng".into(),
6079 cues: Vec::new(),
6080 bitmap: false,
6081 refused: None,
6082 };
6083 // V+A+S grouped, with a second caption BEHIND the group's caption:
6084 // closing the hole is what the second caption's position says.
6085 let group = || {
6086 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6087 let s1 = p.add_lane(LaneKind::Subtitle);
6088 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
6089 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
6090 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6091 (p, s1)
6092 };
6093
6094 // Deleted by the picture: all three lanes close.
6095 let (mut p, s1) = group();
6096 assert!(p.delete_in(Lane::V1, 0));
6097 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
6098 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
6099 assert_eq!(
6100 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
6101 [60],
6102 "the caption's lane closed by its own span: the follower slid up"
6103 );
6104 assert!(p.undo(), "one step");
6105 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
6106
6107 // By the sound: the same whole-group delete.
6108 let (mut p, s1) = group();
6109 assert!(p.delete_in(Lane::A1, 0));
6110 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6111 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6112
6113 // By the caption itself: the same again.
6114 let (mut p, s1) = group();
6115 assert!(p.delete_sub_in(s1, 0));
6116 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6117 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6118 assert!(links_are_consistent(&p.lanes).is_ok());
6119
6120 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6121 // unchanged.
6122 let (mut p, s1) = group();
6123 assert!(p.ungroup(s1, 0), "the caption stands alone");
6124 assert!(p.lift_sub(s1, 0));
6125 assert_eq!(
6126 p.sub_lane(s1)[0].start, 90,
6127 "the follower stayed put: a lone caption's lift is a gap"
6128 );
6129 }
6130
6131 /// Dragging a grouped caption carries its clips, one delta for all of them
6132 /// -- and a caption in no group refuses an overlap exactly as it always did.
6133 #[test]
6134 fn dragging_a_grouped_caption_carries_its_group() {
6135 let caption = |start: u32, frames: u32| SubClip {
6136 start,
6137 frames,
6138 track: 0,
6139 in_us: 0,
6140 out_us: i64::from(frames) * 1_000_000,
6141 link: None,
6142 };
6143 let track = || SubtitleTrack {
6144 path: FILE.into(),
6145 track: None,
6146 language: "eng".into(),
6147 name: String::new(),
6148 label: "eng".into(),
6149 cues: Vec::new(),
6150 bitmap: false,
6151 refused: None,
6152 };
6153 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6154 let s1 = p.add_lane(LaneKind::Subtitle);
6155 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6156 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6157
6158 // Same lane, further along: everyone moves by the same eight frames.
6159 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
6160 assert_eq!(p.sub_lane(s1)[0].start, 10);
6161 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
6162 assert!(links_are_consistent(&p.lanes).is_ok());
6163
6164 // ...and an ungrouped caption is the caption it always was.
6165 assert!(p.ungroup(s1, 0));
6166 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
6167 let s1 = q.add_lane(LaneKind::Subtitle);
6168 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
6169 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
6170 assert!(q
6171 .move_sub(s1, 0, s1, 3)
6172 .unwrap_err()
6173 .to_string()
6174 .contains("already covers"));
6175 }
6176
6177 /// A trim carries a group's caption by the same delta as its clips, clamped
6178 /// to the caption's own walls -- the offsets between the members survive.
6179 #[test]
6180 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
6181 let caption = |start: u32, frames: u32| SubClip {
6182 start,
6183 frames,
6184 track: 0,
6185 in_us: 0,
6186 out_us: i64::from(frames) * 1_000_000,
6187 link: None,
6188 };
6189 let track = || SubtitleTrack {
6190 path: FILE.into(),
6191 track: None,
6192 language: "eng".into(),
6193 name: String::new(),
6194 label: "eng".into(),
6195 cues: Vec::new(),
6196 bitmap: false,
6197 refused: None,
6198 };
6199 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6200 let s1 = p.add_lane(LaneKind::Subtitle);
6201 // The caption sits two frames into the take and ends one early. The
6202 // source runs past the clip, or there is no tail to pull out.
6203 let src = &[20];
6204 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
6205 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6206
6207 // The tail goes out by three: the clip to 12, the caption to 11.
6208 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
6209 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
6210 assert_eq!(
6211 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
6212 (2, 11),
6213 "the caption follows by the delta"
6214 );
6215 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
6216
6217 // The head comes in by two: everyone's start moves two along.
6218 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
6219 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
6220 assert!(links_are_consistent(&p.lanes).is_ok());
6221 }
6222
6223 #[test]
6224 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
6225 let mut p = three();
6226 let before = shape(&p);
6227 assert!(!p.split(0), "timeline 0 has nothing before it");
6228 assert!(!p.split(3), "existing boundary");
6229 assert!(!p.split(5), "existing boundary");
6230 assert!(!p.split(9), "one past the last frame");
6231 assert!(!p.split(1_000));
6232 assert_eq!(shape(&p), before);
6233 // one undo lands before the *second* split, so the refusals pushed nothing
6234 assert!(p.undo());
6235 assert_eq!(p.clips().len(), 2, "refused splits push no history");
6236
6237 // ...and a frame that is a gap in both lanes has nothing to split.
6238 let mut p = three();
6239 assert!(p.lift(Lane::V1, 1));
6240 assert!(p.lift(Lane::A1, 1));
6241 assert!(!p.split(4), "a gap is not a clip");
6242 }
6243
6244 #[test]
6245 fn regroup_refuses_what_a_split_could_not_have_made() {
6246 let mut p = three();
6247 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
6248 assert!(p.regroup(5));
6249 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
6250 // A boundary with a gap on one side, and one where the sources do not
6251 // meet, are both refused.
6252 let mut p = three();
6253 assert!(p.lift(Lane::V1, 1));
6254 assert!(p.lift(Lane::A1, 1));
6255 assert!(!p.regroup(3), "nothing starts at 3 any more");
6256 let mut p = three();
6257 for l in p.lanes() {
6258 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
6259 }
6260 assert!(!p.regroup(3), "source 100 does not follow source 3");
6261 assert!(!p.regroup(0), "nothing ends at 0");
6262 assert!(!p.regroup(1_000));
6263 }
6264
6265 #[test]
6266 fn map_and_spans_sweep_every_boundary() {
6267 let p = three();
6268 assert_eq!(p.timeline_frames(), 9);
6269 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
6270 // contiguous source here, so the clip index is what actually moves
6271 let expect = [
6272 (0, (0, 0)),
6273 (1, (0, 1)),
6274 (2, (0, 2)),
6275 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
6276 (4, (1, 4)),
6277 (5, (2, 5)),
6278 (6, (2, 6)),
6279 (7, (2, 7)),
6280 (8, (2, 8)),
6281 ];
6282 for (t, want) in expect {
6283 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
6284 }
6285 assert_eq!(p.map_timeline(9), None);
6286 // A span is the rest of the clip from where it was asked about.
6287 assert_eq!(
6288 p.span_at(Lane::V1, 6),
6289 Some(Span {
6290 start: 6,
6291 len: 3,
6292 from: Some((0, 6)),
6293 speed: Speed::NORMAL
6294 })
6295 );
6296 assert_eq!(p.span_at(Lane::V1, 9), None);
6297 }
6298
6299 /// The fit policy is one byte *in* the clip rather than an index into a
6300 /// table like the eq and the grade: there is nothing for a table to share.
6301 /// It costs the clip nothing at all -- the fields before it (a `usize`
6302 /// source and two `Option<u16>`s) already left the struct padded to 40
6303 /// bytes, and the byte landed in that padding. This is the assert that says
6304 /// so: a clip that grew a word grew every undo snapshot and every clipboard
6305 /// copy with it.
6306 #[test]
6307 fn a_fit_policy_costs_the_clip_no_word() {
6308 assert_eq!(
6309 std::mem::size_of::<Clip>(),
6310 40,
6311 "Clip changed size: {} bytes",
6312 std::mem::size_of::<Clip>()
6313 );
6314 }
6315
6316 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
6317 /// anything in `three()` so it is recognisable wherever it lands.
6318 const PASTED: Clip = Clip {
6319 start: 0,
6320 in_frame: 100,
6321 out_frame: 102,
6322 source: 0,
6323 link: None,
6324 eq: None,
6325 color: None,
6326 fit: FitPolicy::Fit,
6327 speed: Speed::NORMAL,
6328 };
6329
6330 #[test]
6331 fn paste_mid_clip_splits_around_it() {
6332 let mut p = three();
6333 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
6334 assert_eq!(p.timeline_frames(), 11);
6335 assert_eq!(
6336 shape(&p)[0],
6337 vec![
6338 clip(0, 0, 3, 0),
6339 clip(3, 3, 5, 0),
6340 clip(5, 5, 6, 0),
6341 clip(6, 100, 102, 0),
6342 clip(8, 6, 9, 0),
6343 ]
6344 );
6345 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
6346 // The pasted frames are exactly where they were asked for, and the
6347 // split-off remainder resumes after them.
6348 assert_eq!(p.map_timeline(6), Some((3, 100)));
6349 assert_eq!(p.map_timeline(7), Some((3, 101)));
6350 assert_eq!(p.map_timeline(8), Some((4, 6)));
6351 }
6352
6353 #[test]
6354 fn paste_at_boundary_zero_and_end() {
6355 let mut p = three();
6356 assert!(p.paste(3, PASTED), "existing boundary: no split");
6357 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
6358 assert_eq!(p.map_timeline(3), Some((1, 100)));
6359
6360 let mut p = three();
6361 assert!(p.paste(0, PASTED));
6362 assert_eq!(p.map_timeline(0), Some((0, 100)));
6363 assert_eq!(p.map_timeline(2), Some((1, 0)));
6364
6365 // At the end: appended, there being nothing in front to leave black.
6366 let mut p = three();
6367 assert!(p.paste(9, PASTED));
6368 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
6369 // Past it: down on the frame it was asked for, black in front of it --
6370 // a row let go on the open bed lands under the ghost that promised it.
6371 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
6372 assert!(p.paste(1_000, PASTED));
6373 assert_eq!(p.timeline_frames(), 1_002);
6374 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
6375 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
6376
6377 // An empty clip is the one thing refused, and it pushes no history.
6378 let mut p = three();
6379 assert!(!p.paste(4, clip(0, 7, 7, 0)));
6380 assert_eq!(p.clips().len(), 3);
6381 }
6382
6383 /// The data-loss paste: a clip of a source with no picture used to land on
6384 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
6385 /// carried it was refused on the way back in ("a box with a larger size").
6386 #[test]
6387 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
6388 let mut p = three();
6389 let wav = p.import("/nonexistent/song.wav", 0);
6390 let copied = Clip {
6391 source: wav,
6392 ..PASTED
6393 };
6394 assert!(p.paste(3, copied));
6395 // The room is opened on every lane, or the two would slide apart...
6396 assert_eq!(p.timeline_frames(), 11);
6397 assert_eq!(
6398 shape(&p)[0],
6399 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
6400 "the video lane got room and nothing else"
6401 );
6402 // ...but the clip itself only reaches the lane that can play it.
6403 assert_eq!(
6404 shape(&p)[1],
6405 vec![
6406 clip(0, 0, 3, 0),
6407 clip(3, 100, 102, wav),
6408 clip(5, 3, 5, 0),
6409 clip(7, 5, 9, 0)
6410 ]
6411 );
6412 // A source with a picture is unchanged: still the grouped pair.
6413 let mut p = three();
6414 assert!(p.paste(3, PASTED));
6415 assert_eq!(shape(&p)[0], shape(&p)[1]);
6416 }
6417
6418 /// A hand-written file may hold a clip that ends at the very last frame
6419 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
6420 /// to wrap its start round to the front of the lane: an overlap in debug, a
6421 /// project no reload would accept in release.
6422 #[test]
6423 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
6424 let far = clip(u32::MAX - 90, 0, 90, 0);
6425 let parts = |c: Clip| {
6426 Project::from_parts(
6427 vec![Source::new(FILE, 0)],
6428 two(vec![c], vec![c]),
6429 Vec::new(),
6430 Vec::new(),
6431 )
6432 .expect("valid parts")
6433 };
6434 let mut p = parts(far);
6435 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
6436 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
6437 assert!(!p.undo(), "...and pushes no history either");
6438 assert!(
6439 !p.paste(u32::MAX, PASTED),
6440 "appending has nowhere to go either: the timeline ends at the last frame"
6441 );
6442 // With room for exactly those frames the same paste is taken.
6443 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
6444 assert!(p.paste(0, PASTED));
6445 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
6446 }
6447
6448 #[test]
6449 fn paste_undoes_in_one_step() {
6450 let mut p = three();
6451 let before = shape(&p);
6452 assert!(p.paste(6, PASTED));
6453 assert!(p.undo());
6454 assert_eq!(shape(&p), before, "a paste is one undo step");
6455 }
6456
6457 #[test]
6458 fn a_copy_outlives_the_clip_it_came_from() {
6459 let mut p = three();
6460 let copied = p.clips()[1]; // [3,5)
6461 assert!(p.delete(1));
6462 // Just a frame range: the source is still on disk either way.
6463 assert!(p.paste(0, copied));
6464 assert_eq!(p.map_timeline(0), Some((0, 3)));
6465 assert_eq!(p.timeline_frames(), 9);
6466 }
6467
6468 #[test]
6469 fn delete_closes_the_gap_on_both_lanes() {
6470 let mut p = three();
6471 assert!(p.delete(1));
6472 assert_eq!(p.timeline_frames(), 7);
6473 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
6474 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
6475 // timeline 3 used to be source 3; the gap closed so it is source 5 now
6476 assert_eq!(p.map_timeline(3), Some((1, 5)));
6477 assert_eq!(p.map_timeline(6), Some((1, 8)));
6478 assert_eq!(p.map_timeline(7), None);
6479 }
6480
6481 #[test]
6482 fn delete_first_last_and_only() {
6483 let mut p = three();
6484 assert!(p.delete(0));
6485 assert_eq!(p.map_timeline(0), Some((0, 3)));
6486 assert_eq!(p.timeline_frames(), 6);
6487
6488 let mut p = three();
6489 assert!(p.delete(2));
6490 assert_eq!(p.timeline_frames(), 5);
6491 assert_eq!(p.map_timeline(4), Some((1, 4)));
6492
6493 assert!(!p.delete(2), "index past the end");
6494 assert!(p.delete(1));
6495 assert!(p.delete(0), "and the last remaining clip goes too");
6496 assert_eq!(p.clips().len(), 0);
6497 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
6498 assert!(!p.delete(0), "there is nothing left to delete");
6499 assert!(p.undo(), "one gesture, one undo");
6500 assert_eq!(p.clips().len(), 1);
6501 }
6502
6503 /// The offset model's point: one lane loses a clip, the other does not move.
6504 #[test]
6505 fn a_lift_leaves_a_gap_and_moves_nothing() {
6506 let mut p = three();
6507 let video_before = shape(&p)[0].clone();
6508 assert!(p.lift(Lane::A1, 1));
6509 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
6510 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
6511 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
6512 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
6513 assert_eq!(p.map(Lane::A1, 4), None);
6514 assert_eq!(
6515 p.span_at(Lane::A1, 3),
6516 Some(Span {
6517 start: 3,
6518 len: 2,
6519 from: None,
6520 speed: Speed::NORMAL
6521 })
6522 );
6523 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
6524 assert!(p.undo());
6525 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
6526 }
6527
6528 #[test]
6529 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
6530 let mut p = three();
6531 assert!(p.lift(Lane::A1, 2));
6532 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
6533 assert_eq!(
6534 p.span_at(Lane::A1, 5),
6535 Some(Span {
6536 start: 5,
6537 len: 4,
6538 from: None,
6539 speed: Speed::NORMAL
6540 }),
6541 "the audio lane holds silence to the end of the picture"
6542 );
6543 assert_eq!(p.span_at(Lane::A1, 9), None);
6544 // Every lane covers the timeline exactly, gaps included.
6545 for l in p.lanes() {
6546 let spans = p.spans_from(l, 0);
6547 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
6548 assert_eq!(spans[0].start, 0);
6549 }
6550 }
6551
6552 /// The timeline is emptiable: the last placement comes off like any other,
6553 /// the project holds "nothing on any lane" as a state, and one undo per
6554 /// gesture brings it back.
6555 #[test]
6556 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
6557 let mut p = Project::single(FILE, 9);
6558 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
6559 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
6560 assert_eq!(p.timeline_frames(), 0);
6561 assert_eq!(p.composite_span_at(0), None, "nothing to show");
6562 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
6563 assert!(!p.lift(Lane::A1, 0), "index past the end");
6564 assert!(p.undo(), "and the last lift comes back");
6565 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
6566 // A saved-and-loaded empty timeline is a project like any other, and it
6567 // still names the file its frame rate came from.
6568 assert!(p.lift(Lane::V1, 0));
6569 let (sources, lanes, eq, color) = p.without_orphan_sources();
6570 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
6571 let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
6572 assert_eq!(back.timeline_frames(), 0);
6573 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
6574 }
6575
6576 /// What a keyboard selection walks: one answer per lane, gaps included --
6577 /// the composite's own answer is one lane's and cannot say what the audio
6578 /// lane holds under the same playhead.
6579 #[test]
6580 fn lane_clip_at_answers_for_each_lane_separately() {
6581 let mut p = Project::single(FILE, 9);
6582 assert!(p.split(3), "both lanes split");
6583 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
6584 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
6585 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
6586 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
6587 // A gap on one lane leaves the other's clip selectable there.
6588 assert!(p.lift(Lane::A1, 0));
6589 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
6590 assert_eq!(
6591 p.lane_clip_at(Lane::A1, 3),
6592 Some(0),
6593 "indices moved with it"
6594 );
6595 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
6596 // A lane that is not there is not a panic.
6597 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
6598 }
6599
6600 #[test]
6601 fn place_overwrites_only_its_own_lane() {
6602 let mut p = three();
6603 let audio_before = shape(&p)[1].clone();
6604 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
6605 // is trimmed, nothing shifts.
6606 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
6607 assert_eq!(
6608 shape(&p)[0],
6609 vec![
6610 clip(0, 0, 3, 0),
6611 clip(3, 3, 4, 0),
6612 clip(4, 100, 102, 0),
6613 clip(6, 6, 9, 0),
6614 ]
6615 );
6616 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
6617 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
6618
6619 // Placed inside one clip, it splits it in two.
6620 let mut p = Project::single(FILE, 9);
6621 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
6622 assert_eq!(
6623 shape(&p)[0],
6624 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
6625 );
6626 // ...and placed past the end it makes a gap, which is the whole point.
6627 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
6628 assert_eq!(p.timeline_frames(), 22);
6629 assert_eq!(
6630 p.span_at(Lane::V1, 9),
6631 Some(Span {
6632 start: 9,
6633 len: 11,
6634 from: None,
6635 speed: Speed::NORMAL
6636 })
6637 );
6638 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
6639 }
6640
6641 /// A file with sound let go over a further video track: both halves go down,
6642 /// on the same frames, and the audio row is added when the `+ V` button left
6643 /// the project without one. One undo takes the lane and both clips back.
6644 #[test]
6645 fn a_take_placed_on_a_layer_lands_with_its_sound() {
6646 let mut p = three();
6647 let v2 = p.add_lane(LaneKind::Video);
6648 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
6649
6650 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
6651 let a2 = Lane::new(LaneKind::Audio, 1);
6652 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
6653 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
6654 assert_eq!(p.lane(v2)[0].start, 4);
6655 assert_eq!(p.lane(v2)[0].end(), 6);
6656 assert_eq!(
6657 p.lane(v2)[0].link,
6658 p.lane(a2)[0].link,
6659 "one take, not two placements"
6660 );
6661 assert!(p.lane(v2)[0].link.is_some());
6662 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
6663 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
6664
6665 // The pair overwrites its own two lanes and nothing else, exactly as a
6666 // one-lane place does.
6667 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
6668 assert_eq!(p.lane(v2), p.lane(a2));
6669 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
6670 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
6671
6672 assert!(p.undo(), "one step for the second pair");
6673 assert_eq!(p.lane(v2).len(), 1);
6674 assert!(p.undo(), "one step for the first pair *and* its lane");
6675 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
6676 assert!(p.lane(v2).is_empty());
6677
6678 // Refusals cost nothing: sound placed alone is `place`'s door.
6679 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
6680 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
6681 assert!(
6682 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
6683 "a lane that is not there"
6684 );
6685 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
6686 }
6687
6688 /// The drag between tracks: let go at the frames it already covers the clip
6689 /// keeps them, one undo takes it back, and every way it can be refused
6690 /// leaves the project untouched.
6691 #[test]
6692 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
6693 let v2 = Lane::new(LaneKind::Video, 1);
6694 let mut p = three();
6695 assert_eq!(p.add_lane(LaneKind::Video), v2);
6696 let before = shape(&p);
6697
6698 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
6699 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
6700 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
6701 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
6702 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
6703 // One snapshot: a single undo, and the lane list survives it.
6704 assert!(p.undo());
6705 assert_eq!(shape(&p), before);
6706
6707 // A lane that is not there, the lane and frame it is already at, an
6708 // index that is not there, and a move across kinds: all refused,
6709 // nothing changed.
6710 let history = p.history.len();
6711 for (from, idx, to, start) in [
6712 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
6713 (Lane::V1, 1, Lane::V1, 3),
6714 (Lane::V1, 9, v2, 3),
6715 (Lane::V1, 1, Lane::A1, 3),
6716 (Lane::A1, 1, v2, 3),
6717 ] {
6718 assert!(
6719 !p.move_clip(from, idx, to, start),
6720 "{from:?} {idx} -> {to:?} at {start}"
6721 );
6722 }
6723 assert_eq!(shape(&p), before);
6724 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
6725
6726 // Landing on another clip is refused rather than overwriting it: the
6727 // pointer named the lane, never the take already sitting there.
6728 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
6729 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
6730 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
6731 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
6732 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
6733 }
6734
6735 /// The drag *along* a track, which is the one every other editor has: the
6736 /// clip lands on the frame the pointer let it go at, and stops dead against
6737 /// the neighbour rather than overwriting it.
6738 #[test]
6739 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
6740 let sources = vec![Source::new(FILE, 0)];
6741 let lanes = vec![
6742 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
6743 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
6744 ];
6745 let mut p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
6746 let before = shape(&p);
6747
6748 // Into the gap, exactly where it was let go -- nothing else moves.
6749 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
6750 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
6751 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
6752 // Dragged past the clip in front of it: clamped to its wall, laid end
6753 // to end with it, never over it.
6754 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
6755 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
6756 // One undo per drag, and both of them together are the state it started
6757 // in -- the frames each clip plays never changed.
6758 assert!(p.undo() && p.undo());
6759 assert_eq!(shape(&p), before);
6760
6761 // A drop that changes nothing is a click, not an edit.
6762 let history = p.history.len();
6763 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
6764 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
6765 }
6766
6767 /// A drag carries the whole take: the sound half travels exactly as far as
6768 /// the picture does, and the tighter of their two walls stops both.
6769 #[test]
6770 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
6771 let mut p = three();
6772 assert!(
6773 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
6774 "room to the right"
6775 );
6776 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
6777 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
6778 // Something in the sound's way, and nothing at all in the picture's.
6779 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
6780 let before = shape(&p);
6781
6782 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
6783 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
6784 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
6785 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6786 assert!(p.undo());
6787 assert_eq!(shape(&p), before, "one undo for the whole take");
6788 }
6789
6790 /// The drag that does both at once -- another lane *and* another frame --
6791 /// which is what a pointer let go over a lane always names.
6792 #[test]
6793 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
6794 let v2 = Lane::new(LaneKind::Video, 1);
6795 let mut p = three();
6796 assert_eq!(p.add_lane(LaneKind::Video), v2);
6797
6798 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
6799 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
6800 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
6801 assert_eq!(
6802 p.lane(Lane::A1)[2].start,
6803 20,
6804 "its sound travelled the same distance"
6805 );
6806 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6807 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
6808 }
6809
6810 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
6811 /// [`three`] cuts up all nine of its frames.
6812 const SRC: &[u32] = &[9];
6813
6814 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
6815 /// else on the lane moves, and every wall stops the edge rather than
6816 /// refusing the gesture.
6817 #[test]
6818 fn trimming_the_tail_stops_at_every_wall() {
6819 let mut p = three();
6820
6821 // Pulled in: a gap opens behind it and the clip after it stays put.
6822 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
6823 assert_eq!(
6824 shape(&p)[0],
6825 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
6826 );
6827 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
6828 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
6829
6830 // ...and back out, no further than the clip behind it.
6831 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
6832 assert_eq!(
6833 shape(&p)[0][1],
6834 clip(3, 3, 5, 0),
6835 "stopped at the neighbour"
6836 );
6837 assert!(
6838 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
6839 "already at the wall"
6840 );
6841
6842 // One frame of clip always survives, however far back the pointer went.
6843 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
6844 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
6845
6846 // The last clip has no neighbour, so what stops it is the file: nine
6847 // frames is nine frames.
6848 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
6849 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
6850 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
6851 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
6852 // A source nobody told us the length of may not grow at all -- an
6853 // out-point past the end of a file is a save that will not open again.
6854 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
6855 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
6856 }
6857
6858 /// The head pulled in takes the in-point with it -- what stays plays what it
6859 /// always played -- and stops at the source's own first frame.
6860 #[test]
6861 fn trimming_the_head_moves_the_in_point() {
6862 let mut p = three();
6863 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
6864 assert_eq!(
6865 shape(&p)[0][0],
6866 clip(2, 2, 3, 0),
6867 "two frames off the front"
6868 );
6869 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
6870 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
6871 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
6872 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
6873 // One frame survives here too.
6874 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
6875 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
6876
6877 // A clip that does not begin at its source's first frame: its head goes
6878 // back to source frame 0 and not one frame further.
6879 let mut p = Project::single(FILE, 9);
6880 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
6881 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
6882 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
6883 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
6884 }
6885
6886 /// A clip whose in-point is *past* its own start -- what a ripple delete
6887 /// leaves, the piece in front of it gone and this one slid back to frame 0
6888 /// carrying the in-point the cut gave it. Its head has more source behind it
6889 /// than the timeline has room for, and the timeline's own first frame is the
6890 /// wall: asking is not an overflow, and the answer is 0.
6891 #[test]
6892 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
6893 let mut p = Project::single(FILE, 9);
6894 assert!(p.split(5));
6895 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
6896 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
6897
6898 assert_eq!(
6899 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
6900 Some((0, 3)),
6901 "back to frame 0 at most, and one frame of clip always survives"
6902 );
6903 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
6904 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
6905 assert_eq!(
6906 shape(&p)[0],
6907 vec![clip(2, 7, 9, 0)],
6908 "the in-point followed"
6909 );
6910 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
6911 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
6912 }
6913
6914 /// A still is trimmed from its head exactly as it is from its tail: it has
6915 /// no earlier frame to walk an in-point back to, so the wall is the length
6916 /// the caller's table allows it, measured back from the tail. Measured from
6917 /// the in-point -- which a placed picture has at 0 -- its left edge could
6918 /// never be dragged outwards at all.
6919 #[test]
6920 fn a_stills_head_stretches_out_like_its_tail() {
6921 const STILL: &str = "/nonexistent/card.png";
6922 /// What a still is held to, as `PlaybackSession` fills the table in.
6923 const CAP: &[u32] = &[60];
6924
6925 let mut p = Project::single(STILL, 20);
6926 assert!(p.lift(Lane::A1, 0), "a picture is silent");
6927 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
6928 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
6929
6930 // A source with no entry in the table may not grow, here as at the tail.
6931 assert_eq!(
6932 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
6933 Some((100, 119)),
6934 "a length nobody told us buys no head room"
6935 );
6936 assert_eq!(
6937 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
6938 Some((60, 119)),
6939 "back to a whole cap's worth, one frame of clip surviving"
6940 );
6941 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
6942 assert_eq!(
6943 shape(&p)[0][0],
6944 clip(80, 0, 40, 0),
6945 "twenty frames longer, and still read from the source's first frame"
6946 );
6947 // Past the cap is clamped, exactly as the tail is -- not refused.
6948 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
6949 assert_eq!(
6950 shape(&p)[0][0],
6951 clip(60, 0, 60, 0),
6952 "a cap's worth, no more"
6953 );
6954 // ...and the clip in front is the nearer wall of the two: no head trim
6955 // may open an overlap.
6956 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
6957 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
6958 assert_eq!(
6959 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
6960 Some((85, 119)),
6961 "up to the neighbour's last frame and not over it"
6962 );
6963 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
6964 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
6965 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
6966 }
6967
6968 /// Linked halves trim as one: a link is one span on however many lanes, so
6969 /// the sound follows the picture's edge -- and the tightest wall of the two
6970 /// is what stops both.
6971 #[test]
6972 fn linked_halves_trim_together() {
6973 let mut p = three();
6974 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
6975 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
6976
6977 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
6978 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
6979 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
6980 assert!(
6981 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
6982 "either half drags it"
6983 );
6984 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
6985 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6986
6987 // Something in the way on the *audio* lane stops the picture's tail as
6988 // well: the group can only go as far as its tightest member.
6989 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
6990 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
6991 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
6992 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
6993 links_are_consistent(&p.lanes).expect("still one span");
6994 }
6995
6996 /// A whole drag is one undo step -- the front-end commits once, at the
6997 /// release -- and an edge asked to stay where it is costs none at all.
6998 #[test]
6999 fn a_trim_is_one_undo_step() {
7000 let mut p = three();
7001 let before = shape(&p);
7002 let history = p.history.len();
7003
7004 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7005 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
7006 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
7007 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
7008 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
7009 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
7010
7011 assert!(p.undo());
7012 assert_eq!(shape(&p), before, "both halves back, in one step");
7013 }
7014
7015 /// A moved half stays in its group: a link names a span, not a lane, so the
7016 /// picture on `V2` is still the same take as the sound under it on `A1`.
7017 #[test]
7018 fn move_clip_keeps_the_group() {
7019 let v2 = Lane::new(LaneKind::Video, 1);
7020 let mut p = three();
7021 p.add_lane(LaneKind::Video);
7022 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7023 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7024 assert!(p.move_clip(Lane::V1, 1, v2, 3));
7025 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
7026 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7027 assert_eq!(
7028 p.lane(v2)[0].start,
7029 p.lane(Lane::A1)[1].start,
7030 "and still covers the same span as its sound"
7031 );
7032 }
7033
7034 #[test]
7035 fn ripple_delete_spans_partial_clips() {
7036 let mut p = three();
7037 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
7038 assert!(p.ripple_delete(2, 4));
7039 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
7040 assert_eq!(shape(&p)[1], shape(&p)[0]);
7041 assert_eq!(p.timeline_frames(), 5);
7042 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
7043 assert!(p.undo());
7044 assert_eq!(shape(&p), shape(&three()));
7045 // One that takes everything is a delete like any other: the timeline
7046 // empties, and the undo it cost brings it back whole.
7047 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
7048 assert_eq!(p.timeline_frames(), 0);
7049 assert!(
7050 !p.ripple_delete(0, 100),
7051 "and a delete with nothing left to take is not an undo step"
7052 );
7053 assert!(p.undo());
7054 assert_eq!(shape(&p), shape(&three()));
7055 }
7056
7057 #[test]
7058 fn undo_restores_exactly() {
7059 let mut p = three();
7060 let after_splits = shape(&p);
7061 assert!(p.delete(1));
7062 assert!(p.undo());
7063 assert_eq!(shape(&p), after_splits);
7064
7065 // walk all the way back through both splits, then run dry
7066 assert!(p.undo());
7067 assert_eq!(p.clips().len(), 2);
7068 assert!(p.undo());
7069 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7070 assert!(!p.undo(), "empty history");
7071 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7072 }
7073
7074 /// Past the cap the *oldest* step goes, so a long session undoes exactly
7075 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
7076 #[test]
7077 fn history_stops_at_the_cap() {
7078 let mut p = Project::single(FILE, 400);
7079 for frame in 1..=150 {
7080 assert!(p.split(frame), "split {frame} is an edit");
7081 }
7082 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
7083 for step in 0..HISTORY_CAP {
7084 assert!(p.undo(), "undo {step} is inside the cap");
7085 }
7086 assert!(!p.undo(), "and the 101st has nothing left to take");
7087 // 100 undos off 150 splits is the timeline after the 50th: the older
7088 // steps were dropped, not the newer ones.
7089 assert_eq!(p.clips().len(), 51);
7090 }
7091
7092 /// Undo/redo by hand across a split must never merge two takes into one
7093 /// group by reusing an id.
7094 #[test]
7095 fn group_ids_are_never_reused() {
7096 let mut p = Project::single(FILE, 9);
7097 assert!(p.split(3));
7098 let first = p.clips()[1].link;
7099 assert!(p.undo());
7100 assert!(p.split(5));
7101 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
7102 }
7103
7104 #[test]
7105 fn segments_from_reads_the_audio_lane() {
7106 let p = three();
7107 // mid-clip: partial first segment, whole clips after it
7108 assert_eq!(
7109 p.segments_from(4, FPS),
7110 vec![
7111 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7112 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7113 ]
7114 );
7115 // on a boundary: nothing partial
7116 assert_eq!(
7117 p.segments_from(3, FPS),
7118 vec![
7119 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
7120 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7121 ]
7122 );
7123 // from the top: one entry per clip
7124 assert_eq!(p.segments_from(0, FPS).len(), 3);
7125 // last clip only
7126 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
7127 // past the end / unusable fps
7128 assert!(p.segments_from(9, FPS).is_empty());
7129 assert!(p.segments_from(0, 0.0).is_empty());
7130 assert!(p.segments_from(0, f64::NAN).is_empty());
7131 }
7132
7133 #[test]
7134 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
7135 let mut p = three();
7136 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
7137 assert_eq!(
7138 p.segments_from(0, FPS),
7139 vec![
7140 (Some(0), 0.0, 3.0 / 30.0),
7141 (None, 0.0, 2.0 / 30.0),
7142 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7143 ]
7144 );
7145 // The list still covers exactly the timeline: that is what stops the
7146 // master clock stalling at the hole.
7147 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7148 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
7149 // Starting inside the gap trims the silence, not the clip after it.
7150 assert_eq!(
7151 p.segments_from(4, FPS),
7152 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
7153 );
7154 // ...and a lane that is nothing but gap is a run of silence.
7155 assert!(p.lift(Lane::A1, 0));
7156 assert!(p.lift(Lane::A1, 0));
7157 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
7158 }
7159
7160 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
7161 /// of source 0 then [0,4) of source 1.
7162 fn two_sources() -> Project {
7163 let mut p = three();
7164 let s = p.import(FILE2, 0);
7165 assert_eq!(s, 1);
7166 assert!(p.append_clip(s, 4));
7167 p
7168 }
7169
7170 #[test]
7171 fn import_dedups_and_appends() {
7172 let mut p = Project::single(FILE, 9);
7173 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
7174 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
7175 assert_eq!(p.import(FILE2, 0), 1);
7176 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
7177 // ...but the same file on another audio stream is another source: it is
7178 // what a clip names, and a clip plays exactly one stream.
7179 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
7180 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
7181 assert_eq!(p.sources()[2].audio_stream, 1);
7182 assert!(p.append_clip(2, 4), "a stream entry is placeable");
7183 assert!(p.undo());
7184 assert_eq!(p.sources().len(), 3);
7185 assert!(!p.append_clip(3, 5), "unknown source index");
7186 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
7187
7188 // Two spellings of one real file are one source: this is the case the
7189 // raw-path comparison above would get wrong.
7190 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
7191 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
7192 let mut p = Project::single(here, 9);
7193 assert_eq!(p.import(detour, 0), 0);
7194 assert_eq!(p.sources().len(), 1);
7195 }
7196
7197 #[test]
7198 fn append_clip_is_one_undo_step() {
7199 let mut p = two_sources();
7200 assert_eq!(p.timeline_frames(), 13);
7201 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
7202 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
7203 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
7204 assert!(p.undo());
7205 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
7206 assert_eq!(
7207 p.sources().len(),
7208 2,
7209 "the orphan source entry stays -- indexes are forever"
7210 );
7211 // ...and it is still usable, so a redo-by-hand costs no reimport.
7212 assert!(p.append_clip(1, 0));
7213 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
7214 }
7215
7216 #[test]
7217 fn edits_carry_the_source_along() {
7218 let mut p = two_sources();
7219 // A split inside the second source splits into two source-1 clips.
7220 assert!(p.split(11));
7221 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
7222 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
7223
7224 // A source-1 clip pasted into source-0 territory keeps its file, and so
7225 // does the source-0 half that got split off around it.
7226 let copied = p.clips()[4];
7227 assert!(p.paste(1, copied));
7228 assert_eq!(p.clips()[1].source, 1);
7229 assert_eq!(p.clips()[1].in_frame, 2);
7230 assert_eq!(p.clips()[2].source, 0);
7231 assert!(p.undo());
7232 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
7233 }
7234
7235 #[test]
7236 fn segments_from_names_the_source() {
7237 let p = two_sources();
7238 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
7239 assert_eq!(
7240 p.segments_from(4, FPS),
7241 vec![
7242 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7243 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7244 (Some(1), 0.0, 4.0 / 30.0),
7245 ]
7246 );
7247 // Mid-clip in source 1: only that source is left.
7248 assert_eq!(
7249 p.segments_from(10, FPS),
7250 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
7251 );
7252 assert!(p.segments_from(13, FPS).is_empty());
7253 // Segments still cover exactly the timeline across the join.
7254 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7255 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
7256 }
7257
7258 #[test]
7259 fn segments_follow_deletes_and_fps() {
7260 let mut p = three();
7261 assert!(p.delete(0));
7262 // source seconds, not timeline: deleting the head does not shift them
7263 let segs = p.segments_from(0, 25.0);
7264 assert_eq!(
7265 segs,
7266 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
7267 );
7268 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
7269 assert!(
7270 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
7271 "segments must cover exactly the timeline: {played}"
7272 );
7273 }
7274
7275 #[test]
7276 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
7277 // Import a second file, undo it: source 1 is now an orphan.
7278 let mut p = two_sources();
7279 assert!(p.undo());
7280 let (sources, lanes, eq, color) = p.without_orphan_sources();
7281 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
7282 assert!(eq.is_empty(), "and a project with no equalizer writes none");
7283 assert!(color.is_empty(), "nor a colour it never graded with");
7284 assert_eq!(
7285 lanes,
7286 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
7287 "the clips are untouched"
7288 );
7289
7290 // Three sources where only the middle one is orphaned: the survivors
7291 // renumber, and the clips follow.
7292 let mut p = Project::single(FILE, 9);
7293 assert_eq!(p.import(FILE2, 0), 1);
7294 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
7295 assert!(p.append_clip(2, 4));
7296 let (sources, lanes, eq, color) = p.without_orphan_sources();
7297 assert_eq!(
7298 sources,
7299 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
7300 );
7301 assert_eq!(
7302 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
7303 [0, 1]
7304 );
7305 // ...and what comes out is loadable, with the same timeline.
7306 let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts");
7307 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
7308 assert_eq!(reloaded.sources().len(), 2);
7309 }
7310
7311 /// Taking a file out of the library: refused by name -- lanes and counts --
7312 /// while a clip still plays from it, and once nothing does, the entry goes
7313 /// and every clip that indexed past it is renumbered onto the short list.
7314 #[test]
7315 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
7316 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
7317 // plus a second stream of FILE as source 2 with a take of its own.
7318 let mut p = two_sources();
7319 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
7320 assert!(p.append_clip(2, 4));
7321
7322 let refusal = p
7323 .remove_source(1)
7324 .expect_err("a source with clips on it cannot go")
7325 .to_string();
7326 assert!(refusal.contains(FILE2), "names the file: {refusal}");
7327 assert!(
7328 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
7329 "names the lanes holding it: {refusal}"
7330 );
7331 assert!(refusal.contains("still plays"), "{refusal}");
7332 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
7333 assert_eq!(shape(&p)[0][3].source, 1);
7334
7335 // Delete FILE2's take -- the whole span, on every lane -- and the entry
7336 // is free to go. Source 2's clips become source 1's.
7337 assert!(p.delete_in(Lane::V1, 3));
7338 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
7339 p.remove_source(1).expect("nothing plays FILE2 any more");
7340 assert_eq!(
7341 p.sources(),
7342 [Source::new(FILE, 0), Source::new(FILE, 1)],
7343 "the middle entry is gone"
7344 );
7345 assert_eq!(
7346 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
7347 [0, 0, 0, 1],
7348 "the clips past it renumbered"
7349 );
7350 assert_eq!(
7351 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
7352 [0, 0, 0, 1],
7353 "on every lane"
7354 );
7355 // What is left is a project that still loads, which is the whole point
7356 // of renumbering rather than leaving a hole.
7357 let (sources, lanes, eq, color) = p.without_orphan_sources();
7358 Project::from_parts(sources, lanes, eq, color).expect("from_parts");
7359 }
7360
7361 /// The two edges of a removal: it retires the undo stack (the corner-cut on
7362 /// [`Project::remove_source`]), and the last entry goes like any other
7363 /// once nothing plays it -- a project may name no file at all.
7364 #[test]
7365 fn remove_source_retires_undo_and_empties_the_library() {
7366 let mut p = two_sources();
7367 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
7368 assert!(!p.history.is_empty(), "there is something to undo");
7369 p.remove_source(1).expect("nothing plays FILE2");
7370 assert!(
7371 p.history.is_empty(),
7372 "a snapshot naming the removed source must not survive it"
7373 );
7374 assert!(!p.undo(), "and so there is nothing left to undo");
7375
7376 // The last file standing is held to the one rule every row is -- what
7377 // plays cannot go -- and to no other.
7378 assert_eq!(p.sources().len(), 1);
7379 let refusal = p
7380 .remove_source(0)
7381 .expect_err("its clips are still on the lanes")
7382 .to_string();
7383 assert!(refusal.contains("still plays"), "{refusal}");
7384 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
7385 while p.delete_in(Lane::V1, 0) {}
7386 p.remove_source(0)
7387 .expect("the last row goes like any other");
7388 assert!(
7389 p.sources().is_empty(),
7390 "a project may name no file at all: an empty library over an empty timeline"
7391 );
7392 assert_eq!(p.timeline_frames(), 0);
7393 assert!(
7394 p.remove_source(0).is_err(),
7395 "and an index that is not there is refused, not panicked on"
7396 );
7397 }
7398
7399 /// A clip's equalizer is the clip's: it survives every edit that copies a
7400 /// placement, and it comes back with an undo.
7401 #[test]
7402 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
7403 let mut p = three();
7404 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
7405 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
7406 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7407 assert!(
7408 p.eq_of(Lane::V1, 0).is_none(),
7409 "one clip, not the lane above"
7410 );
7411
7412 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
7413 assert!(p.split(1));
7414 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7415 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
7416 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
7417
7418 // A clipboard copy carries it -- onto another lane, at that.
7419 let copied = p.lane(Lane::A1)[1];
7420 assert!(p.place(Lane::V1, 20, copied));
7421 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
7422 assert!(p.undo());
7423 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
7424
7425 // ...and a change to one is one undo step, in both directions.
7426 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
7427 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
7428 assert!(p.undo());
7429 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7430 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
7431 assert!(p.eq_of(Lane::A1, 0).is_none());
7432 assert!(p.undo());
7433 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7434
7435 // Two refusals, neither of which costs an undo step.
7436 let mut nan = band_at(1);
7437 nan.bands[0].q = f32::INFINITY;
7438 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
7439 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
7440 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7441 assert!(p.undo());
7442 assert_eq!(
7443 p.lane(Lane::A1).len(),
7444 3,
7445 "one step back is before the split"
7446 );
7447 assert!(p.undo());
7448 assert!(
7449 p.eq_of(Lane::A1, 0).is_none(),
7450 "and the next is before the setting: the refusals pushed none"
7451 );
7452 }
7453
7454 /// The table is append-only within a session, exactly as the sources are, so
7455 /// an undone setting is still in it -- and a save is where it goes.
7456 #[test]
7457 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
7458 let mut p = three();
7459 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
7460 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
7461 assert!(p.undo(), "back to the first setting");
7462 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
7463
7464 let (_, lanes, eq, _) = p.without_orphan_sources();
7465 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
7466 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
7467 assert_eq!(lanes[0].1[1].eq, None);
7468
7469 // One curve on three clips is one entry: settings that are equal share.
7470 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
7471 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
7472 let (_, lanes, eq, _) = p.without_orphan_sources();
7473 assert_eq!(eq.len(), 1, "equal settings share their entry");
7474 assert_eq!(lanes[1].1[2].eq, Some(0));
7475 reloads(&p, "an equalizer that outlived an undo");
7476 }
7477
7478 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
7479 /// grade is the clip's, through every edit that copies a placement.
7480 #[test]
7481 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
7482 let mut p = three();
7483 assert!(
7484 p.color_of(Lane::V1, 0).is_none(),
7485 "a fresh clip is ungraded"
7486 );
7487 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7488 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7489 assert!(
7490 p.color_of(Lane::A1, 0).is_none(),
7491 "one clip, not the lane below"
7492 );
7493 assert!(
7494 p.eq_of(Lane::V1, 0).is_none(),
7495 "and a grade is not an equalizer"
7496 );
7497
7498 // Cutting a graded clip must not grade half of it: both halves inherit.
7499 assert!(p.split(1));
7500 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7501 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
7502 assert!(
7503 p.color_of(Lane::V1, 2).is_none(),
7504 "the clip after it is ungraded"
7505 );
7506
7507 // A clipboard copy carries it -- onto another lane, at that.
7508 let copied = p.lane(Lane::V1)[1];
7509 assert!(p.place(Lane::A1, 20, copied));
7510 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
7511 assert!(p.undo());
7512 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
7513
7514 // ...and a change to one is one undo step, in both directions.
7515 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
7516 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
7517 assert!(p.undo());
7518 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7519 assert!(
7520 p.set_color(Lane::V1, 0, None),
7521 "and taking it off is an edit"
7522 );
7523 assert!(p.color_of(Lane::V1, 0).is_none());
7524 assert!(p.undo());
7525 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7526
7527 // Two refusals, neither of which costs an undo step.
7528 let nan = ColorParams {
7529 contrast: f32::NAN,
7530 ..grade_at(1)
7531 };
7532 assert!(
7533 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
7534 "no clip there"
7535 );
7536 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
7537 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7538 assert!(p.undo());
7539 assert_eq!(
7540 p.lane(Lane::V1).len(),
7541 3,
7542 "one step back is before the split"
7543 );
7544 assert!(p.undo());
7545 assert!(
7546 p.color_of(Lane::V1, 0).is_none(),
7547 "and the next is before the grade: the refusals pushed none"
7548 );
7549 }
7550
7551 /// A slider drag is one gesture: the press snapshots, every sample after it
7552 /// only regrades, and the single undo lands on what the clip was *before*
7553 /// the hand touched it -- not one step back down the drag.
7554 #[test]
7555 fn a_whole_colour_drag_undoes_in_one_step() {
7556 let mut p = three();
7557 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
7558 for n in 2..=8 {
7559 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
7560 }
7561 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
7562 assert!(p.undo());
7563 assert!(
7564 p.color_of(Lane::V1, 0).is_none(),
7565 "one undo is the whole gesture, back to ungraded"
7566 );
7567
7568 // The live write refuses what the snapshotting one refuses, and a
7569 // refusal still costs no history either way.
7570 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
7571 assert!(!p.set_color_live(
7572 Lane::V1,
7573 0,
7574 Some(ColorParams {
7575 contrast: f32::NAN,
7576 ..grade_at(1)
7577 })
7578 ));
7579 assert!(p.undo());
7580 assert_eq!(
7581 p.lane(Lane::V1).len(),
7582 2,
7583 "the next step back is the split before the drag: no sample pushed one"
7584 );
7585 }
7586
7587 /// The colour table is append-only within a session, exactly as the eq one
7588 /// is -- and a save is where an undone grade goes.
7589 #[test]
7590 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
7591 let mut p = three();
7592 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
7593 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7594 assert!(p.undo(), "back to the first grade");
7595 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
7596
7597 let (_, lanes, _, color) = p.without_orphan_sources();
7598 assert_eq!(
7599 color,
7600 vec![grade_at(1)],
7601 "what nothing plays is not written"
7602 );
7603 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
7604 assert_eq!(lanes[0].1[1].color, None);
7605
7606 // One grade on three clips is one entry: settings that are equal share.
7607 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
7608 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
7609 let (_, lanes, _, color) = p.without_orphan_sources();
7610 assert_eq!(color.len(), 1, "equal grades share their entry");
7611 assert_eq!(lanes[1].1[2].color, Some(0));
7612 reloads(&p, "a colour that outlived an undo");
7613
7614 // An equalizer and a grade on one clip are two independent tables.
7615 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
7616 let (_, lanes, eq, color) = p.without_orphan_sources();
7617 assert_eq!((eq.len(), color.len()), (1, 1));
7618 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
7619 }
7620
7621 /// Not a claim about correctness but about cost: a clip is copied on every
7622 /// paste, every undo snapshot and every lane clone, so its size is worth
7623 /// knowing. The eq index fit the padding a `Copy` clip already had; the
7624 /// colour one did not, and the struct grew a word.
7625 #[test]
7626 fn a_clip_is_still_a_small_copy() {
7627 assert_eq!(
7628 std::mem::size_of::<Clip>(),
7629 40,
7630 "Clip changed size -- 32 before the colour index, 40 after"
7631 );
7632 }
7633
7634 #[test]
7635 fn from_parts_has_no_history_and_checks_the_invariants() {
7636 let (sources, lanes, eq, color) = three().without_orphan_sources();
7637 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
7638 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone())
7639 .expect("valid parts");
7640 assert_eq!(p.clips(), three().clips());
7641 assert!(!p.undo(), "a loaded project has nothing to undo");
7642 assert!(p.split(4), "...and is editable from there");
7643 assert!(p.undo());
7644
7645 // A lane may be empty, and so may every lane -- an emptied timeline is a
7646 // project. No lane at all is not one: there would be nothing to place on.
7647 assert!(
7648 Project::from_parts(
7649 sources.clone(),
7650 two(video.clone(), Vec::new()),
7651 Vec::new(),
7652 Vec::new(),
7653 )
7654 .is_ok()
7655 );
7656 assert!(
7657 Project::from_parts(
7658 sources.clone(),
7659 two(Vec::new(), Vec::new()),
7660 Vec::new(),
7661 Vec::new(),
7662 )
7663 .is_ok()
7664 );
7665 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
7666 let bad: [Vec<Clip>; 5] = [
7667 vec![clip(0, 0, 3, 1)], // source that is not there
7668 vec![clip(0, 3, 3, 0)], // empty clip
7669 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
7670 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
7671 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
7672 ];
7673 for clips in bad {
7674 assert!(
7675 Project::from_parts(
7676 sources.clone(),
7677 two(clips.clone(), Vec::new()),
7678 Vec::new(),
7679 Vec::new(),
7680 )
7681 .is_err(),
7682 "{clips:?}"
7683 );
7684 assert!(
7685 Project::from_parts(
7686 sources.clone(),
7687 two(video.clone(), clips.clone()),
7688 Vec::new(),
7689 Vec::new(),
7690 )
7691 .is_err()
7692 );
7693 // ...and on a third lane, which is checked by the same walk.
7694 assert!(
7695 Project::from_parts(
7696 sources.clone(),
7697 vec![
7698 (LaneKind::Video, video.clone()),
7699 (LaneKind::Audio, audio.clone()),
7700 (LaneKind::Video, clips),
7701 ],
7702 Vec::new(),
7703 Vec::new(),
7704 )
7705 .is_err()
7706 );
7707 }
7708 // An equalizer index no table entry answers, and a table entry the file
7709 // format could not have written, are refused at this door too.
7710 let eqd = |i: u16| {
7711 vec![Clip {
7712 eq: Some(i),
7713 ..video[0]
7714 }]
7715 };
7716 assert!(
7717 Project::from_parts(
7718 sources.clone(),
7719 two(eqd(0), Vec::new()),
7720 Vec::new(),
7721 Vec::new(),
7722 )
7723 .is_err()
7724 );
7725 let mut nan = band_at(1);
7726 nan.bands[0].freq_hz = f32::NAN;
7727 assert!(
7728 Project::from_parts(
7729 sources.clone(),
7730 two(eqd(0), Vec::new()),
7731 vec![nan],
7732 Vec::new(),
7733 )
7734 .is_err()
7735 );
7736 let loaded = Project::from_parts(
7737 sources.clone(),
7738 two(eqd(0), Vec::new()),
7739 vec![band_at(1)],
7740 Vec::new(),
7741 )
7742 .expect("an eq the table holds");
7743 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
7744
7745 // The same two refusals for a colour, at the same door.
7746 let graded = |i: u16| {
7747 vec![Clip {
7748 color: Some(i),
7749 fit: FitPolicy::default(),
7750 speed: Speed::NORMAL,
7751 ..video[0]
7752 }]
7753 };
7754 assert!(
7755 Project::from_parts(
7756 sources.clone(),
7757 two(graded(0), Vec::new()),
7758 Vec::new(),
7759 Vec::new(),
7760 )
7761 .is_err(),
7762 "a colour index no entry answers"
7763 );
7764 assert!(
7765 Project::from_parts(
7766 sources.clone(),
7767 two(graded(0), Vec::new()),
7768 Vec::new(),
7769 vec![ColorParams {
7770 tint: f32::NAN,
7771 ..grade_at(1)
7772 }],
7773 )
7774 .is_err(),
7775 "a value the file format could not have written"
7776 );
7777 let loaded = Project::from_parts(
7778 sources.clone(),
7779 two(graded(0), Vec::new()),
7780 Vec::new(),
7781 vec![grade_at(1)],
7782 )
7783 .expect("a colour the table holds");
7784 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
7785
7786 // Group ids survive a load, and the next split gets a fresh one.
7787 let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts");
7788 assert!(p.split(4));
7789 assert!(p.clips().iter().all(|c| c.link.is_some()));
7790 }
7791
7792 /// The grouping rules, at the untrusted door and after every edit that can
7793 /// touch a link. A link id is at most one placement per lane -- a clip or a
7794 /// caption, whichever carries it -- and no sequence of edits may produce
7795 /// otherwise, because what an edit produces is what a save writes and a load
7796 /// reads.
7797 ///
7798 /// Amended for the offset-preserving group: the members keep their own
7799 /// spans, so two placements of one id covering different frames is *legal*
7800 /// -- it is what a hand-built group is -- and the only refusal left is the
7801 /// doubled id inside one lane.
7802 #[test]
7803 fn a_link_id_is_never_two_clips_of_one_lane() {
7804 let sources = vec![Source::new(FILE, 0)];
7805 let linked = |start, in_frame, out_frame, link| Clip {
7806 start,
7807 in_frame,
7808 out_frame,
7809 source: 0,
7810 link: Some(link),
7811 eq: None,
7812 color: None,
7813 fit: FitPolicy::default(),
7814 speed: Speed::NORMAL,
7815 };
7816
7817 // The door: a doubled id inside one lane, refused by name.
7818 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
7819 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
7820 .expect_err("refused")
7821 .to_string()
7822 };
7823 assert!(
7824 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
7825 .contains("link 7 names two clips in the V1 lane"),
7826 "a duplicate id inside one lane is refused by name"
7827 );
7828 // ...and the same doubling on a subtitle lane, in its own words: a
7829 // caption is the other placement an id may name.
7830 let caption = |start: u32, frames: u32, link| SubClip {
7831 start,
7832 frames,
7833 track: 0,
7834 in_us: 0,
7835 out_us: i64::from(frames) * 1_000_000,
7836 link: Some(link),
7837 };
7838 let subs = LaneData {
7839 clips: Vec::new(),
7840 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
7841 ..LaneData::new(LaneKind::Subtitle, Vec::new())
7842 };
7843 assert_eq!(
7844 links_are_consistent(&[subs]).unwrap_err().to_string(),
7845 "link 7 names two captions in the S1 lane"
7846 );
7847 // A pair covering *different* frames is legal now: the members of a
7848 // hand-built group keep their own spans, and what binds them is the id.
7849 let apart = Project::from_parts(
7850 sources.clone(),
7851 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
7852 Vec::new(),
7853 Vec::new(),
7854 );
7855 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
7856 // A one-sided link is *not* an error: it is what a lift leaves behind.
7857 let mut p = Project::single(FILE, 9);
7858 assert!(p.lift(Lane::A1, 0));
7859 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
7860 assert!(
7861 Project::from_parts(sources, lanes, eq, color).is_ok(),
7862 "a lifted lane's project has to load again"
7863 );
7864
7865 // The edits: nothing below may break either rule.
7866 let consistent = |p: &Project, what: &str| {
7867 assert!(
7868 links_are_consistent(&p.lanes).is_ok(),
7869 "{what}: {:?}",
7870 p.lanes
7871 );
7872 };
7873 let mut p = three();
7874 let copied = p.clips()[0];
7875 assert!(
7876 copied.link.is_some(),
7877 "the clipboard clip carries its group"
7878 );
7879 assert!(p.lift(Lane::V1, 0));
7880 assert!(p.place(Lane::V1, 0, copied));
7881 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
7882 assert_eq!(
7883 p.clips().iter().filter(|c| c.link == copied.link).count(),
7884 0,
7885 "a placement belongs to no group, so it cannot duplicate one"
7886 );
7887 consistent(&p, "lift + place twice");
7888 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
7889 consistent(&p, "place through a grouped clip");
7890 assert!(p.paste(6, copied), "a rippling paste through another");
7891 consistent(&p, "paste");
7892 assert!(p.split(2));
7893 consistent(&p, "split");
7894 assert!(p.ripple_delete(1, 3));
7895 consistent(&p, "ripple_delete");
7896 assert!(p.undo());
7897 consistent(&p, "undo");
7898 }
7899
7900 /// What an edit produces is what a save writes, so *every* state the public
7901 /// API can reach has to load again. The two the verifier panel found where
7902 /// it did not: a split and a regroup handed one group id to two clips that
7903 /// were not the same span, because the lanes had been edited apart.
7904 #[test]
7905 fn every_reachable_state_reloads() {
7906 let mut p = Project::single(FILE, 150);
7907 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
7908 assert!(p.split(10), "the lanes are cut apart at 10");
7909 reloads(&p, "place on one lane, then split");
7910
7911 let mut p = Project::single(FILE, 150);
7912 assert!(p.split(30));
7913 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
7914 assert!(p.regroup(30), "only the audio lane can rejoin");
7915 assert!(p.split(60));
7916 reloads(&p, "lift, regroup one lane, split");
7917
7918 // Two audio streams of one file, both placed: two source entries with
7919 // one path between them, which is the state a stream picked out of the
7920 // library reaches -- and the state a save has to write and read back.
7921 let mut p = Project::single(FILE, 150);
7922 let second = p.import(FILE, 1);
7923 assert_eq!(second, 1, "the same file on another stream is a new source");
7924 assert!(p.append_clip(second, 150));
7925 assert!(p.split(200));
7926 reloads(
7927 &p,
7928 "a second audio stream of the same file, placed and split",
7929 );
7930 let (sources, ..) = p.without_orphan_sources();
7931 assert_eq!(
7932 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
7933 [0, 1],
7934 "both entries survive the orphan prune: both are played"
7935 );
7936 }
7937
7938 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
7939 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
7940 /// is the stamp playback puts on a decoded source frame -- and the *last*
7941 /// source frame the pump is still holding at a timeline frame has to be
7942 /// exactly the one the export encoded there, at every rate. Anything else is
7943 /// A/V drift that grows with the clip, and no test of either side alone
7944 /// would see it.
7945 ///
7946 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
7947 /// is a better answer than the floor/floor this had: floor/floor put the
7948 /// preview a whole held frame off the export at slow rates.)
7949 #[test]
7950 fn speed_maps_both_ways() {
7951 for permille in (250..=4000).step_by(1) {
7952 let speed = Speed::from_permille(permille);
7953 assert_eq!(speed.permille(), permille, "no clamping in range");
7954 for d in 0..200u32 {
7955 let want = speed.source_at(d);
7956 // What the pump shows at `d` is the last frame whose stamp has
7957 // come due -- and it is `want`, the frame the export encodes
7958 // there. Slowed, that is the frame it is still holding; sped up,
7959 // it is the newest of the several that arrived.
7960 let held = (0..=want + 8)
7961 .filter(|&s| speed.timeline_at(s) <= d)
7962 .next_back();
7963 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
7964 }
7965 for n in 1..300u32 {
7966 // A footprint is never zero: a clip occupying no timeline frame
7967 // is a placement the lane invariants cannot hold.
7968 let frames = speed.frames(n);
7969 assert!(frames >= 1, "{speed} of {n} frames");
7970 // ...and its last timeline frame never reads past the clip.
7971 assert!(
7972 speed.source_at(frames - 1) < n,
7973 "{speed}: the last timeline frame of {n} reads past the clip"
7974 );
7975 // The trim inverse never overshoots the room it was given, and
7976 // answers for every room a footprint can be.
7977 let fit = speed.fit(frames).expect("a clip fits its own footprint");
7978 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
7979 // A room narrower than one source frame's own footprint holds
7980 // nothing, and says so rather than rounding something into it.
7981 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
7982 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
7983 }
7984 }
7985 // Real time is the identity map, byte for byte.
7986 for d in 0..1000 {
7987 assert_eq!(Speed::NORMAL.source_at(d), d);
7988 assert_eq!(Speed::NORMAL.timeline_at(d), d);
7989 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
7990 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
7991 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
7992 }
7993 // The one door: no zero, no reverse, nothing past the ends.
7994 assert_eq!(Speed::from_permille(0), Speed::MIN);
7995 assert_eq!(Speed::from_permille(249), Speed::MIN);
7996 assert_eq!(Speed::from_permille(4001), Speed::MAX);
7997 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
7998 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
7999 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
8000 }
8001
8002 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
8003 /// export encodes at a timeline frame is the one playback is holding there,
8004 /// a file is as long in timeline frames as the seconds it lasts, and the two
8005 /// compose so a speeded clip at another rate is exactly both.
8006 #[test]
8007 fn rate_composes_with_speed() {
8008 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
8009 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
8010 // the identity map or a single-rate project would move.
8011 for (source_fps, timeline_fps) in [
8012 (24000. / 1001., 30.),
8013 (30., 24000. / 1001.),
8014 (60., 30.),
8015 (25., 30.),
8016 (30., 30.),
8017 ] {
8018 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
8019 for n in 0..2000u32 {
8020 let source = rate.source_at(n);
8021 // The stamp is the *first* timeline-rate frame that shows it, so
8022 // the picture on screen at `n` is the picture encoded at `n`.
8023 let held = (0..=source + 4)
8024 .filter(|&s| rate.timeline_at(s) <= n)
8025 .next_back();
8026 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
8027 }
8028 // A file of `count` frames is `timeline_at(count)` frames long here,
8029 // and its last one still reads a frame the file has.
8030 for count in 1..500u32 {
8031 let frames = rate.timeline_at(count);
8032 assert!(frames >= 1, "a file is never zero frames long");
8033 assert!(
8034 rate.source_at(frames - 1) < count,
8035 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
8036 );
8037 }
8038 // No drift: the mapping is one exact division of the *rate itself*,
8039 // not an accumulation and not a rounded rate, so an hour in is as
8040 // true as the first second. (Held to the real ratio of the two rates
8041 // the caller asked for -- `as_f64` would be true of a wrong rate.)
8042 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
8043 let want = f64::from(n) * source_fps / timeline_fps;
8044 assert!(
8045 (f64::from(rate.source_at(n)) - want).abs() < 1.,
8046 "{source_fps} on {timeline_fps}: frame {n} drifted"
8047 );
8048 }
8049 }
8050 // The timeline's own rate is the identity, whichever way it is written.
8051 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
8052 assert!(
8053 Rate::from_fps(30.0004, 30.)
8054 .expect("30.0004 over 30")
8055 .is_real_time(),
8056 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
8057 );
8058 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
8059 // one thing `matches_timeline` refuses a file for now that the rate gate
8060 // is gone.
8061 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
8062 assert!(Rate::from_fps(30., f64::NAN).is_err());
8063 for n in 0..1000 {
8064 assert_eq!(Rate::REAL_TIME.source_at(n), n);
8065 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
8066 }
8067 // ...and the composition, in the order the decoder's door applies it:
8068 // the speed picks the clip's (timeline-rate) frame, the rate picks the
8069 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
8070 // timeline frames per frame shown, each of them exactly 800/1001 of a
8071 // file frame.
8072 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
8073 let speed = Speed::from_permille(2000);
8074 for d in 0..100u32 {
8075 assert_eq!(
8076 rate.source_at(speed.source_at(d)),
8077 (u64::from(d) * 2 * 800 / 1001) as u32,
8078 "2x of a 23.976 fps file at timeline frame {d}"
8079 );
8080 }
8081 }
8082
8083 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
8084 /// source frames per timeline frame and still starts at its own in-point,
8085 /// and a half-speed one shows every source frame twice.
8086 #[test]
8087 fn a_rate_maps_timeline_frames_onto_source_frames() {
8088 let mut p = Project::single(FILE, 40);
8089 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8090 .expect("room enough");
8091 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
8092 assert_eq!(
8093 p.map(Lane::V1, 0),
8094 Some((0, 0)),
8095 "and it starts where it did"
8096 );
8097 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
8098 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
8099 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
8100 // The span a decoder is handed: as many source frames as it will read,
8101 // which is the last shown frame's own and not one more -- timeline frame
8102 // 19 shows source frame 38, so 39 frames are read and the 40th is a
8103 // picture nothing would display.
8104 let span = p.span_at(Lane::V1, 0).expect("a span");
8105 assert_eq!((span.len, span.source_len()), (20, 39));
8106 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
8107 // ...and the same clip the other way round.
8108 let mut p = Project::single(FILE, 40);
8109 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8110 .expect("room enough");
8111 assert_eq!(p.timeline_frames(), 80);
8112 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
8113 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
8114 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
8115 assert_eq!(
8116 p.map(Lane::V1, 79),
8117 Some((0, 39)),
8118 "and the last timeline frame is still inside the source range"
8119 );
8120 }
8121
8122 /// A trim of a speeded clip is still a trim of its *source*, and the edge
8123 /// still stops at the wall: the room a rate leaves is measured in timeline
8124 /// frames and the range it commits in source ones.
8125 #[test]
8126 fn trimming_a_speeded_clip_stays_inside_its_room() {
8127 let mut p = Project::single(FILE, 40);
8128 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8129 .expect("room enough");
8130 // A second clip butted against the first, so the wall is a real one.
8131 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
8132 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
8133 assert_eq!(room, (1, 20), "out to the neighbour and no further");
8134 assert!(
8135 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
8136 "clamped to the wall, which is where the edge already is"
8137 );
8138 let c = p.clips()[0];
8139 assert_eq!(c.end(), 20, "so nothing moved");
8140 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
8141 // ...and in: half the timeline frames is half the source range.
8142 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
8143 let c = p.clips()[0];
8144 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
8145 assert_eq!(c.end(), 10, "and ten timeline frames of them");
8146 assert!(sorted_disjoint(p.clips()));
8147 }
8148
8149 /// The frames a rate cannot address: at half speed each source frame is on
8150 /// screen twice, and the cut between the two showings is not a cut in the
8151 /// file. Refused, so the two halves always add up to the clip that was cut.
8152 #[test]
8153 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
8154 let mut p = Project::single(FILE, 10);
8155 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8156 .expect("room enough");
8157 assert_eq!(p.timeline_frames(), 20);
8158 assert!(
8159 !p.split(3),
8160 "an odd frame is between two showings of one frame"
8161 );
8162 assert_eq!(p.clips().len(), 1, "and nothing was cut");
8163 assert!(p.split(4), "an even one is a frame boundary");
8164 let halves = p.clips().to_vec();
8165 assert_eq!(
8166 (halves[0].end(), halves[1].start, halves[1].end()),
8167 (4, 4, 20),
8168 "the halves meet, and still end where the clip did"
8169 );
8170 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
8171 assert!(p.regroup(4), "and the inverse puts it back");
8172 assert_eq!(p.clips().len(), 1);
8173 }
8174
8175 /// The same claim, swept: random op sequences off the public surface, the
8176 /// project reloaded after every one of them. A failure prints its seed, and
8177 /// the seed replays the whole sequence.
8178 #[test]
8179 fn random_edit_sequences_reload() {
8180 // Two thousand, not two hundred: the overlap a hole punched into a slow
8181 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
8182 // sequences, and a 200-seed sweep walked straight past it (it took a
8183 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
8184 // has no business being the narrow one.
8185 for seed in 0..2000u64 {
8186 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8187 let mut next = move |n: u32| {
8188 // xorshift64*: no dependency, and the seed replays it exactly.
8189 rng ^= rng << 13;
8190 rng ^= rng >> 7;
8191 rng ^= rng << 17;
8192 (rng >> 33) as u32 % n
8193 };
8194 let mut p = Project::single(FILE, 40);
8195 for step in 0..24 {
8196 let frame = next(44);
8197 // A clipboard copy carries the group id of the take it came from
8198 // -- the input that made a placement duplicate an id -- and, one
8199 // time in three, a rate of its own: a *speeded clip placed over
8200 // a speeded clip* is the shape whose remainders have to be run
8201 // through `Speed::fit`, and it is not a shape the lanes hand out
8202 // on their own often enough to be sure of.
8203 let mut copied = *p
8204 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
8205 .get(next(4) as usize)
8206 .unwrap_or(&clip(0, 0, 5, 0));
8207 if next(3) == 0 {
8208 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
8209 }
8210 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
8211 let idx = next(4) as usize;
8212 let _ = match next(16) {
8213 // A clip dragged along its own lane to wherever the pointer
8214 // let it go: the op that moves a placement without changing
8215 // what it plays, so what it may not do is land on top of the
8216 // neighbour it was dragged at.
8217 15 => p.move_clip(lane, idx, lane, frame),
8218 // ...and a second `place`, so a punch lands inside a clip
8219 // far more often than one op in fourteen would put it there.
8220 14 => p.place(lane, frame, copied),
8221 0 => p.split(frame),
8222 1 => p.regroup(frame),
8223 2 => p.lift(lane, idx),
8224 3 => p.place(lane, frame, copied),
8225 4 => p.paste(frame, copied),
8226 5 => p.ripple_delete(frame, next(9)),
8227 6 => p.delete(idx),
8228 7 => p.undo(),
8229 // An equalizer put on and taken off in the mix: what a clip
8230 // carries has to reload with it, and the entries an undo
8231 // orphans must not come back out of the prune.
8232 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8233 9 => p.set_eq(lane, idx, None),
8234 // ...and a colour grade in the same mix, for the same
8235 // reason: it rides on the clip and its orphans must go.
8236 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
8237 11 => p.set_color(lane, idx, None),
8238 // ...and a rate in with them, which is the one of the three
8239 // that moves *placements*: a clip that grew has to be
8240 // refused rather than overlap, and one that shrank leaves a
8241 // lane that still loads. Both are what `reloads` asks.
8242 12 => p
8243 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8244 .is_ok(),
8245 _ => p.append_clip(0, 1 + next(9)),
8246 };
8247 reloads(&p, &format!("seed {seed}, step {step}"));
8248 }
8249 }
8250 }
8251
8252 /// The save/load round trip a project must survive: the parts a save writes,
8253 /// handed back to the constructor a load goes through -- every lane of them,
8254 /// and the reloaded timeline has to be the same lanes in the same order.
8255 fn reloads(p: &Project, what: &str) {
8256 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
8257 match Project::from_parts(sources, lanes, eq, color) {
8258 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
8259 Ok(back) => {
8260 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
8261 // Placements, not whole clips: an orphan prune renumbers the
8262 // sources a clip names, which is the point of it.
8263 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
8264 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
8265 };
8266 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
8267 // The prune renumbers the eq table too, so what has to survive
8268 // is the settings themselves, clip by clip.
8269 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
8270 p.lanes()
8271 .into_iter()
8272 .map(|l| {
8273 (0..p.lane(l).len())
8274 .map(|i| p.eq_of(l, i).cloned())
8275 .collect()
8276 })
8277 .collect()
8278 };
8279 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
8280 // The colour table renumbers in the same prune, so the same
8281 // claim: the params a clip names, not the index it names them by.
8282 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
8283 p.lanes()
8284 .into_iter()
8285 .map(|l| {
8286 (0..p.lane(l).len())
8287 .map(|i| p.color_of(l, i).copied())
8288 .collect()
8289 })
8290 .collect()
8291 };
8292 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
8293 }
8294 }
8295 }
8296
8297 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
8298 /// -- each one sorted and disjoint, and one span per group id -- asserted
8299 /// directly, where the point is the invariant rather than the round trip.
8300 fn invariants_hold(p: &Project, what: &str) {
8301 for lane in p.lanes() {
8302 assert!(
8303 sorted_disjoint(p.lane(lane)),
8304 "{what}: {} is out of order or overlaps itself: {:?}",
8305 lane.label(),
8306 p.lane(lane)
8307 );
8308 }
8309 if let Err(e) = links_are_consistent(&p.lanes) {
8310 panic!("{what}: {e}\n{:?}", p.lanes);
8311 }
8312 }
8313
8314 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
8315 /// edited without any other lane hearing about it. A handle naming a lane
8316 /// that is not there reads as empty and refuses to mutate.
8317 #[test]
8318 fn a_third_lane_is_a_peer() {
8319 let mut p = three();
8320 assert_eq!(p.lane_count(LaneKind::Video), 1);
8321 assert_eq!(p.lane_count(LaneKind::Audio), 1);
8322 let v2 = p.add_lane(LaneKind::Video);
8323 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
8324 assert_eq!(v2.label(), "V2");
8325 assert_eq!(p.lane_count(LaneKind::Video), 2);
8326 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8327 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
8328
8329 // A handle for a lane that is not there: empty, and no mutation takes.
8330 let v3 = Lane::new(LaneKind::Video, 2);
8331 assert!(p.lane(v3).is_empty());
8332 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
8333 assert!(!p.lift(v3, 0));
8334 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
8335
8336 // Placing on V2 moves nothing else, and the lane can outrun the rest.
8337 let before = shape(&p);
8338 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8339 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
8340 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
8341 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8342 assert_eq!(
8343 p.timeline_frames(),
8344 16,
8345 "the last lane to end sets the length"
8346 );
8347 assert_eq!(p.map(v2, 5), Some((0, 21)));
8348 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
8349 assert_eq!(
8350 p.span_at(v2, 0),
8351 Some(Span {
8352 start: 0,
8353 len: 4,
8354 from: None,
8355 speed: Speed::NORMAL
8356 })
8357 );
8358 // Every lane still covers the whole timeline, gaps included.
8359 for l in p.lanes() {
8360 let spans = p.spans_from(l, 0);
8361 assert_eq!(
8362 spans.iter().map(|s| s.len).sum::<u32>(),
8363 16,
8364 "{}",
8365 l.label()
8366 );
8367 }
8368 // ...and playback still reads V1 and A1, whatever else is there.
8369 assert_eq!(p.clips(), p.lane(Lane::V1));
8370 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
8371 let segments = p.segments_from(0, FPS);
8372 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
8373 assert_eq!(
8374 segments[3],
8375 (None, 0.0, 7.0 / FPS),
8376 "A1 keeps the clock counting over the picture V2 added"
8377 );
8378 invariants_hold(&p, "place on V2");
8379
8380 // A lift is that lane's business too, and the lane list undoes.
8381 assert!(p.lift(v2, 0));
8382 assert!(p.lane(v2).is_empty());
8383 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
8384 assert!(p.undo());
8385 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8386 assert!(p.undo());
8387 assert!(p.lane(v2).is_empty(), "the placement came off V2");
8388 assert!(p.undo(), "and one more step takes the lane itself back");
8389 assert_eq!(p.lane_count(LaneKind::Video), 1);
8390 assert_eq!(shape(&p), shape(&three()));
8391 }
8392
8393 /// The add taken back: an empty lane comes off, a lane holding clips never
8394 /// does (and says which clips), the last lane of a kind never does, the
8395 /// lanes below the one that went move up an `ord`, and one undo puts it
8396 /// back where it stood.
8397 #[test]
8398 fn an_empty_lane_comes_off_again() {
8399 let mut p = three();
8400 let v2 = p.add_lane(LaneKind::Video);
8401 let v3 = p.add_lane(LaneKind::Video);
8402 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
8403 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
8404 let history = p.history.len();
8405
8406 // The last lane of its kind stays: `V1`/`A1` are where an import and a
8407 // paste land, and a project missing one would swallow half of a file
8408 // dropped on it.
8409 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
8410 assert_eq!(
8411 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
8412 "there is no V10 to remove"
8413 );
8414
8415 // A lane with clips on it refuses and names them: a track removal never
8416 // deletes a take.
8417 let refusal = why(p.remove_lane(v3));
8418 assert!(refusal.contains("V3 still holds"), "{refusal}");
8419 assert!(refusal.contains(FILE), "{refusal}");
8420 assert!(refusal.contains("at frame 0"), "{refusal}");
8421 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
8422 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
8423
8424 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
8425 // all.
8426 p.remove_lane(v2).expect("V2 is empty");
8427 assert_eq!(p.lane_count(LaneKind::Video), 2);
8428 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8429 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
8430 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
8431 invariants_hold(&p, "remove V2");
8432
8433 // ...and one stroke puts the empty lane back above it.
8434 assert!(p.undo());
8435 assert_eq!(p.lane_count(LaneKind::Video), 3);
8436 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
8437 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
8438 }
8439
8440 /// A track dragged to another place in the stack: the whole lane travels --
8441 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
8442 /// a video one, a lane that crosses one of its own kind swaps names with it
8443 /// (and swaps the composite with it), one undo puts the order back, and a
8444 /// save carries it.
8445 #[test]
8446 fn a_track_is_dragged_to_another_place_in_the_stack() {
8447 let mut p = three();
8448 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
8449 let before = shape(&p);
8450 let history = p.history.len();
8451
8452 // A1 over V1: the screen is rearranged and nothing else is. Both keep
8453 // their names -- neither crossed a lane of its own kind -- so every
8454 // handle a front-end holds still names the track it named before.
8455 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
8456 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
8457 assert_eq!(
8458 shape(&p),
8459 vec![before[1].clone(), before[0].clone()],
8460 "each lane's clips travelled with it, and none was remapped"
8461 );
8462 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
8463 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
8464 invariants_hold(&p, "A1 over V1");
8465
8466 // Nothing moves for a lane that is not there, a slot that is not, or a
8467 // lane already standing in the one it was pointed at.
8468 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
8469 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
8470 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
8471 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
8472
8473 // ...and one stroke puts the order back.
8474 assert!(p.undo());
8475 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
8476 assert_eq!(shape(&p), before);
8477
8478 // A second video lane over the first: display order *is* the stack, so
8479 // the last video lane covering a frame is the picture that shows.
8480 let v2 = p.add_lane(LaneKind::Video);
8481 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
8482 let over = shape(&p)[2].clone();
8483 assert_eq!(
8484 p.composite_span_at(0).map(|s| s.len),
8485 Some(5),
8486 "V2's five frames are what frame 0 shows"
8487 );
8488
8489 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
8490 // a position among the lanes of its kind. The picture that wins changes
8491 // with it: the take that was covering is the covered one now.
8492 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
8493 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
8494 assert_eq!(
8495 shape(&p),
8496 vec![over.clone(), before[0].clone(), before[1].clone()],
8497 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
8498 );
8499 assert_eq!(
8500 p.composite_span_at(0).map(|s| s.len),
8501 Some(3),
8502 "the lower video lane wins, and it is the old V1 now"
8503 );
8504 invariants_hold(&p, "V2 over V1");
8505
8506 // A save writes that order and a load takes it back.
8507 let (sources, lanes, eq, color) = p.without_orphan_sources();
8508 assert_eq!(
8509 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
8510 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
8511 );
8512 let back = Project::from_parts(sources, lanes, eq, color).expect("three lanes load");
8513 assert_eq!(back.lanes(), p.lanes());
8514 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
8515
8516 assert!(p.undo(), "and the stack goes back to how it stood");
8517 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
8518 }
8519
8520 /// The grouping rule across more than two lanes, under the offset model: a
8521 /// split *keeps* the group on the left halves and hands the right halves of
8522 /// that group one fresh id of their own -- a clip in no group comes out of
8523 /// the cut in none. So a take cut apart is two takes, one per side, and a
8524 /// lane that was never part of it stays out of both.
8525 #[test]
8526 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
8527 let mut p = Project::single(FILE, 9);
8528 let take = p.clips()[0].link.expect("a fresh project is one take");
8529 let v2 = p.add_lane(LaneKind::Video);
8530 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
8531 assert!(p.split(4));
8532 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
8533 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
8534 };
8535 let (left, right) = (side(&p, 0), side(&p, 1));
8536 // The lanes in order are V1, A1, V2: the take's two keep its id on the
8537 // left, and the placed clip never had one for the cut to keep.
8538 assert_eq!(
8539 left,
8540 vec![Some(take), Some(take), None],
8541 "the left halves keep the take"
8542 );
8543 // ...and the right halves of that take are one fresh group.
8544 assert_eq!(right[0], right[1]);
8545 assert_ne!(right[0], Some(take));
8546 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
8547 invariants_hold(&p, "split across three lanes");
8548
8549 // V2 ends early: the left halves still keep what each clip carried --
8550 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
8551 // shared by exactly the take's lanes.
8552 let mut p = Project::single(FILE, 9);
8553 let v2 = p.add_lane(LaneKind::Video);
8554 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
8555 assert!(p.split(3));
8556 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
8557 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
8558 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
8559 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
8560 invariants_hold(&p, "split where one lane ends early");
8561
8562 // The inverse rejoins each lane into the group its left half kept.
8563 assert!(p.regroup(3));
8564 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
8565 assert_eq!(
8566 p.lane(Lane::V1)[0].link,
8567 Some(take),
8568 "the take's id is back, not a fresh one"
8569 );
8570 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
8571 invariants_hold(&p, "regroup across three lanes");
8572 }
8573
8574 /// A group is one placement per lane, on however many lanes carry the id --
8575 /// not a video/audio pair and not a pairing by `ord` -- and the members may
8576 /// cover whatever frames they cover: the offset between them is what a
8577 /// hand-built group keeps. Lanes built by hand, because the rule is checked
8578 /// at the untrusted door and no edit can produce the one thing it refuses.
8579 #[test]
8580 fn a_group_may_span_any_lane() {
8581 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
8582 let one = |start: u32, end: u32, link| Clip {
8583 start,
8584 in_frame: start,
8585 out_frame: end,
8586 source: 0,
8587 link: Some(link),
8588 eq: None,
8589 color: None,
8590 fit: FitPolicy::default(),
8591 speed: Speed::NORMAL,
8592 };
8593 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
8594 let kinds = [
8595 LaneKind::Video,
8596 LaneKind::Audio,
8597 LaneKind::Video,
8598 LaneKind::Audio,
8599 ];
8600 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
8601 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
8602 };
8603 let take = || vec![one(0, 4, 7)];
8604 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
8605 // The same take on V1 + A2 only, the lanes between it empty: legal, the
8606 // way a lifted half is legal.
8607 let across = build([take(), Vec::new(), Vec::new(), take()]);
8608 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
8609 // ...and so is a group whose members disagree about their spans: the
8610 // offset between them is the hand's business, not the loader's.
8611 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
8612 assert!(
8613 links_are_consistent(&apart).is_ok(),
8614 "[0, 4) on V1 and [2, 6) on A2 are one group"
8615 );
8616 // One id twice in one lane is still that lane's error, by name.
8617 let twice = build([
8618 Vec::new(),
8619 Vec::new(),
8620 vec![one(0, 4, 7), one(4, 8, 7)],
8621 Vec::new(),
8622 ]);
8623 assert_eq!(
8624 links_are_consistent(&twice).unwrap_err().to_string(),
8625 "link 7 names two clips in the V2 lane"
8626 );
8627 }
8628
8629 /// Every lane a save writes comes out, in display order and with its kind --
8630 /// an empty one included, since it is state a front-end shows -- and a
8631 /// two-lane project still writes exactly the parts it always did.
8632 #[test]
8633 fn a_save_writes_every_lane_it_has() {
8634 let mut p = three();
8635 let before = p.without_orphan_sources();
8636 assert_eq!(before.1.len(), 2, "V1 and A1");
8637 let v2 = p.add_lane(LaneKind::Video);
8638 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8639 let a2 = p.add_lane(LaneKind::Audio);
8640 let (sources, lanes, eq, color) = p.without_orphan_sources();
8641 assert_eq!(
8642 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
8643 [
8644 LaneKind::Video,
8645 LaneKind::Audio,
8646 LaneKind::Video,
8647 LaneKind::Audio
8648 ],
8649 "display order, not video-then-audio"
8650 );
8651 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
8652 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
8653 // ...and all four load again as the same four.
8654 let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load");
8655 assert_eq!(back.lanes(), p.lanes());
8656 assert_eq!(back.lane(a2), p.lane(a2));
8657
8658 // Taking the lanes back leaves exactly what a two-lane save wrote.
8659 for _ in 0..3 {
8660 assert!(p.undo());
8661 }
8662 assert_eq!(
8663 p.without_orphan_sources(),
8664 before,
8665 "byte for byte the same parts a two-lane save always wrote"
8666 );
8667 }
8668
8669 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
8670 /// three lanes and grows more: every lane's own order and the one
8671 /// span-per-id rule after every op, *and* the reload the v4 format restored
8672 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
8673 /// project of any number of lanes.
8674 #[test]
8675 fn random_edit_sequences_keep_many_lanes_consistent() {
8676 for seed in 0..2000u64 {
8677 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8678 let mut next = move |n: u32| {
8679 rng ^= rng << 13;
8680 rng ^= rng >> 7;
8681 rng ^= rng << 17;
8682 (rng >> 33) as u32 % n
8683 };
8684 let mut p = Project::single(FILE, 40);
8685 let v2 = p.add_lane(LaneKind::Video);
8686 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
8687 let lanes = [Lane::V1, Lane::A1, v2];
8688 for step in 0..24 {
8689 let frame = next(44);
8690 let copied = *p
8691 .lane(lanes[next(3) as usize])
8692 .get(next(4) as usize)
8693 .unwrap_or(&clip(0, 0, 5, 0));
8694 let lane = lanes[next(3) as usize];
8695 let idx = next(4) as usize;
8696 let _ = match next(14) {
8697 // The drag, in the mix: a clip dragged along its own lane
8698 // and onto another one, at a frame the pointer picked --
8699 // which is where the group rule and the sorted+disjoint one
8700 // meet, since every half travels the same distance.
8701 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
8702 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8703 11 => p.set_eq(lane, idx, None),
8704 // A rate, which on many lanes is the group rule as well:
8705 // every clip carrying the link moves together or none of
8706 // them does, and `invariants_hold` is what says so.
8707 12 => p
8708 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8709 .is_ok(),
8710 0 => p.split(frame),
8711 1 => p.regroup(frame),
8712 2 => p.lift(lane, idx),
8713 3 => p.place(lane, frame, copied),
8714 4 => p.paste(frame, copied),
8715 5 => p.ripple_delete(frame, next(9)),
8716 6 => p.delete(idx),
8717 7 => p.undo(),
8718 8 => {
8719 p.add_lane(if next(2) == 0 {
8720 LaneKind::Video
8721 } else {
8722 LaneKind::Audio
8723 });
8724 true
8725 }
8726 _ => p.append_clip(0, 1 + next(9)),
8727 };
8728 invariants_hold(&p, &format!("seed {seed}, step {step}"));
8729 reloads(&p, &format!("seed {seed}, step {step}"));
8730 }
8731 }
8732 }
8733
8734 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
8735 /// there, `V1` shows again on either side of it, and a frame no video lane
8736 /// covers is a gap however many lanes there are.
8737 #[test]
8738 fn the_composite_is_the_topmost_lane_with_a_clip() {
8739 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8740 let lanes = vec![
8741 // V1: the whole 30 frames of source 0.
8742 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8743 // V2: source 1 over the middle third.
8744 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
8745 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8746 ];
8747 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
8748 assert_eq!(
8749 p.composite_spans_from(0),
8750 vec![
8751 Span {
8752 start: 0,
8753 len: 10,
8754 from: Some((0, 0)),
8755 speed: Speed::NORMAL
8756 },
8757 Span {
8758 start: 10,
8759 len: 10,
8760 from: Some((1, 5)),
8761 speed: Speed::NORMAL
8762 },
8763 Span {
8764 start: 20,
8765 len: 10,
8766 from: Some((0, 20)),
8767 speed: Speed::NORMAL
8768 },
8769 ],
8770 "V2 takes over for its own span and hands V1 back"
8771 );
8772 // A mid-span ask resolves the same way, which is what a seek does.
8773 assert_eq!(
8774 p.composite_span_at(15),
8775 Some(Span {
8776 start: 15,
8777 len: 5,
8778 from: Some((1, 10)),
8779 speed: Speed::NORMAL
8780 })
8781 );
8782 assert_eq!(p.composite_span_at(30), None, "past the end");
8783
8784 // A hole in V1 under V2's clip: black between the two, and black after
8785 // both run out (the audio lane is still holding the timeline open).
8786 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8787 let holed = vec![
8788 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
8789 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
8790 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8791 ];
8792 let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts");
8793 assert_eq!(
8794 p.composite_spans_from(0),
8795 vec![
8796 Span {
8797 start: 0,
8798 len: 5,
8799 from: Some((0, 0)),
8800 speed: Speed::NORMAL
8801 },
8802 Span {
8803 start: 5,
8804 len: 5,
8805 from: None,
8806 speed: Speed::NORMAL
8807 },
8808 Span {
8809 start: 10,
8810 len: 10,
8811 from: Some((1, 0)),
8812 speed: Speed::NORMAL
8813 },
8814 Span {
8815 start: 20,
8816 len: 10,
8817 from: None,
8818 speed: Speed::NORMAL
8819 },
8820 ]
8821 );
8822
8823 // One video lane: the composite *is* that lane, span for span -- the
8824 // promise every existing two-lane project rests on.
8825 let p = Project::single(FILE, 30);
8826 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
8827 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
8828 }
8829
8830 /// Every audio lane holding something gets a play list, and only those.
8831 #[test]
8832 fn audio_segments_cover_every_lane_that_holds_something() {
8833 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8834 let lanes = vec![
8835 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8836 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8837 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
8838 (LaneKind::Audio, Vec::new()),
8839 ];
8840 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
8841 let lists = p.audio_segments_from(0, FPS);
8842 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
8843 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
8844 // A2 is a gap up to frame 15, then the whole of source 1.
8845 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
8846
8847 // No audio lane holds anything: one all-gap list, so such a timeline
8848 // still plays silence against a master clock.
8849 let p = Project::from_parts(
8850 vec![Source::new(FILE, 0)],
8851 vec![
8852 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8853 (LaneKind::Audio, Vec::new()),
8854 ],
8855 vec![],
8856 vec![],
8857 )
8858 .expect("valid parts");
8859 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
8860 }
8861}