forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB99d87d4Tahinli3 months ago508 commits

project.rs8749 lines, 382.4 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::eq::EqParams;
81use crate::limiter::{Limiter, db_to_linear};
82use crate::scale::FitPolicy;
83use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
84
85/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
86/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
87/// for every purpose but the honest one, which is that it is still a level and
88/// not a mute.
89pub const MIN_GAIN_DB: f32 = -60.0;
90/// ...and how far up. +12 dB is four times the amplitude, which is as much as
91/// a mix bus can take before the limiter is doing all the work.
92pub const MAX_GAIN_DB: f32 = 12.0;
93
94/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
95/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
96/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
97/// comparable nor exactly writable, and `.edith` has to read back the very
98/// number that was set. A thousandth is finer than any card can drag and coarser
99/// than any rounding anyone can hear.
100///
101/// The rate alone: the audio path time-stretches a speeded clip
102/// (`crate::stretch`), so its pitch stays where it was recorded while its
103/// seconds compress or stretch -- the tape effect this used to be is gone.
104/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
105/// [`Speed::MAX`] four times.
106#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
107pub struct Speed(u16);
108
109/// What [`Project::parts`] hands back: the comparable shape of everything an
110/// edit can change, for the sweep's undo round-trip. Test-only, like every
111/// accessor it exists for: the sweep lives behind `cfg(test)`.
112#[cfg(test)]
113#[derive(Clone, Debug, PartialEq)]
114pub(crate) struct SweepParts(
115 pub(crate) usize,
116 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
117 pub(crate) Vec<Vec<SubClip>>,
118);
119
120impl Speed {
121 /// Real time -- what every clip is until something says otherwise, and the
122 /// value every path in this engine short-circuits on.
123 pub const NORMAL: Speed = Speed(1000);
124 pub const MIN: Speed = Speed(250);
125 pub const MAX: Speed = Speed(4000);
126
127 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
128 /// unrepresentable rather than merely refused: nothing downstream divides
129 /// by a speed that could be nothing.
130 pub fn from_permille(permille: u16) -> Self {
131 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
132 }
133
134 pub fn permille(self) -> u16 {
135 self.0
136 }
137
138 pub fn is_normal(self) -> bool {
139 self == Self::NORMAL
140 }
141
142 /// As a multiplier, for the sound worker and for a label.
143 pub fn as_f64(self) -> f64 {
144 f64::from(self.0) / 1000.
145 }
146
147 /// How many *timeline* frames `source` source frames occupy at this rate --
148 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
149 /// clip that occupied no frames would be an empty placement, which the lane
150 /// invariant forbids and which nothing could ever click on again.
151 pub fn frames(self, source: u32) -> u32 {
152 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
153 n.clamp(1, u64::from(u32::MAX)) as u32
154 }
155
156 /// The mapping itself: which source frame of a clip the `offset`th timeline
157 /// frame of it plays. Floored, so the first timeline frame is the clip's own
158 /// in-point at every rate.
159 pub fn source_at(self, offset: u32) -> u32 {
160 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
161 }
162
163 /// Its inverse, for a decoder's frames on their way back out: which timeline
164 /// frame of the clip the `offset`th *source* frame of it lands on.
165 ///
166 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
167 /// decoded frame with this and shows the newest whose stamp has come due, so
168 /// what is on screen at timeline offset `d` is the last source frame with
169 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
170 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
171 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
172 /// the two the same way would put the preview a frame off the export at some
173 /// speeds and a whole held frame off at slow ones -- drift that no test of
174 /// either side alone would catch.
175 pub fn timeline_at(self, offset: u32) -> u32 {
176 (u64::from(offset) * 1000)
177 .div_ceil(u64::from(self.0))
178 .min(u64::from(u32::MAX)) as u32
179 }
180
181 /// The longest source range that still *fits* in `frames` timeline frames at
182 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
183 /// any room narrower than the four timeline frames one source frame occupies.
184 ///
185 /// What a trim commits and what a hole-punch leaves behind: rounding could
186 /// otherwise hand back a range wider than the room, and a clip that outgrew
187 /// its room would overlap its neighbour -- the one thing a lane may never do.
188 /// `None` is not an error, it is "no remainder": the caller drops that piece
189 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
190 /// is `frames` itself, so nothing about an unspeeded edit changes.
191 pub fn fit(self, frames: u32) -> Option<u32> {
192 if frames == 0 || self.frames(1) > frames {
193 return None;
194 }
195 let mut src = self.source_at(frames).max(1);
196 // At most a step or two: `frames` is monotone in `src` and the rounding
197 // above can only overshoot by one source frame's worth.
198 while src > 1 && self.frames(src) > frames {
199 src -= 1;
200 }
201 Some(src)
202 }
203
204 /// How many timeline frames `source` source frames of head (or tail) are
205 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
206 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
207 /// empty, but the room in front of one may well be.
208 pub fn room(self, source: u32) -> u32 {
209 match source {
210 0 => 0,
211 n => self.frames(n),
212 }
213 }
214
215 /// How many timeline frames from `offset` on show the **same** source frame:
216 /// one at real time and faster, more when the clip is slowed. What an export
217 /// encodes without decoding the same picture twice, and the count that makes
218 /// its frame walk exactly as long as the span.
219 pub fn repeats(self, offset: u32, len: u32) -> u32 {
220 let want = self.source_at(offset);
221 (offset..len)
222 .take_while(|&t| self.source_at(t) == want)
223 .count() as u32
224 }
225
226 /// Where in the source a cut `offset` timeline frames into a clip of `len`
227 /// source frames falls -- and `None` when this rate cannot address that
228 /// frame at all.
229 ///
230 /// At half speed a clip of ten source frames is twenty timeline frames long
231 /// and every source frame is on screen twice, so a cut between the two
232 /// showings of one frame is not a cut in the *file*: taking it would leave
233 /// two halves whose lengths no longer add up to the clip that was cut --
234 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
235 /// the model stays exact and the front-end can say why. At real time every
236 /// interior frame answers, which is the path a project without speeds is on.
237 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
238 let src = self.source_at(offset);
239 (src > 0
240 && src < len
241 && self.frames(src) == offset
242 && self.frames(len - src) == self.frames(len) - offset)
243 .then_some(src)
244 }
245}
246
247impl Default for Speed {
248 fn default() -> Self {
249 Self::NORMAL
250 }
251}
252
253impl std::fmt::Display for Speed {
254 /// `2.00x` -- what a card prints and what a clip box is marked with.
255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256 write!(f, "{:.2}x", self.as_f64())
257 }
258}
259
260/// What a file's own frame rate is against the timeline's, as an exact
261/// rational: how many frames of the *file* one frame of the timeline is worth.
262///
263/// Every frame number in this module counts **timeline** frames -- a clip's
264/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
265/// timeline is as many frames long as the seconds it lasts, and every edit
266/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
267/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
268/// opens a worker with it and [`crate::export`] pulls pictures through it. The
269/// file's own numbering exists nowhere else.
270///
271/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
272/// export encodes at a timeline frame has to be the frame playback is holding
273/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
274/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
275///
276/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
277/// stays `800/1001` however far the timeline runs, where a rate rounded to
278/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
279/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
280///
281/// [`PlaybackSession`]: crate::PlaybackSession
282#[derive(Clone, Copy, PartialEq, Eq, Debug)]
283pub struct Rate {
284 /// Frames of the file...
285 source: u32,
286 /// ...per this many frames of the timeline it plays on. Never zero.
287 timeline: u32,
288}
289
290impl Rate {
291 /// A file shot at the timeline's own rate: every conversion below is the
292 /// identity, which is the path a single-rate project is on.
293 pub const REAL_TIME: Self = Self {
294 source: 1,
295 timeline: 1,
296 };
297
298 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
299 /// exactly.
300 ///
301 /// Both rates come out of a container as a division, so neither is ever the
302 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
303 /// already knows how to name one exactly -- it is the same pair the muxer
304 /// counts an export's frames in -- and this is that pair divided by that
305 /// pair, reduced. A rate no timescale can name is an `Err` in that
306 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
307 /// where a file carrying one is refused by name, beside the codec.
308 ///
309 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
310 /// timeline that had ever opened in this editor before mixed rates.
311 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
312 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
313 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
314 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
315 let num = u64::from(src_scale) * u64::from(tl_ticks);
316 let den = u64::from(src_ticks) * u64::from(tl_scale);
317 Ok(Self::reduced(num, den))
318 }
319
320 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
321 fn reduced(num: u64, den: u64) -> Self {
322 let g = gcd(num, den);
323 let (mut num, mut den) = (num / g, den / g);
324 // A ratio no pair of real frame rates produces, but the fields are `u32`
325 // so that every multiplication below fits a `u64` at any frame count.
326 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
327 (num, den) = (num.div_ceil(2), den.div_ceil(2));
328 }
329 Self {
330 source: num.max(1) as u32,
331 timeline: den.max(1) as u32,
332 }
333 }
334
335 /// The same file against a timeline that has itself been retimed: `self` is
336 /// its frames per frame of the old timeline and `k` is old frames per new
337 /// one, so this is its frames per frame of the *new* one -- exactly, without
338 /// going back through an `f64` fps that names neither rate
339 /// ([`crate::PlaybackSession::set_frame_rate`]).
340 pub fn then(self, k: Rate) -> Self {
341 Self::reduced(
342 u64::from(self.source) * u64::from(k.source),
343 u64::from(self.timeline) * u64::from(k.timeline),
344 )
345 }
346
347 pub fn is_real_time(self) -> bool {
348 self.source == self.timeline
349 }
350
351 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
352 /// is, given the timeline's, for a library row that names it.
353 pub fn as_f64(self) -> f64 {
354 f64::from(self.source) / f64::from(self.timeline)
355 }
356
357 /// Which frame of the file the `frame`th timeline-rate frame of it is:
358 /// floored, [`Speed::source_at`]'s half of the pair.
359 pub fn source_at(self, frame: u32) -> u32 {
360 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
361 .min(u64::from(u32::MAX)) as u32
362 }
363
364 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
365 /// timeline-rate frame that shows source frame `source_frame` -- which is
366 /// the stamp playback puts on a decoded picture, and, applied to a file's
367 /// frame *count*, how long that file is in timeline frames.
368 pub fn timeline_at(self, source_frame: u32) -> u32 {
369 (u64::from(source_frame) * u64::from(self.timeline))
370 .div_ceil(u64::from(self.source))
371 .min(u64::from(u32::MAX)) as u32
372 }
373}
374
375/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
376/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
377fn gcd(a: u64, b: u64) -> u64 {
378 match b {
379 0 => a.max(1),
380 b => gcd(b, a % b),
381 }
382}
383
384/// A half-open `[in_frame, out_frame)` range of frames of source
385/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
386/// Never empty.
387///
388/// Counted at the **timeline's** frame rate, not the file's: a source shot at
389/// another rate is converted at the decoder's door ([`Rate`]), so every edit
390/// here is frames of one clock.
391#[derive(Clone, Copy, PartialEq, Eq, Debug)]
392pub struct Clip {
393 /// Timeline frame the clip's first frame is shown at. Meaningless on a
394 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
395 /// with where the caller asked for.
396 pub start: u32,
397 pub in_frame: u32,
398 pub out_frame: u32,
399 /// Index into [`Project::sources`].
400 pub source: usize,
401 /// Group id: clips sharing one were split from the same take. `None` for a
402 /// clip that belongs to no group.
403 pub link: Option<u32>,
404 /// Index into the project's equalizer table
405 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
406 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
407 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
408 /// plain assignment. The table is append-only within a session, so an index
409 /// on a clipboard clip or inside an undo snapshot can never dangle.
410 pub eq: Option<u16>,
411 /// Index into the project's colour table
412 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
413 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
414 /// promises: `Copy`, append-only within a session, never dangling.
415 pub color: Option<u16>,
416 /// How this clip's picture meets a project canvas of another shape
417 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
418 /// two above: it is one byte with no parameters, so there is nothing for a
419 /// table to share, and a clip that is the project's own size never consults
420 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
421 /// where the aspect does not agree.
422 pub fit: FitPolicy,
423 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
424 /// eq and colour indexes: it is two bytes with nothing to share, and a table
425 /// would put a level of indirection between the mapping and the one number
426 /// every frame of it is divided by.
427 ///
428 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
429 /// the clip plays, so a trim and a split still address the file. What it
430 /// changes is how many *timeline* frames that range is spread over
431 /// ([`Clip::frames`]).
432 pub speed: Speed,
433}
434
435impl Clip {
436 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
437 /// reads out of its file -- not how long it is on the timeline, which is
438 /// [`Clip::frames`] and differs the moment it is speeded.
439 pub fn len(&self) -> u32 {
440 self.out_frame - self.in_frame
441 }
442
443 /// Timeline frames it occupies: its source range at its own speed, never
444 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
445 /// what it overlaps, how wide its box is -- is asked of this and not of
446 /// [`Clip::len`].
447 pub fn frames(&self) -> u32 {
448 self.speed.frames(self.len())
449 }
450
451 /// One past the last timeline frame it covers.
452 pub fn end(&self) -> u32 {
453 self.start + self.frames()
454 }
455}
456
457/// A file the timeline plays from, and *which* of its audio streams it plays:
458/// a file carrying one track per language is several sources, one per stream,
459/// sharing a path. Two entries differing only in the stream are two sources --
460/// they are what a clip names, and a clip plays exactly one stream.
461///
462/// The path is always canonical ([`Source::new`]), so the same file reached by
463/// two paths is one source.
464#[derive(Clone, Debug, PartialEq, Eq)]
465pub struct Source {
466 pub path: PathBuf,
467 /// Position among the file's audio tracks in file order, the numbering
468 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
469 /// single track, and for a silent one.
470 pub audio_stream: usize,
471}
472
473impl Source {
474 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
475 Self {
476 path: canonical(path.as_ref()),
477 audio_stream,
478 }
479 }
480}
481
482/// What a lane carries, which is what a *gap* in it means: black frames on a
483/// video lane, silence on an audio one, nothing over the picture on a subtitle
484/// one.
485#[derive(Clone, Copy, PartialEq, Eq, Debug)]
486pub enum LaneKind {
487 Video,
488 Audio,
489 /// Words over the picture, placed and trimmed like everything else
490 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
491 /// so a caption is dragged, cut, rippled and undone by the machinery every
492 /// other clip already goes through.
493 ///
494 /// It carries no [`Clip`] at all, and that is what keeps the media paths
495 /// free of it: [`Project::lane`] hands back an empty slice, so every
496 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
497 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
498 /// check it already had, [`Project::composite_span_at`] and
499 /// [`Project::audio_lanes`] never look at it, and the three doors that
500 /// could still put a picture on one -- [`Project::from_parts`],
501 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
502 Subtitle,
503}
504
505/// Which lane an operation acts on: a kind plus a 0-based position among the
506/// lanes of that kind, so [`Lane::V1`] is the first video lane and
507/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
508///
509/// A handle, not the lane itself. It stays meaningful while lanes are added,
510/// and one naming a lane that is not there reads as an empty lane and refuses
511/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
512/// bounds check of its own.
513#[derive(Clone, Copy, PartialEq, Eq, Debug)]
514pub struct Lane {
515 pub kind: LaneKind,
516 pub ord: usize,
517}
518
519impl Lane {
520 /// The first video lane: what a decoder plays and what an export renders.
521 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
522 /// The first audio lane: what the audio worker plays.
523 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
524 /// The first subtitle lane -- the one a project has only once something
525 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
526 /// alone.
527 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
528
529 pub const fn new(kind: LaneKind, ord: usize) -> Self {
530 Self { kind, ord }
531 }
532
533 /// `V1`, `A2`: how a lane is written in a header column and named in an
534 /// error about it.
535 pub fn label(self) -> String {
536 let kind = match self.kind {
537 LaneKind::Video => 'V',
538 LaneKind::Audio => 'A',
539 LaneKind::Subtitle => 'S',
540 };
541 format!("{kind}{}", self.ord + 1)
542 }
543}
544
545/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
546/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
547/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
548/// frames. Never empty at either end.
549///
550/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
551/// actually has, and placed by the same one number: the window is in the
552/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
553/// placement is in timeline frames like everything else on a lane. So the lane
554/// invariant is the lane's ([`subs_sorted_disjoint`] is
555/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
556/// else, and only the two calls that change a *duration* -- a trim, and the
557/// mapping out -- ever need the timeline's rate.
558///
559/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
560/// paste and an undo snapshot are a plain assignment and can never dangle.
561#[derive(Clone, Copy, PartialEq, Eq, Debug)]
562pub struct SubClip {
563 /// Timeline frame its first frame is shown at.
564 pub start: u32,
565 /// How many timeline frames it covers; `>= 1`. Held rather than derived
566 /// from the window because a [`Project`] has no frame rate -- the rate
567 /// enters at the door of the two calls that need it -- and every placement
568 /// question (where it ends, what it overlaps) is asked in frames.
569 pub frames: u32,
570 /// Index into [`Project::subtitles`]: *which* track's words these are.
571 pub track: usize,
572 /// The half-open window of that track it shows, in microseconds from the
573 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
574 /// timed in, so no conversion stands between a cue and the window that
575 /// keeps it.
576 pub in_us: i64,
577 pub out_us: i64,
578 /// Group id: `Some` exactly when a hand put this caption in a group with
579 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
580 /// no group, and what a cut cuts apart loses the one it had
581 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
582 /// clip is what makes the caption move, trim and delete with it.
583 pub link: Option<u32>,
584}
585
586impl SubClip {
587 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
588 /// what every overlap question is asked of.
589 pub fn end(&self) -> u32 {
590 self.start + self.frames
591 }
592
593 /// How much of its track it shows, in microseconds; `>= 1` by the
594 /// never-empty invariant.
595 pub fn window_us(&self) -> i64 {
596 self.out_us - self.in_us
597 }
598
599 /// Where in its window the timeline frame `frame` falls, in microseconds --
600 /// the cut a split, a ripple and a trim all land on.
601 ///
602 /// By proportion and not by the timeline's rate: the window and the frame
603 /// count measure the same stretch of time, so the fraction of the frames
604 /// before `frame` is the fraction of the microseconds before it. That is
605 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
606 /// without either of them learning an fps.
607 fn window_at(&self, frame: u32) -> i64 {
608 let into = i64::from(frame.saturating_sub(self.start));
609 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
610 }
611}
612
613/// One lane: what it is and what it holds. A struct rather than a bare
614/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
615/// compositing mode, a name -- and it belongs next to the clips it applies to.
616#[derive(Clone, Debug)]
617struct LaneData {
618 kind: LaneKind,
619 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
620 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
621 /// ever seeing a subtitle: they all read this list.
622 clips: Vec<Clip>,
623 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
624 /// empty on a video or audio one. Beside the clips rather than an enum over
625 /// them so that everything a lane *is* -- its place in the stack, its
626 /// label, its undo snapshot, its removal -- stays one code path for all
627 /// three kinds.
628 subs: Vec<SubClip>,
629 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
630 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
631 /// makes it a different thing from a clip's equalizer: it moves everything
632 /// on the track by the same amount, cuts included. Meaningless on a video
633 /// lane, where it is kept at 0 and asked by nothing.
634 gain_db: f32,
635}
636
637impl LaneData {
638 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
639 Self {
640 kind,
641 clips,
642 subs: Vec::new(),
643 gain_db: 0.0,
644 }
645 }
646
647 /// The two lanes a project starts with: `V1` then `A1`, in display order.
648 /// One place, because a freshly opened file is exactly this pair.
649 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
650 vec![
651 LaneData::new(LaneKind::Video, video),
652 LaneData::new(LaneKind::Audio, audio),
653 ]
654 }
655}
656
657/// The placements one group id names, split by the two lists a lane holds:
658/// what a drag, a trim and a delete each have to walk, now that a group may
659/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
660/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
661/// -- so the pairs are `(lane storage index, index into that lane's list)`.
662#[derive(Default)]
663struct Members {
664 clips: Vec<(usize, usize)>,
665 subs: Vec<(usize, usize)>,
666}
667
668impl Members {
669 /// Whether the group is the one placement and no more: what a lift leaves
670 /// behind, and what every whole-group question answers "not one" for.
671 fn alone(&self) -> bool {
672 self.clips.len() + self.subs.len() < 2
673 }
674}
675
676/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
677#[derive(Clone, Copy, PartialEq, Eq, Debug)]
678pub enum Edge {
679 /// Its first timeline frame; moving it changes where in the source the clip
680 /// starts reading, so the picture behind the edge slides with it.
681 Start,
682 /// One past its last timeline frame; moving it only says how much of the
683 /// source to keep.
684 End,
685}
686
687/// What a lane holds over one stretch of the timeline: either a placed clip or
688/// a gap. Returned already trimmed to the position it was asked about, so a
689/// caller can hand `len` straight to a decoder (or to a black-frame generator).
690#[derive(Clone, Copy, PartialEq, Eq, Debug)]
691pub struct Span {
692 /// Timeline frame the span starts at.
693 pub start: u32,
694 /// Frames it covers; `>= 1`.
695 pub len: u32,
696 /// `(source index, first source frame)`, or `None` for a gap -- which the
697 /// engine renders as black frames and as silence.
698 pub from: Option<(usize, u32)>,
699 /// The rate the clip this came off plays at ([`Clip::speed`]);
700 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
701 /// timeline frames whatever it says -- the speed is how many *source* frames
702 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
703 /// come back to the timeline.
704 pub speed: Speed,
705}
706
707impl Span {
708 /// One past the last timeline frame it covers.
709 pub fn end(&self) -> u32 {
710 self.start + self.len
711 }
712
713 /// How many source frames it reads: what a decoder is asked for and how wide
714 /// an audio window is. `len` at real time, and the one arithmetic both the
715 /// picture and the sound go through, so they cannot disagree about where a
716 /// speeded clip ends.
717 pub fn source_len(&self) -> u32 {
718 match self.from {
719 // The last timeline frame's own source frame is the last one needed
720 // -- never one more, which at a slow rate would read a frame the
721 // next clip owns and at a fast one would decode a picture nothing
722 // shows.
723 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
724 None => self.len,
725 }
726 }
727
728 /// Where a source frame of this span lands on the timeline: the stamp
729 /// playback puts on a decoded frame, through the ceil half of the pair
730 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
731 /// frame, so a frame before it stamps at the span's start.
732 pub fn timeline_at(&self, source_frame: u32) -> u32 {
733 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
734 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
735 }
736}
737
738/// What one speeded audio segment asks of the worker: how many source frames to
739/// consume per output frame, and how many seconds of timeline it has to fill.
740/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
741/// resampling at all.
742#[derive(Clone, Copy, PartialEq, Debug)]
743pub struct Stretch {
744 /// Source frames per output frame -- the speed as a multiplier.
745 pub step: f64,
746 /// What the segment owes the timeline, which is what it is padded or
747 /// trimmed to.
748 pub timeline_secs: f64,
749}
750
751/// What a save writes and a load takes back: the sources, every lane in
752/// display order with its kind, and the equalizer and colour tables their clips
753/// index into -- [`Project::without_orphan_sources`] out,
754/// [`Project::from_parts`] in.
755pub type Parts = (
756 Vec<Source>,
757 Vec<(LaneKind, Vec<Clip>)>,
758 Vec<EqParams>,
759 Vec<ColorParams>,
760);
761
762/// How many undo steps a project keeps. One gesture is one step, so 100 is past
763/// any chain a person walks back by hand, and the oldest step is dropped rather
764/// than the history growing without end: a snapshot is the whole lane list, so
765/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
766/// that grows for as long as the session lasts.
767const HISTORY_CAP: usize = 100;
768
769/// The edit list plus its undo history.
770#[derive(Clone, Debug)]
771pub struct Project {
772 /// Append-only: never popped, never reordered. See the module docs.
773 sources: Vec<Source>,
774 /// In display order, which is the order [`Lane::ord`] counts in: the nth
775 /// lane of a kind here is that kind's `ord` n. Never empty.
776 lanes: Vec<LaneData>,
777 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
778 eq: Vec<EqParams>,
779 /// The same, for [`Clip::color`].
780 color: Vec<ColorParams>,
781 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
782 /// whole lane list, so adding a lane undoes as well. Bounded by
783 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
784 history: Vec<Vec<LaneData>>,
785 /// Never rolled back by an undo: an id retired by an undone split must not
786 /// come back and group two clips that were never together.
787 next_link: u32,
788 /// The subtitle tracks this timeline shows, in the order they were added.
789 /// Not in the lane list and not in the history snapshots, for the reason
790 /// the limiter is not: which subtitles a project carries is a setting on
791 /// it, and it is saved as a *reference* to the file the cues came out of
792 /// ([`crate::subtitle`]).
793 subtitles: Vec<SubtitleTrack>,
794 /// The master limiter every lane's sound is summed *through*
795 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
796 /// is what the history snapshots hold: it is a setting on the mix, like the
797 /// project's resolution is a setting on the picture, and neither is an undo
798 /// step.
799 limiter: Limiter,
800 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
801 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
802 /// the resolution, and not in the lane snapshots for the same reason.
803 tone: crate::tonemap::Preset,
804}
805
806impl Project {
807 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
808 /// grouped -- the state of a freshly opened video, where the timeline is the
809 /// source. `frame_count` of 0 would break the never-empty invariant, so it
810 /// is clamped to one frame.
811 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
812 let clip = Clip {
813 start: 0,
814 in_frame: 0,
815 out_frame: frame_count.max(1),
816 source: 0,
817 link: Some(0),
818 eq: None,
819 color: None,
820 fit: FitPolicy::default(),
821 speed: Speed::NORMAL,
822 };
823 Self {
824 // A file is opened on its first audio stream: nothing has picked
825 // one yet, and every file with audio at all has that one.
826 sources: vec![Source::new(path, 0)],
827 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
828 eq: Vec::new(),
829 color: Vec::new(),
830 history: Vec::new(),
831 next_link: 1,
832 subtitles: Vec::new(),
833 limiter: Limiter::default(),
834 tone: crate::tonemap::Preset::default(),
835 }
836 }
837
838 /// A project rebuilt from a saved edit list -- the load half of
839 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
840 /// an `ord` is a lane's position among the lanes of that kind, exactly as
841 /// [`Project::lanes`] hands them back. History is *not* saved, so
842 /// [`Project::undo`] is `false` until the first edit of the new session.
843 /// This is the one door untrusted parts come in through, so every invariant
844 /// every other constructor keeps is checked here, by name and in release:
845 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
846 /// or a colour) that is not there, a clip whose end overflows, a lane that is
847 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
848 /// below.
849 ///
850 /// A project whose lanes are all *empty* is not among them: an emptied
851 /// timeline is a project like any other -- it plays black and silent, it
852 /// saves, and it loads back. What a project cannot be is laneless, because
853 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
854 /// handle indexes into.
855 pub fn from_parts(
856 sources: Vec<Source>,
857 lanes: Vec<(LaneKind, Vec<Clip>)>,
858 eq: Vec<EqParams>,
859 color: Vec<ColorParams>,
860 ) -> crate::Result<Self> {
861 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
862 return Err(format!("eq {bad} holds a band that is not a finite number").into());
863 }
864 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
865 return Err(format!("color {bad} holds a value that is not a finite number").into());
866 }
867 if lanes.is_empty() {
868 return Err("no lanes at all: that is not a project".into());
869 }
870 let lanes: Vec<LaneData> = lanes
871 .into_iter()
872 .map(|(kind, clips)| LaneData::new(kind, clips))
873 .collect();
874 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
875 let name = lane.label();
876 // A subtitle lane carries words and never a picture
877 // ([`LaneKind::Subtitle`]); a file that puts one there names a
878 // source on a lane that has nothing to play it with, and every
879 // media path below would then read a clip off a lane it does not
880 // know about.
881 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
882 return Err(format!(
883 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
884 data.clips.len()
885 )
886 .into());
887 }
888 for c in &data.clips {
889 if c.out_frame <= c.in_frame {
890 return Err(format!(
891 "{name} clip at {} plays the empty range [{}, {})",
892 c.start, c.in_frame, c.out_frame
893 )
894 .into());
895 }
896 if c.source >= sources.len() {
897 return Err(format!(
898 "{name} clip at {} names source {} of {}",
899 c.start,
900 c.source,
901 sources.len()
902 )
903 .into());
904 }
905 if c.start.checked_add(c.frames()).is_none() {
906 return Err(format!(
907 "{name} clip at {} runs past the last frame there is",
908 c.start
909 )
910 .into());
911 }
912 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
913 return Err(format!(
914 "{name} clip at {} names eq {} of {}",
915 c.start,
916 c.eq.unwrap_or_default(),
917 eq.len()
918 )
919 .into());
920 }
921 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
922 return Err(format!(
923 "{name} clip at {} names color {} of {}",
924 c.start,
925 c.color.unwrap_or_default(),
926 color.len()
927 )
928 .into());
929 }
930 }
931 if !sorted_disjoint(&data.clips) {
932 return Err(format!("the {name} lane is out of order or overlaps itself").into());
933 }
934 }
935 links_are_consistent(&lanes)?;
936 // The counter sits past every id the file names, on either of a lane's
937 // lists: a v16 caption may carry the highest link there is, and a
938 // re-issued id would silently group it with the next placement that
939 // asks for one -- the loader refusing a save the editor just wrote.
940 let next_link = lanes
941 .iter()
942 .flat_map(|l| {
943 let clips = l.clips.iter().filter_map(|c| c.link);
944 let subs = l.subs.iter().filter_map(|s| s.link);
945 clips.chain(subs)
946 })
947 .max()
948 // Saturating so a crafted file cannot make the counter wrap: at the
949 // ceiling ids stop being fresh, which loses grouping, not memory.
950 .map_or(0, |m| m.saturating_add(1));
951 Ok(Self {
952 sources: sources
953 .iter()
954 .map(|s| Source::new(&s.path, s.audio_stream))
955 .collect(),
956 lanes,
957 eq,
958 color,
959 history: Vec::new(),
960 next_link,
961 subtitles: Vec::new(),
962 limiter: Limiter::default(),
963 tone: crate::tonemap::Preset::default(),
964 })
965 }
966
967 /// The first video lane -- what an export renders and what a single-lane
968 /// caller still means by "the clips".
969 pub fn clips(&self) -> &[Clip] {
970 self.lane(Lane::V1)
971 }
972
973 /// The clips of `lane`, or nothing at all for a lane that is not there.
974 pub fn lane(&self, lane: Lane) -> &[Clip] {
975 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
976 }
977
978 /// Every lane's handle, in display order -- what a walk over "all lanes"
979 /// iterates, and what a front-end lays out top to bottom.
980 pub fn lanes(&self) -> Vec<Lane> {
981 handles(&self.lanes)
982 }
983
984 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
985 /// for every `ord` below it, and none at or above it.
986 pub fn lane_count(&self, kind: LaneKind) -> usize {
987 self.lanes.iter().filter(|l| l.kind == kind).count()
988 }
989
990 /// Appends an empty lane of `kind` and hands back its handle. One undo
991 /// step, because the lane list is state a front-end shows: an added lane
992 /// that could not be taken back would be the one edit with no way out.
993 /// Nothing plays differently until something is placed on it.
994 ///
995 /// An empty lane is a lane like any other -- so is a whole project of them
996 /// ([`Project::from_parts`]); nothing plays until something is placed.
997 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
998 self.snapshot();
999 self.lanes.push(LaneData::new(kind, Vec::new()));
1000 Lane::new(kind, self.lane_count(kind) - 1)
1001 }
1002
1003 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1004 /// one undo step like it, which restores the lane where it stood.
1005 ///
1006 /// Refused, changing nothing, while the lane holds anything: the refusal
1007 /// names the clips (file and first frame), because a track removal that
1008 /// deleted takes with it would be the one edit nobody sees coming. Refused
1009 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1010 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1011 /// kind and *skips* a kind that is not there), so a project without one
1012 /// would swallow half of every file dropped on it, silently.
1013 ///
1014 /// The lanes below it move up one `ord`, so a handle a caller was holding
1015 /// (a selection, an open card) names the lane after it from here on -- the
1016 /// one thing a front-end owes this call.
1017 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1018 let Some(i) = self.index(lane) else {
1019 return Err(format!("there is no {} to remove", lane.label()).into());
1020 };
1021 // A subtitle lane is not in that rule: nothing lands on one by itself
1022 // -- a project starts without any and one is added when a caption is --
1023 // so the last of them comes off like any other empty track.
1024 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1025 return Err(format!(
1026 "{} is the only {} track: every import lands on it",
1027 lane.label(),
1028 match lane.kind {
1029 LaneKind::Video => "video",
1030 LaneKind::Audio => "audio",
1031 // Unreachable while the guard above lets the last subtitle
1032 // lane go, and its own word here so the sentence stays true
1033 // if that rule is ever relaxed.
1034 LaneKind::Subtitle => "subtitle",
1035 }
1036 )
1037 .into());
1038 }
1039 if !self.lanes[i].subs.is_empty() {
1040 // Three names and a count, exactly as the clips below get: the way
1041 // out of the refusal is the drag, so the words say so.
1042 let named: Vec<String> = self.lanes[i]
1043 .subs
1044 .iter()
1045 .take(3)
1046 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1047 .collect();
1048 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1049 0 => String::new(),
1050 n => format!(" and {n} more"),
1051 };
1052 return Err(format!(
1053 "{} still holds {}{rest}: delete those captions (or drag them to \
1054 another track) first",
1055 lane.label(),
1056 named.join(", ")
1057 )
1058 .into());
1059 }
1060 let clips = &self.lanes[i].clips;
1061 if !clips.is_empty() {
1062 // Three names and a count: a lane can hold forty clips and a
1063 // refusal nobody reads to the end says nothing at all.
1064 let named: Vec<String> = clips
1065 .iter()
1066 .take(3)
1067 .map(|c| {
1068 let name = self.sources.get(c.source).map_or_else(
1069 || format!("source {}", c.source),
1070 |s| s.path.display().to_string(),
1071 );
1072 format!("{name} at frame {}", c.start)
1073 })
1074 .collect();
1075 let rest = match clips.len().saturating_sub(named.len()) {
1076 0 => String::new(),
1077 n => format!(" and {n} more"),
1078 };
1079 return Err(format!(
1080 "{} still holds {}{rest}: delete those clips (or drag them to \
1081 another track) first",
1082 lane.label(),
1083 named.join(", ")
1084 )
1085 .into());
1086 }
1087 self.snapshot();
1088 self.lanes.remove(i);
1089 Ok(())
1090 }
1091
1092 /// Moves `lane` to display position `to` -- an index into
1093 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1094 /// the handle it answers to from now on. `None`, changing nothing and
1095 /// snapshotting nothing, for a lane that is not there, a position that is
1096 /// not, and a lane already standing in it.
1097 ///
1098 /// The whole track travels: its clips, its gain, its kind. Nothing is
1099 /// remapped, so no take changes lane and no group is broken -- this is the
1100 /// *order* of the lanes and nothing else, which is why one call is one undo
1101 /// step like an add or a removal.
1102 ///
1103 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1104 /// last video lane covering a frame, so moving one video lane past another
1105 /// changes which picture wins, in the preview and in an export alike. The
1106 /// audio lanes are summed and their sum does not care about order, so an
1107 /// audio track moved among the video ones is a rearrangement of the screen
1108 /// alone.
1109 ///
1110 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1111 /// position among the lanes of that kind), so a lane that crosses one of
1112 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1113 /// `V1`, clips and all -- while one that crosses only lanes of the other
1114 /// kind keeps its name. That is the returned handle: unchanged means every
1115 /// handle a caller holds still names the track it named before.
1116 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1117 let i = self.index(lane)?;
1118 if to >= self.lanes.len() || to == i {
1119 return None;
1120 }
1121 self.snapshot();
1122 let data = self.lanes.remove(i);
1123 self.lanes.insert(to, data);
1124 Some(handles(&self.lanes)[to])
1125 }
1126
1127 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1128 /// not there. The one place a handle becomes a position.
1129 fn index(&self, lane: Lane) -> Option<usize> {
1130 self.lanes
1131 .iter()
1132 .enumerate()
1133 .filter(|(_, l)| l.kind == lane.kind)
1134 .map(|(i, _)| i)
1135 .nth(lane.ord)
1136 }
1137
1138 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1139 let i = self.index(lane)?;
1140 Some(&mut self.lanes[i].clips)
1141 }
1142
1143 /// The files the clips index into, in import order; index 0 is the file the
1144 /// project was opened with.
1145 pub fn sources(&self) -> &[Source] {
1146 &self.sources
1147 }
1148
1149 /// The same list in the `(path, stream)` shape the audio engine indexes
1150 /// into -- [`crate::AudioSession::open_multi_streams`] and
1151 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1152 /// was placed with is the stream that plays *and* the stream that exports.
1153 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1154 self.sources
1155 .iter()
1156 .map(|s| (s.path.clone(), s.audio_stream))
1157 .collect()
1158 }
1159
1160 /// Index for `path` played on `audio_stream`, appending it if it is new.
1161 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1162 /// by two paths imports once and two streams of one file are two sources.
1163 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1164 /// no history: a source entry alone changes nothing playable.
1165 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1166 let source = Source::new(path, audio_stream);
1167 match self.sources.iter().position(|s| *s == source) {
1168 Some(idx) => idx,
1169 None => {
1170 self.sources.push(source);
1171 self.sources.len() - 1
1172 }
1173 }
1174 }
1175
1176 /// Append a whole-file clip of `source` to the end of every *media* lane,
1177 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1178 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1179 /// come in through [`Project::add_subtitles`], which is the palette.
1180 ///
1181 /// One history snapshot, so an import is one undo step, and undoing it
1182 /// leaves the (harmless) source entry behind, because indexes are forever.
1183 /// Refused for an unknown source index.
1184 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1185 if source >= self.sources.len() {
1186 return false;
1187 }
1188 self.snapshot();
1189 let start = self.timeline_frames();
1190 let clip = Clip {
1191 start,
1192 in_frame: 0,
1193 out_frame: frame_count.max(1),
1194 source,
1195 link: Some(self.new_link()),
1196 eq: None,
1197 color: None,
1198 fit: FitPolicy::default(),
1199 speed: Speed::NORMAL,
1200 };
1201 for data in self
1202 .lanes
1203 .iter_mut()
1204 .filter(|l| l.kind != LaneKind::Subtitle)
1205 {
1206 data.clips.push(clip);
1207 }
1208 true
1209 }
1210
1211 /// Drops a source entry -- the file a library row *is* -- and renumbers
1212 /// every clip that indexed past it, which is why this is more than a
1213 /// `Vec::remove`.
1214 ///
1215 /// Refused, changing nothing, while any clip still plays from it: the
1216 /// refusal names the lanes and how many clips each holds, so a caller can
1217 /// say what has to be deleted first. The *last* entry goes like any other
1218 /// -- a project may name no file at all, which is an empty library over an
1219 /// empty timeline (nothing can play, since a clip would have refused the
1220 /// removal). What a front-end does with that is its own decision: `edith`'s
1221 /// window goes back to the empty state it launches in, and
1222 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1223 /// refuses to write a project that names nothing, because no such file
1224 /// could be opened again.
1225 ///
1226 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1227 /// source index of its own -- a clipboard, which is the one thing outside
1228 /// this type that does -- has to fix it up or drop it, or a paste plays a
1229 /// different file. [`PlaybackSession::remove_source`] hands back the index
1230 /// that went for exactly that.
1231 ///
1232 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1233 /// snapshot older than the removal can name the very source being removed
1234 /// (delete a file's clips, then remove the file) and restoring it would
1235 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1236 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1237 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1238 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1239 /// exists) currently rules out.
1240 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1241 let Some(source) = self.sources.get(idx) else {
1242 return Err(format!("there is no source {idx} to remove").into());
1243 };
1244 let name = source.path.display().to_string();
1245 let used: Vec<String> = handles(&self.lanes)
1246 .into_iter()
1247 .zip(&self.lanes)
1248 .filter_map(
1249 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1250 0 => None,
1251 1 => Some(format!("{} (1 clip)", lane.label())),
1252 n => Some(format!("{} ({n} clips)", lane.label())),
1253 },
1254 )
1255 .collect();
1256 if !used.is_empty() {
1257 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1258 }
1259 self.sources.remove(idx);
1260 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1261 if c.source > idx {
1262 c.source -= 1;
1263 }
1264 }
1265 self.history.clear();
1266 Ok(())
1267 }
1268
1269 /// The sources a clip actually names, with the clips reindexed onto them
1270 /// -- what a save writes. Indexes are forever *inside* a session (see
1271 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1272 /// entry behind; writing that orphan to a project file would let a file
1273 /// nothing plays refuse a future load. New indexes are assigned in order of
1274 /// first use -- lane by lane, in display order -- so the same project always
1275 /// emits the same bytes.
1276 ///
1277 /// Every lane comes out, in display order and with its kind: that is what a
1278 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1279 /// takes back.
1280 ///
1281 /// The equalizer and colour tables are pruned the same way and for the same
1282 /// reason: an undone [`set_eq`](Project::set_eq) or
1283 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1284 /// and this is the one moment they can go -- the indexes that survive it are
1285 /// only the ones a clip names.
1286 ///
1287 /// One exception, and it is the emptied timeline's: a project no clip plays
1288 /// from still keeps its first source, if it has one. A file is what a
1289 /// reopened project scaffolds itself from -- the frame rate is written
1290 /// nowhere else -- so a save that pruned the last of them would write a
1291 /// project that cannot be loaded back at all.
1292 ///
1293 /// What comes out is *not* ordered by anything a reader may assume: first
1294 /// use, lane by lane, means the entry at index 0 can be a still or a song
1295 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1296 /// picks its rate and its audio reference by what a source *is*, never by
1297 /// where it sits.
1298 pub fn without_orphan_sources(&self) -> Parts {
1299 let mut moved = vec![None; self.sources.len()];
1300 let mut sources = Vec::new();
1301 let mut moved_eq = vec![None; self.eq.len()];
1302 let mut eq = Vec::new();
1303 let mut moved_color = vec![None; self.color.len()];
1304 let mut color = Vec::new();
1305 let mut lanes = self.lanes.clone();
1306 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1307 let old = c.source;
1308 c.source = match moved[old] {
1309 Some(new) => new,
1310 None => {
1311 sources.push(self.sources[old].clone());
1312 moved[old] = Some(sources.len() - 1);
1313 sources.len() - 1
1314 }
1315 };
1316 if let Some(old) = c.eq.map(usize::from) {
1317 c.eq = Some(match moved_eq[old] {
1318 Some(new) => new,
1319 None => {
1320 eq.push(self.eq[old].clone());
1321 let new = (eq.len() - 1) as u16;
1322 moved_eq[old] = Some(new);
1323 new
1324 }
1325 });
1326 }
1327 if let Some(old) = c.color.map(usize::from) {
1328 c.color = Some(match moved_color[old] {
1329 Some(new) => new,
1330 None => {
1331 color.push(self.color[old]);
1332 let new = (color.len() - 1) as u16;
1333 moved_color[old] = Some(new);
1334 new
1335 }
1336 });
1337 }
1338 }
1339 if sources.is_empty() {
1340 sources.extend(self.sources.first().cloned());
1341 }
1342 (
1343 sources,
1344 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1345 // comes out for one is an empty list, and its *place* in the display
1346 // order is what a save writes it for. What is on it travels beside
1347 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1348 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1349 eq,
1350 color,
1351 )
1352 }
1353
1354 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1355 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1356 /// track moves by it, which is what makes it a different control from a
1357 /// clip's equalizer (one frequency range of one take) and from the master
1358 /// volume (what this machine monitors at, which no file carries).
1359 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1360 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1361 }
1362
1363 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1364 /// One undo step like every other edit -- it is in the lane list, so an
1365 /// undo restores it with the rest. `false`, and no history, for a lane that
1366 /// is not there, for a value that is not finite, and for one already set.
1367 ///
1368 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1369 /// a value nobody reads: words have no loudness, so a slider that appeared
1370 /// to move one would be a control with no effect. (A video lane's gain is
1371 /// meaningless in the same way but is kept settable: it is the pair `A1`
1372 /// carries for a take, and mixing reads it off the audio lane alone.)
1373 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1374 let Some(i) = self.index(lane) else {
1375 return false;
1376 };
1377 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1378 return false;
1379 }
1380 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1381 if self.lanes[i].gain_db == db {
1382 return false;
1383 }
1384 self.snapshot();
1385 self.lanes[i].gain_db = db;
1386 true
1387 }
1388
1389 /// Every lane's volume in dB, in display order -- what a save writes,
1390 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1391 ///
1392 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1393 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1394 /// one): a save zips the two lists, so a lane that is in one and not the
1395 /// other would hand every track below it the volume of the track above.
1396 pub fn lane_gains(&self) -> Vec<f32> {
1397 self.lanes.iter().map(|l| l.gain_db).collect()
1398 }
1399
1400 /// What is placed on every lane, in display order and in step with
1401 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1402 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1403 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1404 ///
1405 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1406 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1407 /// clip's source there is no orphan to prune and no index to move.
1408 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1409 self.lanes.iter().map(|l| l.subs.clone()).collect()
1410 }
1411
1412 /// The placements a *load* puts back, one list per lane in display order --
1413 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1414 /// same reason. Called *after*
1415 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1416 /// names.
1417 ///
1418 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1419 /// like it, by name and in release, because it is the same untrusted file:
1420 /// a placement on a lane that is not a subtitle lane, an empty span or an
1421 /// empty window, a track the palette does not have, a span running past the
1422 /// last frame there is, and a lane that is out of order or overlaps itself
1423 /// ([`place_sub`] refuses every one of those on the live timeline).
1424 ///
1425 /// [`place_sub`]: Project::place_sub
1426 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1427 let names = handles(&self.lanes);
1428 let palette = self.subtitles.len();
1429 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1430 let name = lane.label();
1431 if list.is_empty() {
1432 continue;
1433 }
1434 if data.kind != LaneKind::Subtitle {
1435 return Err(format!(
1436 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1437 subtitle track",
1438 list.len()
1439 )
1440 .into());
1441 }
1442 for s in &list {
1443 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1444 return Err(format!(
1445 "{name} caption at {} is empty: {} frames of [{}, {})",
1446 s.start, s.frames, s.in_us, s.out_us
1447 )
1448 .into());
1449 }
1450 if s.track >= palette {
1451 return Err(format!(
1452 "{name} caption at {} names subtitle track {} of {palette}",
1453 s.start, s.track
1454 )
1455 .into());
1456 }
1457 if s.start.checked_add(s.frames).is_none() {
1458 return Err(format!(
1459 "{name} caption at {} runs past the last frame there is",
1460 s.start
1461 )
1462 .into());
1463 }
1464 }
1465 if !subs_sorted_disjoint(&list) {
1466 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1467 }
1468 data.subs = list;
1469 // The counter also has to clear the ids these captions carry: this
1470 // is the door a load's placements come through, *after*
1471 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1472 // a hand-grouped caption may carry the highest id in the file.
1473 self.next_link = self.next_link.max(
1474 data.subs
1475 .iter()
1476 .filter_map(|s| s.link)
1477 .max()
1478 .map_or(0, |m| m.saturating_add(1)),
1479 );
1480 }
1481 Ok(self)
1482 }
1483
1484 /// The mix settings a *load* puts back: lane volumes in display order (a
1485 /// short list leaves the rest at unity) and the master limiter, both
1486 /// clamped as their setters clamp them.
1487 ///
1488 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1489 /// setters push an undo step, and a project that arrives one undo away from
1490 /// a state it was never in is a project whose first ctrl+z is a surprise.
1491 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1492 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1493 if db.is_finite() {
1494 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1495 }
1496 }
1497 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1498 self
1499 }
1500
1501 /// The HDR rendition a *load* puts back -- the same door
1502 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1503 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1504 self.tone = preset;
1505 self
1506 }
1507
1508 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1509 /// project setting, not a clip's: one picture, one look
1510 /// ([`crate::tonemap::Preset`]).
1511 pub fn tone(&self) -> crate::tonemap::Preset {
1512 self.tone
1513 }
1514
1515 /// Sets it. `false` for the one already in force, which is what keeps a
1516 /// re-pick of the current rendition from costing a reseek.
1517 ///
1518 /// corner-cut: not an undo step, for the reason the limiter and the project
1519 /// resolution are not -- it is not in the lane list the history snapshots.
1520 /// Upgrade path is the same one: a history entry holding the project's own
1521 /// settings beside the lanes.
1522 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1523 if self.tone == preset {
1524 return false;
1525 }
1526 self.tone = preset;
1527 true
1528 }
1529
1530 /// The subtitle tracks a *load* puts back, in the order they were saved --
1531 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1532 /// the same reason.
1533 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1534 self.subtitles = tracks;
1535 self
1536 }
1537
1538 /// What this timeline shows over the picture, in the order they were added:
1539 /// what a front-end lists and what a save writes.
1540 pub fn subtitles(&self) -> &[SubtitleTrack] {
1541 &self.subtitles
1542 }
1543
1544 /// Adds a track, unless the very same one -- same file, same track number
1545 /// inside it -- is already on the list. `false` for that repeat: importing
1546 /// the same `.srt` twice is one subtitle track, not two identical ones.
1547 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1548 if self
1549 .subtitles
1550 .iter()
1551 .any(|t| t.path == track.path && t.track == track.track)
1552 {
1553 return false;
1554 }
1555 self.subtitles.push(track.clone());
1556 true
1557 }
1558
1559 /// Takes the track at `idx` off the list -- what a row's own remove goes
1560 /// through, so whatever an import added can be taken back out. Refused by
1561 /// name for a row this project does not have, rather than a silent no-op:
1562 /// a front-end holding a stale index has picked the wrong row and needs to
1563 /// hear it.
1564 ///
1565 /// Every index past `idx` moves down by one, as [`remove_source`](
1566 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1567 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1568 /// it, or it names a different track afterwards. The placements on the
1569 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1570 /// index into this very list, so every one past `idx` is walked down with
1571 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1572 /// for its clips, for its reason.
1573 ///
1574 /// Refused, changing nothing, while anything placed on a subtitle lane
1575 /// plays *this* row: the placement would have to be deleted or retargeted,
1576 /// and either one is an edit nobody asked for. The refusal names the lane
1577 /// and the frame it is at, up to three of them --
1578 /// [`remove_source`](Project::remove_source) refuses the same way for the
1579 /// same silent corruption.
1580 ///
1581 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1582 /// history snapshots hold the lane list and subtitles are not on it
1583 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1584 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1585 /// door, which reads the subtitles of a file and nothing else -- and not a
1586 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1587 /// entry holding the project's own settings beside the lanes. The history
1588 /// is *cleared* rather than kept, as a source removal clears it: the
1589 /// snapshots hold the indexes as they were before the reindex, so an undo
1590 /// into one would put every placement past `idx` on the wrong track.
1591 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1592 if idx >= self.subtitles.len() {
1593 return Err(format!("there is no subtitle track {idx} to remove").into());
1594 }
1595 let placed: Vec<String> = handles(&self.lanes)
1596 .into_iter()
1597 .zip(&self.lanes)
1598 .flat_map(|(lane, data)| {
1599 data.subs
1600 .iter()
1601 .filter(move |s| s.track == idx)
1602 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1603 })
1604 .take(3)
1605 .collect();
1606 if !placed.is_empty() {
1607 return Err(format!(
1608 "{} is on the timeline ({}): delete those clips first",
1609 self.track_name(idx),
1610 placed.join(", ")
1611 )
1612 .into());
1613 }
1614 self.subtitles.remove(idx);
1615 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1616 if s.track > idx {
1617 s.track -= 1;
1618 }
1619 }
1620 self.history.clear();
1621 Ok(())
1622 }
1623
1624 /// What a refusal calls a palette row: the name the panel shows, and the
1625 /// index alone for a row that is not there.
1626 fn track_name(&self, track: usize) -> String {
1627 self.subtitles
1628 .get(track)
1629 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1630 }
1631
1632 /// The subtitle lanes in display order -- what a front-end lays out and
1633 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1634 /// [`audio_lanes`](Project::audio_lanes).
1635 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1636 self.lanes()
1637 .into_iter()
1638 .filter(|l| l.kind == LaneKind::Subtitle)
1639 .collect()
1640 }
1641
1642 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1643 /// for a subtitle track, and empty for every other lane and for one that is
1644 /// not there.
1645 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1646 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1647 }
1648
1649 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1650 /// twin, with one deliberate difference: it **refuses** an overlap instead
1651 /// of overwriting what it lands on.
1652 ///
1653 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1654 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1655 /// carries is a *window of a track* and where the hand let go, and the
1656 /// second of those is the argument. So a caller builds the placement once
1657 /// (from the palette row it dragged) and drops it at as many frames as it
1658 /// likes without rewriting the field each time.
1659 ///
1660 /// A picture placed over a picture hides it and the hidden one is still
1661 /// there to drag back out; two captions in one frame are two lines nobody
1662 /// asked to stack, and the words that lost are gone from the screen with
1663 /// nothing to show for it. So the refusal names the placement in the way,
1664 /// and the caller picks another frame or another lane -- which is what a
1665 /// second subtitle lane is for.
1666 ///
1667 /// One undo step on success, and none on any refusal: an empty window or an
1668 /// empty span, a track the palette does not have
1669 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1670 /// subtitle lane, a span that would run past the last frame there is, and
1671 /// the overlap above.
1672 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1673 if lane.kind != LaneKind::Subtitle {
1674 return Err(format!(
1675 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1676 the others",
1677 lane.label()
1678 )
1679 .into());
1680 }
1681 let Some(i) = self.index(lane) else {
1682 return Err(format!("there is no {} to place on", lane.label()).into());
1683 };
1684 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1685 return Err(format!(
1686 "that placement is empty: {} frames of [{}, {})",
1687 sub.frames, sub.in_us, sub.out_us
1688 )
1689 .into());
1690 }
1691 if sub.track >= self.subtitles.len() {
1692 return Err(format!(
1693 "it names subtitle track {} of {}",
1694 sub.track,
1695 self.subtitles.len()
1696 )
1697 .into());
1698 }
1699 // The placement belongs to no group, for [`place`]'s reason: a caption
1700 // dragged out of the palette arrives alone, and grouping it with what
1701 // is under it is a hand's decision ([`Project::group_all`]).
1702 let sub = SubClip {
1703 start: at,
1704 link: None,
1705 ..sub
1706 };
1707 if at.checked_add(sub.frames).is_none() {
1708 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1709 }
1710 if let Some(other) = self.lanes[i]
1711 .subs
1712 .iter()
1713 .find(|o| o.end() > sub.start && o.start < sub.end())
1714 {
1715 return Err(format!(
1716 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1717 on another subtitle track",
1718 lane.label(),
1719 other.start,
1720 other.start,
1721 other.end()
1722 )
1723 .into());
1724 }
1725 self.snapshot();
1726 let subs = &mut self.lanes[i].subs;
1727 let idx = subs.partition_point(|o| o.start < sub.start);
1728 subs.insert(idx, sub);
1729 debug_assert!(subs_sorted_disjoint(subs));
1730 Ok(())
1731 }
1732
1733 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1734 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1735 /// refused an overlap where that one clamps to it, for
1736 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1737 /// still and no picture under it that a landing would hide, so "as far as
1738 /// it goes" would silently be a frame nobody named.
1739 ///
1740 /// A caption *in* a group drags the group: one delta for every member --
1741 /// its clips and its other captions -- clamped to the room each of them
1742 /// has, exactly as a clip's drag always has. That is the point of putting
1743 /// a caption in a group: the words go where the picture goes.
1744 ///
1745 /// The window travels untouched: a caption dragged later says the same
1746 /// words later, exactly as a clip dragged later plays the same pictures
1747 /// later.
1748 ///
1749 /// One undo step on success; nothing changed and no step on a refusal --
1750 /// an index that is not there, a lane that is not a subtitle lane or is not
1751 /// there, and (for a caption in no group) an overlap. A drop that changes
1752 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1753 /// up and put it back has done nothing wrong, and a front-end showing every
1754 /// `Err` would say so.
1755 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1756 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1757 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1758 };
1759 if to.kind != LaneKind::Subtitle {
1760 return Err(format!(
1761 "{} is not a subtitle track: a caption cannot play on it",
1762 to.label()
1763 )
1764 .into());
1765 }
1766 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1767 return Err(format!("there is no {} to move onto", to.label()).into());
1768 };
1769 if (here, start) == (dest, sub.start) {
1770 // A pick-up-put-back: the drag ended where it began, which is not a
1771 // mistake to name -- `Ok`, and no undo step, because nothing
1772 // changed. A refusal here would toast a hand that did nothing.
1773 return Ok(());
1774 }
1775 if start.checked_add(sub.frames).is_none() {
1776 return Err(
1777 format!("a placement at frame {start} runs past the last frame there is").into(),
1778 );
1779 }
1780 // A grouped caption carries its group, clamped to the room the whole
1781 // group has rather than refused ([`Project::move_room]) -- one drag, one
1782 // delta, one undo step.
1783 let members = self.group_of(from, idx).expect("the subtitle was found");
1784 if !members.alone() {
1785 if members
1786 .subs
1787 .iter()
1788 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1789 {
1790 return Err(format!(
1791 "a group is one caption per track: {} already carries this group",
1792 to.label()
1793 )
1794 .into());
1795 }
1796 let want = i64::from(start) - i64::from(sub.start);
1797 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1798 return Err(format!(
1799 "another placement already covers those frames on {}",
1800 to.label()
1801 )
1802 .into());
1803 };
1804 let delta = want.clamp(lo, hi);
1805 self.snapshot();
1806 for &(l, i) in &members.clips {
1807 let c = &mut self.lanes[l].clips[i];
1808 c.start = (i64::from(c.start) + delta) as u32;
1809 }
1810 for &(l, i) in &members.subs {
1811 let s = &mut self.lanes[l].subs[i];
1812 s.start = (i64::from(s.start) + delta) as u32;
1813 }
1814 let moved = self.lanes[here].subs.remove(idx);
1815 let subs = &mut self.lanes[dest].subs;
1816 let at = subs.partition_point(|o| o.start < moved.start);
1817 subs.insert(at, moved);
1818 debug_assert!(subs_sorted_disjoint(subs));
1819 debug_assert!(members
1820 .clips
1821 .iter()
1822 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1823 return Ok(());
1824 }
1825 let moved = SubClip { start, ..sub };
1826 if let Some(other) = self.lanes[dest]
1827 .subs
1828 .iter()
1829 .enumerate()
1830 .find(|&(j, o)| {
1831 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
1832 })
1833 .map(|(_, o)| *o)
1834 {
1835 return Err(format!(
1836 "the {} subtitle at frame {} already covers [{}, {})",
1837 to.label(),
1838 other.start,
1839 other.start,
1840 other.end()
1841 )
1842 .into());
1843 }
1844 self.snapshot();
1845 self.lanes[here].subs.remove(idx);
1846 let subs = &mut self.lanes[dest].subs;
1847 let at = subs.partition_point(|o| o.start < moved.start);
1848 subs.insert(at, moved);
1849 debug_assert!(subs_sorted_disjoint(subs));
1850 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
1851 Ok(())
1852 }
1853
1854 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
1855 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
1856 /// pulling an edge past what is legal means "as far as it goes".
1857 ///
1858 /// The window follows the edge, in the seconds the frames are worth at
1859 /// `fps`: a head pulled in starts the caption later *in its track* (the
1860 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
1861 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
1862 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
1863 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
1864 /// needed here and nowhere else in this file, because a trim is the only
1865 /// edit that changes a *duration*.
1866 ///
1867 /// The walls: one frame always survives, an edge never crosses the
1868 /// neighbouring subtitle on its own lane, a head never walks back past the
1869 /// track's own start (`in_us` of 0), and a tail never runs past the last
1870 /// cue the track has -- which is the source length a media trim needs a
1871 /// caller's table for, and which this one can simply read.
1872 ///
1873 /// `Err`, with nothing changed and no undo step, for an index that is not
1874 /// there and an unusable `fps`. An edge that ends up where it already was
1875 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
1876 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
1877 /// reason: a drag that stops at a wall is not a mistake to report.
1878 pub fn trim_sub(
1879 &mut self,
1880 lane: Lane,
1881 idx: usize,
1882 edge: Edge,
1883 to: u32,
1884 fps: f64,
1885 ) -> crate::Result<()> {
1886 if !(fps.is_finite() && fps > 0.0) {
1887 return Err(format!("{fps} is not a frame rate to trim against").into());
1888 }
1889 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
1890 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
1891 };
1892 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
1893 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
1894 };
1895 let to = to.clamp(lo, hi);
1896 let at = match edge {
1897 Edge::Start => sub.start,
1898 Edge::End => sub.end(),
1899 };
1900 if to == at {
1901 // The edge is where it was asked to go -- either the hand did not
1902 // move it, or the clamp above stopped it at a wall it was already
1903 // standing against. Both are a drag that changed nothing: `Ok`, no
1904 // undo step, and no toast for a box that simply stopped moving.
1905 return Ok(());
1906 }
1907 self.snapshot();
1908 let members = self.group_of(lane, idx).expect("the subtitle was found");
1909 let i = self.index(lane).expect("the subtitle was found on it");
1910 let s = &mut self.lanes[i].subs[idx];
1911 match edge {
1912 // The words that stay are the words that were there, so the window
1913 // moves with the head -- a trim, not a slip.
1914 Edge::Start => {
1915 // Clamped to a window that is still a window: the walls above
1916 // are frames and the rounding between the two clocks is not
1917 // exact, and neither is a caller's hand-built placement.
1918 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
1919 .clamp(0, s.out_us - 1);
1920 s.frames = s.end() - to;
1921 s.start = to;
1922 }
1923 Edge::End => {
1924 s.out_us =
1925 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
1926 s.frames = to - s.start;
1927 }
1928 }
1929 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
1930 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
1931 // A caption in a group drags its group's edge with it, exactly as a
1932 // clip's trim does: one delta, each member clamped to its own room.
1933 // No source table to grow by, which only tightens how far a member may
1934 // follow -- never whether it may.
1935 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
1936 Ok(())
1937 }
1938
1939 /// How far that edge may travel, `(first, last)` timeline frame inclusive
1940 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
1941 /// drawing the box during a drag asks. `None` for an index that is not
1942 /// there.
1943 pub fn trim_sub_room(
1944 &self,
1945 lane: Lane,
1946 idx: usize,
1947 edge: Edge,
1948 fps: f64,
1949 ) -> Option<(u32, u32)> {
1950 let subs = self.sub_lane(lane);
1951 let s = *subs.get(idx)?;
1952 // How many timeline frames a stretch of the track is worth, which is
1953 // what turns its two walls -- its own start, and its last cue -- into
1954 // frames. A rate that is not a rate leaves the window where it is.
1955 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
1956 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
1957 false => 0,
1958 };
1959 Some(match edge {
1960 Edge::Start => (
1961 s.start
1962 .saturating_sub(frames_of(s.in_us))
1963 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
1964 s.end() - 1,
1965 ),
1966 Edge::End => {
1967 // Out to the end of the track it reads, and never over the
1968 // subtitle behind it. A track the palette no longer has (or one
1969 // with no cues at all) may not grow, exactly as a source with no
1970 // entry in a media trim's table may not.
1971 let track_end = self
1972 .subtitles
1973 .get(s.track)
1974 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
1975 .unwrap_or(s.out_us);
1976 (
1977 s.start + 1,
1978 s.start
1979 .saturating_add(frames_of(track_end - s.in_us).max(1))
1980 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
1981 )
1982 }
1983 })
1984 }
1985
1986 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
1987 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
1988 /// `false` for an index that is not there (which a lane that is not a
1989 /// subtitle lane always is).
1990 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
1991 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
1992 return false;
1993 };
1994 self.snapshot();
1995 self.lanes[i].subs.remove(idx);
1996 true
1997 }
1998
1999 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2000 /// window of its track, clipped to that window and shifted to where the
2001 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2002 /// carried through the picture's spans -- this is its twin for a track that
2003 /// is placed on a lane of its own, and it is what a preview draws and what
2004 /// an export of the lane would write.
2005 ///
2006 /// Cut, not stretched: a cue half inside the window keeps the half that is
2007 /// inside, and a cue wholly outside it is gone -- the same rule the media
2008 /// spans follow. `fps` is the timeline's rate, needed here because a
2009 /// placement's *position* is in frames while its words are in microseconds.
2010 ///
2011 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2012 /// of their cues, no file opened), which is how a front-end asks it.
2013 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2014 if !(fps.is_finite() && fps > 0.0) {
2015 return Vec::new();
2016 }
2017 let mut out = Vec::new();
2018 for s in self.sub_lane(lane) {
2019 let Some(track) = self.subtitles.get(s.track) else {
2020 // A placement whose track was taken off the palette
2021 // ([`Project::remove_subtitles`]) shows nothing rather than
2022 // showing another track's words.
2023 continue;
2024 };
2025 // Where the placement's own first microsecond lands on the
2026 // timeline, and how many microseconds of timeline one microsecond
2027 // of the window is worth: the placement's own proportion, which a
2028 // group's re-rate changes (the frames compress, the window does
2029 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2030 // every cue lands where it always did; at 2x the words cross the
2031 // screen in half the time, cue for cue.
2032 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2033 let onto = |t: i64| {
2034 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2035 };
2036 for cue in &track.cues {
2037 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2038 if b <= a {
2039 continue; // wholly outside the window this placement keeps
2040 }
2041 out.push(SubtitleCue {
2042 start_us: onto(a),
2043 end_us: onto(b),
2044 text: cue.text.clone(),
2045 image: cue.image.clone(),
2046 });
2047 }
2048 }
2049 // The placements come in timeline order, but two lanes' worth (or a
2050 // track whose cues a window reordered) do not.
2051 out.sort_by_key(|cue| cue.start_us);
2052 out
2053 }
2054
2055 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2056 /// lanes is multiplied by on its way into the mix: the same lanes in the
2057 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2058 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2059 /// the bit-exact path.
2060 pub fn audio_gains(&self) -> Vec<f32> {
2061 self.audio_lanes()
2062 .into_iter()
2063 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2064 .collect()
2065 }
2066
2067 /// The master limiter the mix is summed through. A project setting, not a
2068 /// clip's and not a lane's: there is one mix.
2069 pub fn limiter(&self) -> Limiter {
2070 self.limiter
2071 }
2072
2073 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2074 /// for a setting already in force.
2075 ///
2076 /// corner-cut: not an undo step, for the reason the project resolution is not
2077 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2078 /// lane list the history snapshots. Upgrade path is a history entry that
2079 /// holds the mix settings beside the lanes.
2080 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2081 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2082 if self.limiter == limiter {
2083 return false;
2084 }
2085 self.limiter = limiter;
2086 true
2087 }
2088
2089 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2090 /// plays flat (and for an index that is not there) -- what a feeder and an
2091 /// export ask before they build an [`crate::eq::EqState`].
2092 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2093 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2094 }
2095
2096 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2097 /// take them off. One undo step, like every other edit. `false` -- and no
2098 /// history -- for an index that is not there and for params holding a value
2099 /// that is not finite, which is the one thing the file format could not
2100 /// write and read back.
2101 ///
2102 /// Settings equal to ones already in the table share their entry, so a
2103 /// project that puts the same curve on twenty clips writes it once.
2104 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2105 if idx >= self.lane(lane).len() {
2106 return false;
2107 }
2108 let slot = match params {
2109 None => None,
2110 Some(params) => {
2111 if !finite(&params) {
2112 return false;
2113 }
2114 Some(match self.eq.iter().position(|p| *p == params) {
2115 Some(at) => at as u16,
2116 // corner-cut: the table is append-only within a session (see
2117 // the module docs) and `Clip::eq` is a u16, so the 65535th
2118 // *distinct* setting of one session is refused rather than
2119 // silently aliased. Upgrade path if a UI ever drags a slider
2120 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2121 // snapshot the table into the history and compact it here.
2122 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2123 None => {
2124 self.eq.push(params);
2125 (self.eq.len() - 1) as u16
2126 }
2127 })
2128 }
2129 };
2130 self.snapshot();
2131 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2132 true
2133 }
2134
2135 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2136 /// ungraded (and for an index that is not there) -- what the renderer and
2137 /// the export ask before they call [`crate::color::apply_yuv`].
2138 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2139 self.color
2140 .get(usize::from(self.lane(lane).get(idx)?.color?))
2141 }
2142
2143 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2144 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2145 /// (and no history) for an index that is not there or a value that is not
2146 /// finite, and equal settings share a table entry.
2147 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2148 self.write_color(lane, idx, params, true)
2149 }
2150
2151 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2152 /// one pointer drag, whose first write (a plain `set_color`) already took the
2153 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2154 /// not one per pixel -- and undoing it lands where the hand picked it up.
2155 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2156 self.write_color(lane, idx, params, false)
2157 }
2158
2159 fn write_color(
2160 &mut self,
2161 lane: Lane,
2162 idx: usize,
2163 params: Option<ColorParams>,
2164 snapshot: bool,
2165 ) -> bool {
2166 if idx >= self.lane(lane).len() {
2167 return false;
2168 }
2169 let slot = match params {
2170 None => None,
2171 Some(params) => {
2172 if !color_finite(&params) {
2173 return false;
2174 }
2175 Some(match self.color.iter().position(|p| *p == params) {
2176 Some(at) => at as u16,
2177 // corner-cut: the 65535th *distinct* grade of one session is
2178 // refused rather than silently aliased, exactly as `set_eq`
2179 // refuses the 65535th curve; same upgrade path.
2180 None if self.color.len() >= usize::from(u16::MAX) => return false,
2181 None => {
2182 self.color.push(params);
2183 (self.color.len() - 1) as u16
2184 }
2185 })
2186 }
2187 };
2188 if snapshot {
2189 self.snapshot();
2190 }
2191 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2192 true
2193 }
2194
2195 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2196 /// index that is not there, which is what every clip starts at anyway.
2197 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2198 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2199 }
2200
2201 /// Sets it, for the clip **and its whole group**: a link is one span on
2202 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2203 /// from its sound would be a group no save could load. One snapshot, so the
2204 /// group's change is one [`Project::undo`].
2205 ///
2206 /// The source range is untouched -- a speed says how many timeline frames
2207 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2208 /// split still address the file afterwards.
2209 ///
2210 /// Refused, changing nothing and costing no undo step, when the clip would
2211 /// grow into the one after it on its own lane: slowing a clip down makes it
2212 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2213 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2214 /// something a user can go and fix. Also for an index that is not there.
2215 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2216 self.write_speed(lane, idx, speed, true)
2217 }
2218
2219 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2220 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2221 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2222 /// not one per rate it passed through -- exactly as
2223 /// [`set_color_live`](Self::set_color_live) is for a slider.
2224 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2225 self.write_speed(lane, idx, speed, false)
2226 }
2227
2228 fn write_speed(
2229 &mut self,
2230 lane: Lane,
2231 idx: usize,
2232 speed: Speed,
2233 snapshot: bool,
2234 ) -> crate::Result<()> {
2235 let Some(members) = self.group_of(lane, idx) else {
2236 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2237 };
2238 let labels = handles(&self.lanes);
2239 // The clip the hand is holding is the group's clock: everything else
2240 // in the group, caption members included, re-times by the ratio its new
2241 // rate gives its own frames. The clips take the rate itself; a caption
2242 // has none, so it takes the *ratio* -- its span on the timeline
2243 // compresses or stretches about the held clip's head, while the words
2244 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2245 // timeline moves, the track does not).
2246 let Some(held) = self.lane(lane).get(idx).copied() else {
2247 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2248 };
2249 // The same per-member piece `speeded_playhead` builds for this op,
2250 // asked here instead of read there -- a caption's length comes from
2251 // the map's own ends (`end - start`), never `round(len * ratio)`
2252 // separately, which is what let the two answers drift apart by a
2253 // frame.
2254 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2255 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2256 let retimed = |s: SubClip| {
2257 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2258 let start = map.apply(s.start);
2259 let end = map.apply(s.end()).max(start.saturating_add(1));
2260 SubClip { start, frames: end - start, ..s }
2261 };
2262 for &(l, i) in &members.clips {
2263 let clips = &self.lanes[l].clips;
2264 let mut moved = clips[i];
2265 moved.speed = speed;
2266 if let Some(next) = clips.get(i + 1)
2267 && moved.end() > next.start
2268 {
2269 let name = labels[l].label();
2270 return Err(format!(
2271 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2272 move it along, or trim this one first",
2273 moved.end(),
2274 next.start
2275 )
2276 .into());
2277 }
2278 }
2279 // ...and the captions, against their own lanes' captions: a stretch
2280 // that runs one into its neighbour is refused for the clip arm's
2281 // reason -- a lane may not overlap itself -- and by name like it.
2282 let subs: Vec<(usize, usize, SubClip)> = members
2283 .subs
2284 .iter()
2285 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2286 .collect();
2287 for &(l, i, moved) in &subs {
2288 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2289 if j != i && moved.start < other.end() && other.start < moved.end() {
2290 return Err(format!(
2291 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2292 starts at {}: move it along, or trim this one first",
2293 labels[l].label(),
2294 self.lanes[l].subs[i].start,
2295 moved.end(),
2296 other.start
2297 )
2298 .into());
2299 }
2300 }
2301 }
2302 if snapshot {
2303 self.snapshot();
2304 }
2305 for (l, i) in members.clips {
2306 self.lanes[l].clips[i].speed = speed;
2307 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2308 }
2309 for (l, i, moved) in subs {
2310 self.lanes[l].subs[i] = moved;
2311 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2312 }
2313 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2314 Ok(())
2315 }
2316
2317 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2318 /// playhead standing at `at` -- read off the geometry **before** the
2319 /// write, because the old ends are gone after it. The question a card
2320 /// asks as its bar moves: the picture under the cursor has to stay the
2321 /// picture under the cursor, or the scene changes with the rate.
2322 ///
2323 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2324 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2325 /// a clip member keeps its own start and re-fits its length at the new
2326 /// rate -- its **old** rate against the new one, which is what the bar's
2327 /// live samples ask about as much as a first press does; a caption
2328 /// member scales about the held clip's start by the held clip's own
2329 /// proportion; and a playhead outside every member's old extent stays
2330 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2331 /// (or the room a stretch takes) absorbs the difference, not the
2332 /// playhead. `None` for an index that is not there.
2333 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2334 let members = self.group_of(lane, idx)?;
2335 let held = self.lane(lane).get(idx).copied()?;
2336 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2337 for &(l, i) in members.clips.iter().chain(&members.subs) {
2338 let (span, map) = match self
2339 .lanes[l]
2340 .clips
2341 .get(i)
2342 .filter(|_| members.clips.contains(&(l, i)))
2343 {
2344 // The clip's own span, re-fitted at its own old rate: one
2345 // piece of the map, anchored where the clip itself is. The
2346 // new length is the same *source* frames at the new rate --
2347 // len divided by it, never multiplied.
2348 Some(c) => (
2349 (c.start, c.start + c.frames()),
2350 TimelineMap::piece(
2351 (c.start, c.start + c.frames()),
2352 (
2353 c.start,
2354 c.start + (c.len() as f64 / new).round() as u32,
2355 ),
2356 ),
2357 ),
2358 // The caption's span, scaled about the held clip's head by
2359 // the held clip's proportion -- the offset the group keeps.
2360 None => {
2361 let s = self.lanes[l].subs.get(i)?;
2362 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2363 (
2364 (s.start, s.end()),
2365 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2366 )
2367 }
2368 };
2369 // The piece owns only its own old span: outside it the playhead
2370 // is another member's question, or nobody's.
2371 if (span.0..span.1).contains(&at) {
2372 return Some(map.apply(at));
2373 }
2374 }
2375 Some(at)
2376 }
2377
2378 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2379 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2380 /// every clip starts at anyway.
2381 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2382 self.lane(lane)
2383 .get(idx)
2384 .map_or(FitPolicy::default(), |c| c.fit)
2385 }
2386
2387 /// Sets it. One undo step like every other edit, and `false` (with no
2388 /// history) for an index that is not there. Unlike an eq or a grade there is
2389 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2390 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2391 if idx >= self.lane(lane).len() {
2392 return false;
2393 }
2394 self.snapshot();
2395 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2396 true
2397 }
2398
2399 /// Every frame number on every lane rewritten onto a timeline counted at
2400 /// another rate: `k` is old timeline frames per new one, `counts` is how
2401 /// long each source is on the *new* timeline (indexed as
2402 /// [`Project::sources`] is), and the edit survives as the same seconds of
2403 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2404 /// the edit list, and the only thing that touches the frame numbers without
2405 /// being an edit anyone made.
2406 ///
2407 /// Every position -- a clip's start and its end alike -- goes through the
2408 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2409 /// stays a gap, and a take's picture and its sound land on the same frame on
2410 /// their two lanes: no lane can drift against another. A clip is then only
2411 /// ever made to *fit* the room its own start and end mapped to, never to
2412 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2413 /// below is the backstop for the one case that could: a slow clip so short
2414 /// that no source range fits its new room at all).
2415 ///
2416 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2417 /// onto the new grid, so a rate picked, unpicked and picked again is within
2418 /// a frame of where it started rather than back at it. Upgrade path is
2419 /// keeping the edit list at one reference rate and conforming on the way
2420 /// out, which every frame number in this module would then be measured in.
2421 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2422 for lane in &mut self.lanes {
2423 let mut cursor = 0;
2424 for clip in &mut lane.clips {
2425 let start = k.timeline_at(clip.start).max(cursor);
2426 // The room its own end mapped to -- never zero, since a clip is
2427 // never empty even on a grid too coarse to hold it.
2428 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2429 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2430 // Its footage, held inside the file's new length: a clip whose
2431 // out-point was the last frame of its source must not come out
2432 // of this naming a frame past the end -- that is a project that
2433 // would not open again ([`crate::PlaybackSession::open_project`]
2434 // refuses one by name).
2435 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2436 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2437 clip.start = start;
2438 clip.in_frame = in_frame;
2439 clip.out_frame = in_frame + len;
2440 cursor = clip.end();
2441 }
2442 // A subtitle's *window* is in microseconds and a rate change moves
2443 // no seconds, so only where it sits is remapped -- through the same
2444 // [`Rate::timeline_at`] every clip boundary goes through, so a
2445 // caption still starts on the frame its picture does.
2446 let mut cursor = 0;
2447 for sub in &mut lane.subs {
2448 let start = k.timeline_at(sub.start).max(cursor);
2449 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2450 sub.start = start;
2451 cursor = sub.end();
2452 }
2453 }
2454 }
2455
2456 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2457 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2458 ///
2459 /// A subtitle lane counts like any other: a caption placed past the last
2460 /// picture holds the timeline open under it, exactly as an `A2` running
2461 /// past `V1` does, rather than being silently clipped away by the length
2462 /// ([`crate::export::timeline_cues`] clips cues to this).
2463 pub fn timeline_frames(&self) -> u32 {
2464 self.lanes
2465 .iter()
2466 .filter_map(|l| match l.kind {
2467 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2468 _ => l.clips.last().map(Clip::end),
2469 })
2470 .max()
2471 .unwrap_or(0)
2472 }
2473
2474 /// The same, counting the *media* alone: where the last picture or sound
2475 /// runs out, with the captions over them ignored.
2476 ///
2477 /// What an export actually writes ends here -- the picture loop walks the
2478 /// composite spans and the file stops with them -- so this is the length a
2479 /// cue has to be inside of to be written at all (what
2480 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2481 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2482 /// thing is a picture or a sound, which is every timeline that has no
2483 /// caption hanging past the end of both.
2484 pub fn media_frames(&self) -> u32 {
2485 self.lanes
2486 .iter()
2487 .filter(|l| l.kind != LaneKind::Subtitle)
2488 .filter_map(|l| l.clips.last().map(Clip::end))
2489 .max()
2490 .unwrap_or(0)
2491 }
2492
2493 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2494 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2495 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2496 self.lane_spans(Lane::V1)
2497 }
2498
2499 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2500 // Timeline frames, not source ones: a box on a lane is as wide as the
2501 // clip is long *there*, which a speed halves or quadruples.
2502 self.lane(lane)
2503 .iter()
2504 .map(|c| (c.start, c.frames()))
2505 .collect()
2506 }
2507
2508 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2509 /// and past the end -- [`Project::span_at`] is the version that tells those
2510 /// two apart.
2511 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2512 let clips = self.lane(lane);
2513 let idx = at(clips, timeline_frame)?;
2514 Some((idx, source_frame(&clips[idx], timeline_frame)))
2515 }
2516
2517 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2518 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2519 self.map(Lane::V1, timeline_frame)
2520 }
2521
2522 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2523 /// it, or the gap running to the next clip (or to the end of the timeline,
2524 /// which is where a lane shorter than its neighbour keeps showing black).
2525 /// `None` at or past the end of the timeline, which is the only "nothing
2526 /// left" there is.
2527 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2528 let total = self.timeline_frames();
2529 if timeline_frame >= total {
2530 return None;
2531 }
2532 let clips = self.lane(lane);
2533 Some(match at(clips, timeline_frame) {
2534 Some(idx) => Span {
2535 start: timeline_frame,
2536 len: clips[idx].end() - timeline_frame,
2537 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2538 speed: clips[idx].speed,
2539 },
2540 None => Span {
2541 start: timeline_frame,
2542 speed: Speed::NORMAL,
2543 // The next placement, or the end of the timeline: a gap is
2544 // bounded by what comes after it, never by its own bookkeeping.
2545 len: clips
2546 .iter()
2547 .find(|c| c.start > timeline_frame)
2548 .map_or(total, |c| c.start)
2549 - timeline_frame,
2550 from: None,
2551 },
2552 })
2553 }
2554
2555 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2556 /// gaps included -- the whole play list, which is what an export walks.
2557 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2558 let mut out = Vec::new();
2559 let mut t = timeline_frame;
2560 while let Some(span) = self.span_at(lane, t) {
2561 t = span.end();
2562 out.push(span);
2563 }
2564 out
2565 }
2566
2567 /// What the *composite* shows from `timeline_frame` on -- the answer
2568 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2569 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2570 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2571 /// (the usual overlay convention). A frame no video lane covers is a gap,
2572 /// which is black however many lanes are above or below it.
2573 ///
2574 /// No blending, so exactly one lane is visible at a time and the composite
2575 /// is itself a span list -- which is why one decoder plays it, the same one
2576 /// a single-lane timeline uses, rather than N running at once.
2577 ///
2578 /// The span is cut short wherever a *higher* lane's clip starts, because
2579 /// from that frame on a different lane wins; that is what makes walking
2580 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2581 ///
2582 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2583 /// lanes would then be visible in one frame and the caller needs a decoder
2584 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2585 /// (this same walk, per lane) feeding N decoders.
2586 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2587 let total = self.timeline_frames();
2588 if timeline_frame >= total {
2589 return None;
2590 }
2591 let video = self.video_lanes();
2592 // The last covering lane is the winner; only the lanes above it can
2593 // interrupt what it shows.
2594 let winner = video
2595 .iter()
2596 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2597 let (from, speed, until) = match winner {
2598 Some(i) => {
2599 let clips = self.lane(video[i]);
2600 let idx = at(clips, timeline_frame).expect("just found above");
2601 (
2602 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2603 clips[idx].speed,
2604 clips[idx].end(),
2605 )
2606 }
2607 // Nothing covers it: black until something above the floor starts.
2608 None => (None, Speed::NORMAL, total),
2609 };
2610 let takeover = video[winner.map_or(0, |i| i + 1)..]
2611 .iter()
2612 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
2613 .map(|c| c.start)
2614 .min();
2615 Some(Span {
2616 start: timeline_frame,
2617 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
2618 from,
2619 speed,
2620 })
2621 }
2622
2623 /// The video lanes in display order, topmost last -- the order the composite
2624 /// rule counts in.
2625 fn video_lanes(&self) -> Vec<Lane> {
2626 self.lanes()
2627 .into_iter()
2628 .filter(|l| l.kind == LaneKind::Video)
2629 .collect()
2630 }
2631
2632 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
2633 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
2634 /// index on that lane. `None` over a gap and past the end. What a front-end
2635 /// asks to act on "the clip on screen" without re-deriving the rule.
2636 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
2637 let video = self.video_lanes();
2638 let winner = video
2639 .iter()
2640 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
2641 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
2642 }
2643
2644 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
2645 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
2646 /// answers "the clip on screen"; this answers it per lane, which is what
2647 /// walking the lanes for something to select needs.
2648 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
2649 at(self.lane(lane), timeline_frame)
2650 }
2651
2652 /// How the composite is graded at `timeline_frame`, so the picture playback
2653 /// converts and the one an export encodes are graded from one answer.
2654 /// `None` over a gap (black is black) and for a clip nobody has graded,
2655 /// which is the byte-identical path everywhere.
2656 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
2657 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2658 self.color_of(lane, idx)
2659 }
2660
2661 /// How the composite meets the project canvas at `timeline_frame`, so the
2662 /// picture playback composes and the one an export encodes are placed from
2663 /// one answer. `Fit` over a gap, where black is already the canvas.
2664 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
2665 self.composite_clip_at(timeline_frame)
2666 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
2667 }
2668
2669 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
2670 /// viewer sees from `timeline_frame` to the end, in order. What an export
2671 /// encodes and what playback walks at a clip boundary.
2672 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
2673 let mut out = Vec::new();
2674 let mut t = timeline_frame;
2675 while let Some(span) = self.composite_span_at(t) {
2676 t = span.end();
2677 out.push(span);
2678 }
2679 out
2680 }
2681
2682 /// Split every lane at `timeline_frame`, so that frame becomes the first
2683 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
2684 /// (`false`, no change) when no lane has a clip to split there -- at a
2685 /// placement's own start, in a gap, and past the end -- all of which would
2686 /// produce an empty clip or nothing at all.
2687 ///
2688 /// Lanes' halves share an id only where they are the *same* span: the lanes
2689 /// are edited apart, so the clip being cut here may start (or end)
2690 /// somewhere else on another lane, and a group id whose clips disagree
2691 /// about their span is not one take (see [`links_are_consistent`], which
2692 /// refuses to load one).
2693 ///
2694 /// Metadata only: no mapping changes, in any lane.
2695 pub fn split(&mut self, timeline_frame: u32) -> bool {
2696 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
2697 }
2698
2699 /// [`split`](Project::split), with the snapshot optional and the lanes
2700 /// named: a batch that has already taken a snapshot
2701 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
2702 /// region and must still be one undo press, and a *scoped* batch must not
2703 /// cut a lane it was told to leave alone.
2704 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
2705 let cut: Vec<Option<Clip>> = self
2706 .lanes
2707 .iter()
2708 .enumerate()
2709 .map(|(i, l)| {
2710 on.contains(&i)
2711 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
2712 .flatten()
2713 })
2714 .collect();
2715 // The same question on the subtitle lanes, in their own arithmetic: a
2716 // razor cuts the captions with the picture, and a frame where only a
2717 // caption can be cut is still a cut.
2718 let cut_subs: Vec<bool> = self
2719 .lanes
2720 .iter()
2721 .enumerate()
2722 .map(|(i, l)| {
2723 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
2724 })
2725 .collect();
2726 // The links the captions carry, read before the room is opened below
2727 // -- `sub_open_room` takes the id off both halves, exactly as
2728 // `open_room` does for a clip, and the split hands the halves theirs
2729 // back afterwards.
2730 let sub_orig: Vec<Option<u32>> = self
2731 .lanes
2732 .iter()
2733 .zip(&cut_subs)
2734 .map(|(l, &cut)| {
2735 cut.then(|| {
2736 l.subs
2737 .iter()
2738 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
2739 .and_then(|s| s.link)
2740 })
2741 .flatten()
2742 })
2743 .collect();
2744 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
2745 return false;
2746 }
2747 if snapshot {
2748 self.snapshot();
2749 }
2750 for (data, _) in self
2751 .lanes
2752 .iter_mut()
2753 .zip(&cut_subs)
2754 .filter(|&(_, &cut)| cut)
2755 {
2756 // A split is room of no width: the halves keep their windows by
2757 // proportion and nothing moves.
2758 sub_open_room(&mut data.subs, timeline_frame, 0);
2759 debug_assert!(subs_sorted_disjoint(&data.subs));
2760 }
2761 // Each side is its own question, and the answer is the group the clip
2762 // already carried: the left half *keeps* its take's id -- the take the
2763 // frames before the cut still are -- and the right halves of one take
2764 // share one fresh id of their own, clips and captions alike. A lane
2765 // holding no group (a `place`ment, a caption nobody grouped) comes out
2766 // of the cut holding none, which is what it went in with. The captions'
2767 // own links were drawn above, before the room opened.
2768 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
2769 let mut distinct: Vec<u32> = Vec::new();
2770 for id in orig.iter().chain(&sub_orig).flatten() {
2771 if !distinct.contains(id) {
2772 distinct.push(*id);
2773 }
2774 }
2775 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
2776 let right_of =
2777 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
2778 for (l, data) in self.lanes.iter_mut().enumerate() {
2779 if !cut_subs[l] {
2780 continue;
2781 }
2782 // The pair the razor just made: they touch at the frame it cut.
2783 if let Some(idx) = data
2784 .subs
2785 .iter()
2786 .position(|s| s.end() == timeline_frame)
2787 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
2788 {
2789 data.subs[idx].link = sub_orig[l];
2790 data.subs[idx + 1].link = right_of(sub_orig[l]);
2791 }
2792 }
2793 for (data_i, data) in self.lanes.iter_mut().enumerate() {
2794 // The lanes this call was not scoped to are not cut, whatever their
2795 // own clips would allow.
2796 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
2797 continue;
2798 };
2799 let mut tail = data.clips[idx];
2800 // Where the cut lands *in the file*, which is the clip's own rate
2801 // away from where it lands on the timeline. Both halves keep the
2802 // speed, and `splittable` has already refused any frame at which
2803 // the two would not add up to the one being cut.
2804 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
2805 tail.start = timeline_frame;
2806 tail.link = right_of(orig[data_i]);
2807 data.clips[idx].out_frame = tail.in_frame;
2808 data.clips[idx].link = orig[data_i];
2809 data.clips.insert(idx + 1, tail);
2810 }
2811 true
2812 }
2813
2814 /// The inverse of [`split`](Project::split): rejoin the placements that meet
2815 /// at `timeline_frame` in every lane and put the result back in one group.
2816 /// Only what a split could have produced is rejoined -- the two sides must
2817 /// touch on the timeline *and* be consecutive frames of the same source --
2818 /// so the clip list comes back exactly as it was and traversal with it.
2819 /// `false` when no lane has such a pair. The rejoined placement keeps the
2820 /// **left** half's id, which is the take the split left on it: rejoining a
2821 /// cut take puts the take back, id and all.
2822 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
2823 // What each lane would end up covering, if it joins here at all.
2824 let joined: Vec<Option<(u32, u32)>> = self
2825 .lanes
2826 .iter()
2827 .map(|l| {
2828 joinable(&l.clips, timeline_frame)
2829 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
2830 })
2831 .collect();
2832 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
2833 let join_subs: Vec<Option<usize>> = self
2834 .lanes
2835 .iter()
2836 .map(|l| sub_joinable(&l.subs, timeline_frame))
2837 .collect();
2838 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
2839 return false;
2840 }
2841 self.snapshot();
2842 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
2843 if let Some(idx) = sub {
2844 data.subs[idx].frames += data.subs[idx + 1].frames;
2845 data.subs[idx].out_us = data.subs[idx + 1].out_us;
2846 data.subs.remove(idx + 1);
2847 debug_assert!(subs_sorted_disjoint(&data.subs));
2848 }
2849 let Some(idx) = joinable(&data.clips, timeline_frame) else {
2850 continue;
2851 };
2852 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
2853 data.clips.remove(idx + 1);
2854 }
2855 true
2856 }
2857
2858 /// Take the placement at `idx` of `lane` out of its group: every clip and
2859 /// every caption carrying its id -- on however many lanes -- is handed an
2860 /// id of its own, so from here on each half moves, trims and is deleted
2861 /// alone. The music video whose sound is to be cut against its picture
2862 /// starts here, and so does the caption that has to come off the picture it
2863 /// was pinned to.
2864 ///
2865 /// An id of its own rather than none at all: a half no other lane is grouped
2866 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
2867 /// (see [`links_are_consistent`]), and it is what a front-end already draws
2868 /// as detached. `None` would instead say "was never part of a take", which
2869 /// is what a one-lane [`place`](Project::place) means.
2870 ///
2871 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
2872 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
2873 /// the group back. Refused (`false`, nothing changed) for an index that is
2874 /// not there, a placement in no group at all, and one whose group has no
2875 /// other half -- that one is already detached, and a refusal must not cost
2876 /// an undo step.
2877 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
2878 let Some(members) = self.group_of(lane, idx) else {
2879 return false;
2880 };
2881 if members.alone() {
2882 return false;
2883 }
2884 let Some(id) = self
2885 .lane(lane)
2886 .get(idx)
2887 .and_then(|c| c.link)
2888 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
2889 else {
2890 return false;
2891 };
2892 self.snapshot();
2893 // Drawn before the walk: `new_link` takes the whole project, and the
2894 // walk holds the lanes.
2895 let count = members.clips.len() + members.subs.len();
2896 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
2897 for data in &mut self.lanes {
2898 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
2899 c.link = fresh.pop();
2900 }
2901 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
2902 s.link = fresh.pop();
2903 }
2904 }
2905 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2906 true
2907 }
2908
2909 /// Put two clips on two lanes into one group, so what moves one moves the
2910 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
2911 /// how a picture is regrouped with sound it was never opened with. Whatever
2912 /// either of them was grouped with comes along: those clips cover this same
2913 /// span already, so the result is one group and not two overlapping ones.
2914 ///
2915 /// Same frames or nothing: a group id names **one span** on however many
2916 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
2917 /// clips that do not cover the same frames cannot be one take, and the
2918 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
2919 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
2920 /// mean, not the rule.
2921 ///
2922 /// Metadata only, one snapshot. The error says what is wrong, because
2923 /// `false` would not: a bad index, one lane twice (a group is at most one
2924 /// clip per lane), spans that disagree, and a pair that is already one take
2925 /// -- nothing changes, and none of them costs an undo step.
2926 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
2927 if a == b {
2928 return Err(format!(
2929 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
2930 a.label()
2931 )
2932 .into());
2933 }
2934 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
2935 p.lane(lane)
2936 .get(idx)
2937 .copied()
2938 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
2939 };
2940 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
2941 if (x.start, x.end()) != (y.start, y.end()) {
2942 return Err(format!(
2943 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
2944 a.label(),
2945 x.start,
2946 x.end(),
2947 b.label(),
2948 y.start,
2949 y.end()
2950 )
2951 .into());
2952 }
2953 if x.link.is_some() && x.link == y.link {
2954 return Err("those two are one take already".into());
2955 }
2956 self.snapshot();
2957 let id = self.new_link();
2958 // Every clip either of them was grouped with, by the same rule: all of
2959 // them cover this span, so one id over the lot stays consistent.
2960 let old = [x.link, y.link];
2961 for data in &mut self.lanes {
2962 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
2963 if old.contains(&c.link) {
2964 c.link = Some(id);
2965 }
2966 }
2967 }
2968 // And the two themselves, which a `place` may have left in no group.
2969 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
2970 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
2971 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2972 Ok(())
2973 }
2974
2975 /// Put every placement the picks name into one group -- the group a hand
2976 /// builds with ctrl-click and a menu: the picture, its sound and the
2977 /// caption over it, on as many lanes as the picks name. What any of them
2978 /// was already grouped with rides along (one group, not two sharing a
2979 /// member), and the members keep their own spans: a group is one id over
2980 /// one placement per lane, and the offsets between them are what the group
2981 /// preserves -- a drag, a trim and a delete all move the members *by the
2982 /// same distance*, not to the same frames.
2983 ///
2984 /// No two picks may name one lane -- that is the one clip-per-lane rule,
2985 /// and the refusal says which lane -- and a pick that names nothing is
2986 /// refused with its own words. At least two picks, or there is nothing to
2987 /// group.
2988 ///
2989 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
2990 /// apart again. None of the refusals changes anything or costs an undo
2991 /// step.
2992 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
2993 if picks.len() < 2 {
2994 return Err("a group is two placements or more: pick another one first".into());
2995 }
2996 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
2997 for &(lane, idx) in picks {
2998 if seen.contains(&lane) {
2999 return Err(format!(
3000 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3001 track",
3002 lane.label()
3003 )
3004 .into());
3005 }
3006 seen.push(lane);
3007 let there = if lane.kind == LaneKind::Subtitle {
3008 idx < self.sub_lane(lane).len()
3009 } else {
3010 idx < self.lane(lane).len()
3011 };
3012 if !there {
3013 let what = if lane.kind == LaneKind::Subtitle {
3014 "subtitle"
3015 } else {
3016 "clip"
3017 };
3018 return Err(
3019 format!("there is no {what} {idx} on {}", lane.label()).into()
3020 );
3021 }
3022 }
3023 let links: Vec<Option<u32>> = picks
3024 .iter()
3025 .map(|&(lane, idx)| {
3026 if lane.kind == LaneKind::Subtitle {
3027 self.sub_lane(lane)[idx].link
3028 } else {
3029 self.lane(lane)[idx].link
3030 }
3031 })
3032 .collect();
3033 // The picks are already one per lane (`seen`, above), but a pick's
3034 // *existing* group can carry a second member onto a lane another
3035 // pick (or another existing group in the merge) already occupies --
3036 // two captions on one sub lane, say, each grouped with a different
3037 // clip before this call. Merging both in would leave that lane with
3038 // two members of one id, which `links_are_consistent` may never see:
3039 // refused by name, before anything moves, rather than a group closed
3040 // broken.
3041 let labels = handles(&self.lanes);
3042 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3043 for (li, data) in self.lanes.iter().enumerate() {
3044 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3045 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3046 if n > 0 {
3047 per_lane.insert(li, n as u32);
3048 }
3049 }
3050 // A pick that carries no link of its own is invisible to the scan
3051 // above (there is no `Some` to match): it still claims its lane.
3052 for &(lane, _) in picks {
3053 let li = self.index(lane).expect("checked above");
3054 per_lane.entry(li).or_insert(0);
3055 if !self.lanes[li]
3056 .clips
3057 .iter()
3058 .any(|c| c.link.is_some() && links.contains(&c.link))
3059 && !self.lanes[li]
3060 .subs
3061 .iter()
3062 .any(|s| s.link.is_some() && links.contains(&s.link))
3063 {
3064 *per_lane.get_mut(&li).expect("just inserted") += 1;
3065 }
3066 }
3067 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3068 return Err(format!(
3069 "a group is one placement per lane: merging these groups would put two on {}",
3070 labels[li].label()
3071 )
3072 .into());
3073 }
3074 self.snapshot();
3075 let id = self.new_link();
3076 // Whatever any pick was grouped with comes along, for [`group`]'s
3077 // reason -- one id over the lot, not two groups sharing a member.
3078 for data in &mut self.lanes {
3079 for c in data.clips.iter_mut() {
3080 if c.link.is_some() && links.contains(&c.link) {
3081 c.link = Some(id);
3082 }
3083 }
3084 for s in data.subs.iter_mut() {
3085 if s.link.is_some() && links.contains(&s.link) {
3086 s.link = Some(id);
3087 }
3088 }
3089 }
3090 // And the picks themselves, which a `place` may have left in no group.
3091 // The lane seats are read before the walk, which holds the lanes.
3092 let seats: Vec<(usize, bool)> = picks
3093 .iter()
3094 .map(|&(lane, _)| {
3095 (
3096 self.index(lane).expect("checked above"),
3097 lane.kind == LaneKind::Subtitle,
3098 )
3099 })
3100 .collect();
3101 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3102 let _ = lane;
3103 if sub {
3104 self.lanes[at].subs[idx].link = Some(id);
3105 } else {
3106 self.lanes[at].clips[idx].link = Some(id);
3107 }
3108 }
3109 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3110 Ok(())
3111 }
3112
3113 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3114 /// lands on and leaving every other clip exactly where it is -- the
3115 /// per-lane paste. Anything already there is trimmed away (and split in two
3116 /// if `clip` lands inside it), which is what keeps the lane sorted and
3117 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3118 /// gap. Refused only for an empty `clip`.
3119 ///
3120 /// The placement belongs to no group: a clipboard clip carries the link id
3121 /// of the take it was copied from, and placing it twice -- or placing a copy
3122 /// back over the clip it came from -- would put that id on two clips of one
3123 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3124 /// `None` rather than a fresh id because a one-lane placement has nothing on
3125 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3126 /// become a group again.
3127 ///
3128 /// Refused for an empty `clip`, for a lane that is not there, and for a
3129 /// subtitle lane, which carries no picture and no sound
3130 /// ([`Project::place_sub`] is its door).
3131 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3132 if clip.out_frame <= clip.in_frame
3133 || lane.kind == LaneKind::Subtitle
3134 || self.index(lane).is_none()
3135 {
3136 return false;
3137 }
3138 self.snapshot();
3139 let clip = Clip {
3140 start: timeline_frame,
3141 link: None,
3142 ..clip
3143 };
3144 self.insert_over(lane, clip);
3145 true
3146 }
3147
3148 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3149 /// one grouped take -- what a picture let go over a further video track
3150 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3151 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3152 /// this half a file with sound landed on a layer silent, and the only way to
3153 /// hear it was to drop it a second time on an audio lane.
3154 ///
3155 /// Both halves overwrite what they land on and neither ripples, exactly as
3156 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3157 /// nothing under it moves. One history snapshot for the pair, the added lane
3158 /// included, so one [`Project::undo`] takes the whole placement back. The two
3159 /// carry one link, which is what makes them one take to a drag, a trim and a
3160 /// save.
3161 ///
3162 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3163 /// there or is not a video lane: sound placed alone is
3164 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3165 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3166 if clip.out_frame <= clip.in_frame
3167 || lane.kind != LaneKind::Video
3168 || self.index(lane).is_none()
3169 {
3170 return false;
3171 }
3172 self.snapshot();
3173 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3174 // an ord names a lane only while every ord below it does.
3175 while self.lane_count(LaneKind::Audio) <= lane.ord {
3176 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3177 }
3178 let clip = Clip {
3179 start: timeline_frame,
3180 link: Some(self.new_link()),
3181 ..clip
3182 };
3183 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3184 self.insert_over(half, clip);
3185 }
3186 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3187 true
3188 }
3189
3190 /// `clip` into `lane` at its own start, over whatever it lands on: the
3191 /// insert both placement doors make, which is what keeps a lane sorted and
3192 /// disjoint. The caller has checked that the lane is there.
3193 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3194 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3195 clear(clips, clip.start, clip.end());
3196 let idx = clips.partition_point(|c| c.start < clip.start);
3197 clips.insert(idx, clip);
3198 debug_assert!(sorted_disjoint(clips));
3199 }
3200
3201 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3202 /// frame `start`: the drag that rearranges takes, along a track and across
3203 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3204 /// was. `start` at the clip's own is the pure lane change.
3205 ///
3206 /// The whole group travels the same distance, each half on the lane it
3207 /// already sits on -- a link means "these cover one span on however many
3208 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3209 /// sound would be a group no save could load. Only the dragged half changes
3210 /// lane, and that is not a desync: a link names no lane at all.
3211 ///
3212 /// `start` is **clamped**, never refused, to the room the group has: no
3213 /// member crosses a neighbour on the lane it lands on, exactly as
3214 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3215 /// dragging past a neighbour means "as far as it goes", and butting up
3216 /// against the take next door is how clips are laid end to end. The
3217 /// tightest member's wall wins, so a sound half boxed in between two others
3218 /// holds its picture still.
3219 ///
3220 /// Refused, changing nothing and costing no undo step, for a lane that is
3221 /// not there, an index that is not there, a move across *kinds* (a picture
3222 /// cannot play on an audio lane, and the save it wrote would not open
3223 /// again), a head let go *inside* another clip or into a gap too narrow to
3224 /// hold this one -- a move that overwrote what it landed on would destroy a
3225 /// take the pointer never named, which is what [`place`](Project::place)
3226 /// may do and a drag may not -- a half let go onto the lane its own partner
3227 /// is on, and a drop that changes neither lane nor frame, which is a clip
3228 /// picked up and put back down, i.e. a click.
3229 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3230 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3231 return false;
3232 };
3233 if from.kind != to.kind {
3234 return false;
3235 }
3236 let members = self.group_of(from, idx).expect("the clip was found");
3237 let held = self.index(from).expect("the clip was found on it");
3238 // The two halves of one group would land on one span of one lane, which
3239 // is the one thing a link may never mean. Refused rather than clamped:
3240 // the partner moves the same distance, so there is no room for it
3241 // anywhere on that lane.
3242 if dest != held
3243 && members
3244 .clips
3245 .iter()
3246 .chain(&members.subs)
3247 .any(|&(l, _)| l == dest)
3248 {
3249 return false;
3250 }
3251 let want = i64::from(start) - i64::from(clip.start);
3252 // How far the group may travel, in timeline frames and signed: every
3253 // member -- the clips and any caption grouped with them -- narrows it
3254 // to the gap it is landing in, and what is left is what the pointer is
3255 // clamped to.
3256 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3257 return false;
3258 };
3259 if lo > hi {
3260 return false;
3261 }
3262 let delta = want.clamp(lo, hi);
3263 if delta == 0 && dest == held {
3264 return false;
3265 }
3266 self.snapshot();
3267 for &(l, i) in &members.clips {
3268 let c = &mut self.lanes[l].clips[i];
3269 // In range by the walls above, which are `u32` frames throughout.
3270 c.start = (i64::from(c.start) + delta) as u32;
3271 }
3272 for &(l, i) in &members.subs {
3273 let s = &mut self.lanes[l].subs[i];
3274 s.start = (i64::from(s.start) + delta) as u32;
3275 }
3276 if dest != held {
3277 let clip = self.lanes[held].clips.remove(idx);
3278 let clips = &mut self.lanes[dest].clips;
3279 let at = clips.partition_point(|c| c.start < clip.start);
3280 clips.insert(at, clip);
3281 }
3282 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3283 debug_assert!(members
3284 .clips
3285 .iter()
3286 .chain(&members.subs)
3287 .all(|&(l, _)| {
3288 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3289 }));
3290 true
3291 }
3292
3293 /// How far a group drag may travel, `(least, most)` in timeline frames and
3294 /// signed: every member narrows the range to the gap it is landing in --
3295 /// the clips against their lanes' clips and the captions against their
3296 /// lanes' captions -- and what is left is what the pointer is clamped to.
3297 /// `travelling` names the one member that changes lane, if any: the clip a
3298 /// hand is carrying onto another track, whose walls are read on the lane it
3299 /// is let go over at the frame the pointer named. `None` when a member has
3300 /// no gap to land in at all.
3301 fn move_room(
3302 &self,
3303 members: &Members,
3304 travelling: Option<(usize, usize, usize, u32)>,
3305 ) -> Option<(i64, i64)> {
3306 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3307 for &(l, i) in members.clips.iter().chain(&members.subs) {
3308 let sub = members.subs.contains(&(l, i));
3309 let (start, frames) = match self.lanes[l]
3310 .clips
3311 .get(i)
3312 .filter(|_| !sub)
3313 .map(|c| (c.start, c.frames()))
3314 {
3315 Some(pair) => pair,
3316 None => {
3317 let s = self.lanes[l].subs.get(i)?;
3318 (s.start, s.frames)
3319 }
3320 };
3321 let land = travelling
3322 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3323 .map_or(l, |(_, _, dest, _)| dest);
3324 // Which gap this member's walls are read off: its own place on the
3325 // lane it stays on, and the frame the pointer named on the lane it
3326 // is let go over. A clip's neighbours are the clips of the lane it
3327 // lands on and a caption's are its captions -- the two lists of one
3328 // lane never meet.
3329 let at = match travelling {
3330 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3331 _ => start,
3332 };
3333 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3334 let neighbours: Vec<(u32, u32)> = if sub {
3335 self.lanes[land]
3336 .subs
3337 .iter()
3338 .map(|s| (s.start, s.end()))
3339 .collect()
3340 } else {
3341 self.lanes[land]
3342 .clips
3343 .iter()
3344 .map(|c| (c.start, c.end()))
3345 .collect()
3346 };
3347 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3348 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3349 continue;
3350 }
3351 if *other_start <= at && at < *other_end {
3352 // A head let go inside another placement, which a clamp
3353 // has no answer for: the drop is refused.
3354 return None;
3355 }
3356 match other_end <= &at {
3357 true => wall_lo = wall_lo.max(*other_end),
3358 false => wall_hi = wall_hi.min(*other_start),
3359 }
3360 }
3361 if wall_hi - wall_lo < frames {
3362 return None;
3363 }
3364 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3365 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3366 }
3367 Some((lo, hi))
3368 }
3369
3370 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3371 /// the drag on a clip's end that makes it play more or less of its source.
3372 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3373 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3374 /// is room that was already empty. One snapshot, so a whole drag is one
3375 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3376 /// sample. Changes the timeline->source mapping: the caller must reseek.
3377 ///
3378 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3379 /// exactly what they played before, which is what makes this a trim and not
3380 /// a slip.
3381 ///
3382 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3383 /// legal means "as far as it goes", and stopping the box there is the
3384 /// affordance. The walls are: one frame of clip always survives, an edge
3385 /// never crosses the neighbouring clip on its own lane, an in-point never
3386 /// walks back past the source's first frame, and an out-point never runs
3387 /// past `source_frames[clip.source]` -- the caller's table of how long each
3388 /// source actually is ([`Project`] does not know, and a clip ending past its
3389 /// file's last frame is a save that will not open again; see
3390 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3391 /// there may not grow at all.
3392 ///
3393 /// Linked placements trim *together*, by one delta: every member's same
3394 /// edge moves the distance the dragged one did, clamped to the room its
3395 /// own walls leave -- offsets between the members of a hand-built group
3396 /// survive the trim, exactly as they survive a drag.
3397 ///
3398 /// `false`, changing nothing and costing no undo step, for an index that is
3399 /// not there and for an edge that is already where it was asked to go.
3400 pub fn trim(
3401 &mut self,
3402 lane: Lane,
3403 idx: usize,
3404 edge: Edge,
3405 to: u32,
3406 source_frames: &[u32],
3407 ) -> bool {
3408 let (Some((lo, hi)), Some(clip)) = (
3409 self.trim_room(lane, idx, edge, source_frames),
3410 self.lane(lane).get(idx).copied(),
3411 ) else {
3412 return false;
3413 };
3414 let to = to.clamp(lo, hi);
3415 let at = match edge {
3416 Edge::Start => clip.start,
3417 Edge::End => clip.end(),
3418 };
3419 if to == at {
3420 return false;
3421 }
3422 // Worked out before anything moves: at a slow rate a room can be too
3423 // narrow to hold even one source frame ([`Speed::fit`]), and the
3424 // dragged clip refusing to fit must refuse the whole gesture rather
3425 // than be given a range wider than its room -- which is the overlap
3426 // the lane invariant exists to forbid. The walls below leave that room,
3427 // so this is the backstop for a project that came in through another
3428 // door.
3429 let room = match edge {
3430 // The frames that stay play what they played, so what survives is
3431 // measured from the *end*.
3432 Edge::Start => clip.end() - to,
3433 Edge::End => to - clip.start,
3434 };
3435 let Some(keep) = clip.speed.fit(room) else {
3436 return false;
3437 };
3438 let members = self.group_of(lane, idx).expect("checked above");
3439 self.snapshot();
3440 let still = self.is_still(&clip);
3441 let held = self.index(lane).expect("checked above");
3442 let c = &mut self.lanes[held].clips[idx];
3443 match edge {
3444 // A still has no earlier frame to walk an in-point back to --
3445 // every frame of it is the same picture -- so its head grows
3446 // *forward*: the range it plays is however long the new room is,
3447 // anchored at the source's frame 0. Bounded by `lo`, which is where
3448 // the cap in `source_frames` is applied.
3449 Edge::Start if still => {
3450 c.in_frame = 0;
3451 c.out_frame = keep;
3452 c.start = to;
3453 }
3454 Edge::Start => {
3455 // Non-negative by `lo`, which is what keeps the in-point on the
3456 // source.
3457 c.in_frame = c.out_frame - keep.min(c.out_frame);
3458 c.start = to;
3459 }
3460 // Never wider than the room the edge was clamped to: see
3461 // [`Speed::fit`].
3462 Edge::End => c.out_frame = c.in_frame + keep,
3463 }
3464 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3465 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3466 true
3467 }
3468
3469 /// The rest of a group after one member's `edge` has moved by `delta`:
3470 /// every other member's same edge moves the same distance, clamped to the
3471 /// room its own walls leave -- a clip's against its lane and its source,
3472 /// a caption's against its own lane, its window following by the
3473 /// placement's own proportion. The undo step is the caller's: this is the
3474 // second half of one edit, not an edit of its own.
3475 fn follow_group(
3476 &mut self,
3477 members: &Members,
3478 dragged: &(usize, usize),
3479 edge: Edge,
3480 delta: i64,
3481 source_frames: &[u32],
3482 ) {
3483 for &(l, i) in &members.clips {
3484 if (l, i) == *dragged {
3485 continue;
3486 }
3487 let c = self.lanes[l].clips[i];
3488 let at = match edge {
3489 Edge::Start => c.start,
3490 Edge::End => c.end(),
3491 };
3492 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3493 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3494 if to == at {
3495 continue;
3496 }
3497 let room = match edge {
3498 Edge::Start => c.end() - to,
3499 Edge::End => to - c.start,
3500 };
3501 let Some(keep) = c.speed.fit(room) else {
3502 continue;
3503 };
3504 let still = self.is_still(&self.lanes[l].clips[i]);
3505 let c = &mut self.lanes[l].clips[i];
3506 match edge {
3507 Edge::Start if still => {
3508 c.in_frame = 0;
3509 c.out_frame = keep;
3510 c.start = to;
3511 }
3512 Edge::Start => {
3513 c.in_frame = c.out_frame - keep.min(c.out_frame);
3514 c.start = to;
3515 }
3516 Edge::End => c.out_frame = c.in_frame + keep,
3517 }
3518 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3519 }
3520 for &(l, i) in &members.subs {
3521 if (l, i) == *dragged {
3522 continue;
3523 }
3524 let s = self.lanes[l].subs[i];
3525 let at = match edge {
3526 Edge::Start => s.start,
3527 Edge::End => s.end(),
3528 };
3529 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3530 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3531 if to == at {
3532 continue;
3533 }
3534 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3535 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3536 }
3537 }
3538
3539 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3540 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3541 /// What a front-end drawing the box *during* a drag asks, so the live width
3542 /// is the width the release will commit and an edge stops under the pointer
3543 /// rather than snapping back. The **clip's own** walls: the rest of its
3544 /// group follows by the same delta within their own ([`follow_group`]), so
3545 /// what is drawn for the dragged edge is what its own clip will commit.
3546 /// `None` for an index that is not there.
3547 pub fn trim_room(
3548 &self,
3549 lane: Lane,
3550 idx: usize,
3551 edge: Edge,
3552 source_frames: &[u32],
3553 ) -> Option<(u32, u32)> {
3554 let l = self.index(lane)?;
3555 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3556 }
3557
3558 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3559 /// its lane's storage index: the one wall computation, asked for the clip
3560 /// itself and for each member a group trim carries.
3561 fn clip_room(
3562 &self,
3563 l: usize,
3564 i: usize,
3565 edge: Edge,
3566 source_frames: &[u32],
3567 ) -> (u32, u32) {
3568 let clips = &self.lanes[l].clips;
3569 let c = clips[i];
3570 let (lo, hi) = match edge {
3571 Edge::Start => (
3572 // Back to the source's own first frame -- as many *timeline*
3573 // frames as that head is worth at the clip's rate, which at
3574 // real time is the head itself -- and never over the clip in
3575 // front of it. Saturating because a clip may hold *more*
3576 // head than the timeline has room for -- a ripple delete
3577 // slides a clip back to frame 0 with its in-point wherever
3578 // the cut left it -- and frame 0 is the other wall.
3579 //
3580 // A still is measured from its *tail* instead: it has no
3581 // in-point worth the name (every frame the same picture), so
3582 // its head reaches exactly as far as its tail does -- out to
3583 // the length the caller's table gives it, whole. Measured
3584 // from the in-point it would have no head room at all, which
3585 // is a placed picture whose left edge cannot be dragged out.
3586 // No entry in the table means no growth, as it does at the
3587 // other end.
3588 if self.is_still(&c) {
3589 c.end().saturating_sub(
3590 c.speed
3591 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
3592 )
3593 } else {
3594 c.start.saturating_sub(c.speed.room(c.in_frame))
3595 }
3596 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
3597 // One *frame of clip* always survives, and at a rate below
3598 // real time one frame of clip is several frames of timeline
3599 // ([`Speed::room`]): an edge dragged closer than that would
3600 // ask for a range no source frame fits in. At real time this
3601 // is `end - 1`, unchanged.
3602 c.end() - c.speed.room(1),
3603 ),
3604 Edge::End => (
3605 // ...and the same wall from the other end: the shortest this
3606 // clip can be is the room one source frame of it takes.
3607 c.start + c.speed.room(1),
3608 // Out to whatever is left of the source -- again in timeline
3609 // frames, at this clip's rate -- and never over the clip
3610 // behind it.
3611 c.start
3612 .saturating_add(
3613 c.speed.room(
3614 source_frames
3615 .get(c.source)
3616 .copied()
3617 .unwrap_or(c.out_frame)
3618 .saturating_sub(c.in_frame),
3619 ),
3620 )
3621 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
3622 ),
3623 };
3624 // `hi.max(lo)`: for a clip the invariants hold for, the range always
3625 // contains the edge's own place, and a caller's wrong `source_frames`
3626 // must not become an empty range (or a panicking `clamp`) here.
3627 (lo, hi.max(lo))
3628 }
3629
3630 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
3631 /// every frame is the same picture, so which frame of it a clip's in-point
3632 /// names is not a question -- what [`Project::trim`] lets grow at either
3633 /// end. `false` for a source that is not there.
3634 fn is_still(&self, clip: &Clip) -> bool {
3635 self.sources
3636 .get(clip.source)
3637 .is_some_and(|s| crate::is_image(&s.path))
3638 }
3639
3640 /// The placements that move as one with the one at `idx` of `lane` --
3641 /// itself and whatever carries its link, on the media lanes and the
3642 /// subtitle ones alike. `None` for an index that is not there.
3643 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
3644 let sub = lane.kind == LaneKind::Subtitle;
3645 let link = if sub {
3646 self.sub_lane(lane).get(idx)?.link
3647 } else {
3648 self.lane(lane).get(idx)?.link
3649 };
3650 let mut members = Members::default();
3651 match link {
3652 Some(link) => {
3653 for (l, data) in self.lanes.iter().enumerate() {
3654 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
3655 members.clips.push((l, i));
3656 }
3657 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
3658 members.subs.push((l, i));
3659 }
3660 }
3661 }
3662 None => {
3663 let l = self.index(lane).expect("the placement was found on it");
3664 if sub {
3665 members.subs.push((l, idx));
3666 } else {
3667 members.clips.push((l, idx));
3668 }
3669 }
3670 }
3671 Some(members)
3672 }
3673
3674 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
3675 /// new group, pushing everything from there on later by its length in
3676 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
3677 /// the clip it lands in is split around it; past the end of the timeline it
3678 /// goes down where it was asked for, with black in front of it -- which is
3679 /// what a library row let go on the open bed means, and what the ghost under
3680 /// the pointer promised. A clipboard means "put it here", not "here and
3681 /// black in front", and clamps to the end at its own door
3682 /// ([`crate::PlaybackSession::paste_at`]).
3683 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
3684 ///
3685 /// `V1` and `A1` and no other lane, because a take is one picture and one
3686 /// sound: copying it onto every lane there is would play the same audio
3687 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
3688 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
3689 /// video lane it is a clip that decodes to nothing, and a save carrying one
3690 /// does not open again -- and a still image ([`crate::is_image`]) reaches
3691 /// `V1` only, for the mirror of that reason. The room is still opened on
3692 /// every media lane, or the lanes it was not inserted into would slide out
3693 /// of step with the ones it was -- and the subtitle lanes are left alone:
3694 /// the words keep their own clock, and a caption that should travel with a
3695 /// clip is what a group is for.
3696 ///
3697 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
3698 /// Changes the timeline->source mapping: the caller must reseek. Refused for
3699 /// an empty `clip` and for one naming a source that is not there (both of
3700 /// which the public fields let a caller build), and for a paste whose ripple
3701 /// would push a clip past the last frame there is -- nothing is changed by
3702 /// any of them.
3703 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
3704 let Some(source) = self.sources.get(clip.source) else {
3705 return false;
3706 };
3707 if clip.out_frame <= clip.in_frame {
3708 return false;
3709 }
3710 let audio_only = crate::is_audio(&source.path);
3711 // ...and its mirror: a still is a picture and no sound, so a copy of one
3712 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
3713 // worker tries to demux -- which silences the *whole session*, not just
3714 // that clip -- and a save the engine's own `open_project` then refuses.
3715 let picture_only = crate::is_image(&source.path);
3716 // The frame it was asked for and no other: a row let go on the empty
3717 // bed past the last clip lands *there*, under the ghost that promised
3718 // it, with black in front. Clamping to the end here made every drop on
3719 // open bed an append -- the clipboard's rule, applied to a hand that
3720 // had named a place.
3721 let at = timeline_frame;
3722 // The room it takes on the timeline, which its speed decides -- not the
3723 // source range it reads.
3724 let len = clip.frames();
3725 // Room for it: `open_room` adds `len` to every start from `at` on, and a
3726 // hand-written file may hold a clip that ends at the very last frame
3727 // (`edith::check` permits `start + len == u32::MAX`). Refused here
3728 // rather than wrapped there -- a wrapped start lands *behind* the clip
3729 // it belongs after, which is an overlap no save will read back.
3730 if at.checked_add(len).is_none()
3731 || self
3732 .lanes
3733 .iter()
3734 .flat_map(|l| &l.clips)
3735 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
3736 {
3737 return false;
3738 }
3739 // ...and room *to open*: the paste splits whatever it lands inside of,
3740 // and a speeded clip can only be cut where its own rate has a source
3741 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
3742 // of one, which is the overlap a lane may never hold. At real time every
3743 // frame answers, so this cannot refuse an unspeeded paste.
3744 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
3745 if self
3746 .lanes
3747 .iter()
3748 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
3749 {
3750 return false;
3751 }
3752 self.snapshot();
3753 let clip = Clip {
3754 start: at,
3755 link: Some(self.new_link()),
3756 ..clip
3757 };
3758 // Only lanes that can play the source: a file with no picture belongs on
3759 // an audio lane and nowhere else, exactly as `place_stream_at` decides
3760 // it for an import. On a video lane it would decode to nothing, and the
3761 // save it wrote would not open again.
3762 let kinds: &[LaneKind] = match (audio_only, picture_only) {
3763 (true, _) => &[LaneKind::Audio],
3764 (_, true) => &[LaneKind::Video],
3765 _ => &[LaneKind::Video, LaneKind::Audio],
3766 };
3767 let takes: Vec<usize> = kinds
3768 .iter()
3769 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
3770 .collect();
3771 for (i, data) in self.lanes.iter_mut().enumerate() {
3772 open_room(&mut data.clips, at, len);
3773 // The subtitle lanes are NOT touched: a paste inserts media, and
3774 // the words keep their own clock. Opening room here used to split
3775 // a caption the paste landed inside and slide the rest behind it
3776 // -- "a caption that stayed put while the picture moved on no
3777 // longer says the same thing" -- but a caption pinned to nothing
3778 // (and a video arriving on a timeline of words alone) has no
3779 // picture to follow, and the split did to the words what no hand
3780 // asked for. A caption that should travel with a clip is what a
3781 // group is for, and a group moves as one.
3782 if takes.contains(&i) {
3783 let idx = data.clips.partition_point(|c| c.start < at);
3784 data.clips.insert(idx, clip);
3785 }
3786 debug_assert!(sorted_disjoint(&data.clips));
3787 debug_assert!(subs_sorted_disjoint(&data.subs));
3788 }
3789 true
3790 }
3791
3792 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
3793 /// silence, and nothing else moves. Refused only for an out-of-range index
3794 /// (which a lane that is not there always is) -- lifting the last placement
3795 /// there is leaves an *empty* timeline, which is a state the project holds
3796 /// like any other and an undo brings back.
3797 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
3798 if idx >= self.lane(lane).len() {
3799 return false;
3800 }
3801 self.snapshot();
3802 self.lane_mut(lane).expect("checked above").remove(idx);
3803 true
3804 }
3805
3806 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
3807 /// the hole: everything after slides back by `len`. The rippling delete --
3808 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
3809 /// empty range; a delete that leaves nothing behind empties the timeline,
3810 /// which is a state like any other and one undo away.
3811 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
3812 if len == 0 {
3813 return false;
3814 }
3815 // Nothing reaches past `at`: there is nothing to cut and nothing to
3816 // slide back, and a delete that changes nothing must not cost an undo
3817 // step (see [`snapshot`](Project::snapshot)).
3818 if !self
3819 .lanes
3820 .iter()
3821 .flat_map(|l| &l.clips)
3822 .any(|c| c.end() > at)
3823 {
3824 return false;
3825 }
3826 self.snapshot();
3827 let on = all_lanes(&self.lanes);
3828 ripple(&mut self.lanes, &on, at, len);
3829 true
3830 }
3831
3832 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
3833 /// out of the lanes in `scope` and close each hole, as one edit: the
3834 /// jumpcut a silence scan asks for ([`crate::silence`]).
3835 ///
3836 /// A lane that is not in `scope` **does not move**, which is the whole
3837 /// point of the parameter: the silences of a podcast track come out
3838 /// without the music track under it sliding. `scope` is an arbitrary set of
3839 /// lanes and not a kind or a range, so a caller with its own idea of what
3840 /// is selected (a take, a track, everything) says it in lanes and nothing
3841 /// here has to learn about selection.
3842 ///
3843 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
3844 /// reason this exists rather than a caller's loop over
3845 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
3846 /// undo press, not forty. Cut back to front, so a region's frames still
3847 /// mean what the caller measured while the ones before it are cut.
3848 ///
3849 /// The list is sorted and overlapping entries are merged before anything is
3850 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
3851 /// other's frames. Refused, with no undo step, for an empty list, for a
3852 /// scope naming no lane that is there, and -- by name -- when the scope
3853 /// would take one half of a take with it
3854 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
3855 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
3856 let regions = tidy(regions);
3857 let on = self.scoped(scope)?;
3858 let Some(&(first, _)) = regions.first() else {
3859 return Err("nothing to cut".into());
3860 };
3861 self.scope_holds_takes_whole(&on, first)?;
3862 self.snapshot();
3863 for &(at, len) in regions.iter().rev() {
3864 ripple(&mut self.lanes, &on, at, len);
3865 }
3866 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3867 Ok(())
3868 }
3869
3870 /// The storage indices of `scope`, which is what every batch below walks.
3871 /// `Err` for a scope that names nothing there rather than a silent no-op:
3872 /// an edit asked for on a lane that is not there did not happen, and the
3873 /// caller has to hear so.
3874 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
3875 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
3876 match on.is_empty() {
3877 true => Err("no track to work on".into()),
3878 false => Ok(on),
3879 }
3880 }
3881
3882 /// The law a scoped ripple lives under: **a group travels as one**, so a
3883 /// batch that moves one half of a take and not the other would leave the
3884 /// halves disagreeing about where they stand -- an offset no hand asked
3885 /// for, and the reason the take's lanes have to be scoped together.
3886 ///
3887 /// Refused by name rather than widened silently. Widening would edit a
3888 /// track the user did not scope, which is exactly the surprise scoping
3889 /// exists to end; a front-end that wants the take is free to *say* the
3890 /// take's lanes, and to name them in what it tells the user afterwards.
3891 ///
3892 /// Only from `from` on: a take sitting entirely before the first cut does
3893 /// not move, so it is not this rule's business.
3894 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
3895 let labels = handles(&self.lanes);
3896 // The halves of a group are on either of a lane's lists, and the
3897 // refusal names whichever sits outside the scope -- a clip like it
3898 // always has, and a caption now that a group may hold one.
3899 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
3900 let Some(id) = link else {
3901 return Ok(());
3902 };
3903 for (j, data) in self.lanes.iter().enumerate() {
3904 if on.contains(&j) {
3905 continue;
3906 }
3907 let clip = data.clips.iter().find(|o| o.link == Some(id));
3908 let sub = data.subs.iter().find(|s| s.link == Some(id));
3909 if let Some(half) = clip {
3910 return Err(format!(
3911 "the {what} at frame {start} is one take with the {} clip at frame {}: \
3912 moving one track of a take would pull it apart -- take the whole take, \
3913 or detach them first",
3914 labels[j].label(),
3915 half.start
3916 )
3917 .into());
3918 }
3919 if let Some(half) = sub {
3920 return Err(format!(
3921 "the {what} at frame {start} is one take with the {} caption at frame {}: \
3922 moving one track of a take would pull it apart -- take the whole take, \
3923 or detach them first",
3924 labels[j].label(),
3925 half.start
3926 )
3927 .into());
3928 }
3929 }
3930 Ok(())
3931 };
3932 for &i in on {
3933 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
3934 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
3935 }
3936 // A caption before the first cut does not move, so it is not this
3937 // rule's business -- exactly the clip test's own line.
3938 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
3939 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
3940 }
3941 }
3942 Ok(())
3943 }
3944
3945 /// Play every one of `regions` at `speed` instead of cutting it: each is
3946 /// split out of whatever covers it, re-rated, and the room it no longer
3947 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
3948 /// does not ripple, and a hole where a silence shrank is the one thing this
3949 /// must not leave. One snapshot for the lot, like
3950 /// [`cut_regions`](Project::cut_regions).
3951 ///
3952 /// The rate is **absolute**, not a multiplier on what is there: running it
3953 /// twice over the same stretch leaves it at `speed`, not at `speed`
3954 /// squared, so a second pass over an already-cut timeline changes nothing.
3955 ///
3956 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
3957 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
3958 ///
3959 /// Refused by name, with nothing changed and no undo step, when:
3960 ///
3961 /// * the scope would take one half of a take with it
3962 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
3963 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
3964 /// shrink by different amounts and the ripple would pull them apart,
3965 /// which is what cutting does not suffer and why delete mode has no such
3966 /// refusal;
3967 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
3968 /// piece could not be split out exactly;
3969 /// * two lanes' pieces would end up different lengths, which is a group
3970 /// whose halves disagree about their span (the refusal
3971 /// [`write_speed`](Project::write_speed) already makes, in its words);
3972 /// * the region would grow rather than shrink, i.e. it already plays faster
3973 /// than `speed`.
3974 pub fn speed_regions(
3975 &mut self,
3976 regions: &[(u32, u32)],
3977 speed: Speed,
3978 scope: &[Lane],
3979 ) -> crate::Result<()> {
3980 let regions = tidy(regions);
3981 let on = self.scoped(scope)?;
3982 let Some(&(first, _)) = regions.first() else {
3983 return Err("nothing to speed up".into());
3984 };
3985 self.scope_holds_takes_whole(&on, first)?;
3986 let labels = handles(&self.lanes);
3987 // Before anything is touched, because this is the refusal a person can
3988 // act on: a clip that laps over the edge of a silence has to be trimmed
3989 // (or the silences cut instead), and saying so after a rollback would
3990 // be saying it about a timeline that already looks different.
3991 for &(at, len) in &regions {
3992 for &l in &on {
3993 for c in &self.lanes[l].clips {
3994 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
3995 {
3996 return Err(format!(
3997 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
3998 speeding it up would pull the lanes apart -- trim it first, or cut the \
3999 silences out instead",
4000 labels[l].label(),
4001 c.start,
4002 at + len
4003 )
4004 .into());
4005 }
4006 }
4007 }
4008 }
4009 // The rest is checked as it is built: a split's own arithmetic is what
4010 // says whether a rate can address an edge. So the snapshot is taken
4011 // first and *rolled back* on a refusal -- one undo either way, and a
4012 // refusal still costs no step (`undo` pops the one just pushed).
4013 self.snapshot();
4014 for &(at, len) in regions.iter().rev() {
4015 self.write_split(at, false, &on);
4016 self.write_split(at + len, false, &on);
4017 let mut room: Option<(Lane, u32)> = None;
4018 let mut refused = None;
4019 for &l in &on {
4020 let clips = &self.lanes[l].clips;
4021 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4022 if (c.start, c.end()) != (at, at + len) {
4023 // *Which* edge did not come off: a rate that cannot
4024 // address the end of the silence is not a rate that
4025 // cannot address its start, and naming the wrong frame
4026 // sends the user looking in the wrong place.
4027 let edge = match c.start == at {
4028 true => at + len,
4029 false => at,
4030 };
4031 refused = Some(format!(
4032 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4033 detach it, or put it back to 1.00x first",
4034 labels[l].label(),
4035 c.start,
4036 c.speed
4037 ));
4038 continue;
4039 }
4040 let after = speed.frames(c.len());
4041 match room {
4042 None => room = Some((labels[l], after)),
4043 Some((first, n)) if n != after => {
4044 refused = Some(format!(
4045 "at {speed} the {} half of the silence at frame {at} would cover \
4046 {after} frames and the {} half {n}: they are one take and a take \
4047 is one span -- detach them first",
4048 labels[l].label(),
4049 first.label()
4050 ));
4051 }
4052 Some(_) => {}
4053 }
4054 }
4055 }
4056 let shrunk = match (refused, room) {
4057 (Some(e), _) => {
4058 self.undo();
4059 return Err(e.into());
4060 }
4061 // A gap on every lane: nothing to re-rate, and nothing to close.
4062 (None, None) => continue,
4063 (None, Some((_, after))) => after,
4064 };
4065 // The region's new length, on every scoped lane alike.
4066 let after = shrunk;
4067 let Some(delta) = len.checked_sub(shrunk) else {
4068 self.undo();
4069 return Err(format!(
4070 "the silence at frame {at} already plays faster than {speed}: \
4071 at that rate it would be {shrunk} frames instead of {len}"
4072 )
4073 .into());
4074 };
4075 for &l in &on {
4076 for c in &mut self.lanes[l].clips {
4077 if c.start == at && c.end() == at + len {
4078 c.speed = speed;
4079 } else if c.start >= at + len {
4080 c.start -= delta;
4081 }
4082 }
4083 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4084 // The captions on a scoped lane travel with the region's time:
4085 // a piece inside it plays in `after` frames instead of `len`
4086 // -- same words on less timeline, its window untouched, for
4087 // [`write_speed`]'s reason -- and everything behind the region
4088 // slides up by what the region gave back.
4089 //
4090 // The pieces inside re-time by their *boundaries*, not each
4091 // on its own: rounding one piece's start and its neighbour's
4092 // start apart can land both on the same frame (two one-frame
4093 // cues of a thirty-frame region at 2x both want frame 15), so
4094 // the mapped boundaries are walked in order and forced apart
4095 // -- each piece at least one frame, none past the region's own
4096 // new end, where the first follower lands exactly. A rounding
4097 // artifact is clamped, not refused: nothing about the words
4098 // asked for an overlap.
4099 let share = f64::from(after) / f64::from(len).max(1.);
4100 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4101 let mut prev = at;
4102 let subs = &mut self.lanes[l].subs;
4103 for i in 0..subs.len() {
4104 let s = subs[i];
4105 if s.start >= at + len {
4106 subs[i].start = s.start - delta;
4107 } else if s.start >= at && s.end() <= at + len {
4108 let mut start = map(s.start).max(prev);
4109 let end = map(s.end()).max(start + 1).min(at + after);
4110 start = start.min(end - 1);
4111 subs[i].start = start;
4112 subs[i].frames = end - start;
4113 prev = end;
4114 }
4115 }
4116 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4117 }
4118 }
4119 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4120 Ok(())
4121 }
4122
4123 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4124 /// -- the whole-group delete a single-lane front-end means. `false` for a
4125 /// bad index. Changes the mapping: the caller must reseek.
4126 pub fn delete(&mut self, idx: usize) -> bool {
4127 self.delete_in(Lane::V1, idx)
4128 }
4129
4130 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4131 /// in no group (or a group of one, which is the same thing to a delete) is
4132 /// what it always was: its own span cut out of *every* lane, so the
4133 /// timeline closes up under it. A clip in a group takes the group with it,
4134 /// each member by its **own** span and on its **own** lane -- the members
4135 /// keep their offsets, so their spans may disagree, and the lanes may end
4136 /// up out of step with each other, which is inherent to a hand-built group
4137 /// and one undo away. Every member -- clips and captions alike -- goes by
4138 /// the same law: its own span out of its own lane, hole closed; a caption
4139 /// in no group keeps the lift that leaves a gap, which is its own door's
4140 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4141 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4142 /// index, and for a lane that is not there. Changes the mapping: the
4143 /// caller must reseek.
4144 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4145 let Some(members) = self.group_of(lane, idx) else {
4146 return false;
4147 };
4148 if !members.alone() {
4149 return self.delete_members(&members);
4150 }
4151 let Some(clip) = self.lane(lane).get(idx).copied() else {
4152 return false;
4153 };
4154 self.ripple_delete(clip.start, clip.frames())
4155 }
4156
4157 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4158 /// caption in no group lifts, exactly as its own key always made it
4159 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4160 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4161 /// span out of its own lane, hole closed, captions and clips alike.
4162 /// `false` for a bad index.
4163 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4164 let Some(members) = self.group_of(lane, idx) else {
4165 return false;
4166 };
4167 if !members.alone() {
4168 return self.delete_members(&members);
4169 }
4170 self.lift_sub(lane, idx)
4171 }
4172
4173 /// The one whole-group delete both doors land in: every member's own span
4174 /// cut out of its own lane and the hole closed there -- clips and
4175 /// captions by the same law -- and nothing else on another lane moves,
4176 /// which is what keeps one member's ripple from dragging another
4177 /// member's lane out from under it. One snapshot, one undo step.
4178 fn delete_members(&mut self, members: &Members) -> bool {
4179 self.snapshot();
4180 for &(l, i) in &members.clips {
4181 let c = self.lanes[l].clips[i];
4182 ripple(&mut self.lanes, &[l], c.start, c.frames());
4183 }
4184 // The captions go by the same law their clip siblings do -- the span
4185 // out of its own lane, the hole closed -- and not by the lift a
4186 // *lone* caption's delete is: deleted with its group, the words after
4187 // it slide up with everything else, or the lane the group emptied is
4188 // the one lane the delete left a hole in. `ripple` is the one
4189 // mechanism (it clears the span and shifts the rest, clips and
4190 // captions alike); a sub lane holds no clips, so its other list is
4191 // untouched.
4192 for &(l, i) in &members.subs {
4193 let s = self.lanes[l].subs[i];
4194 ripple(&mut self.lanes, &[l], s.start, s.frames);
4195 }
4196 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4197 true
4198 }
4199
4200 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4201 #[cfg(test)]
4202 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4203 self.lane(lane)
4204 }
4205
4206 /// How many undo steps are stacked: what the sweep asks so "one op, one
4207 /// snapshot" is a count and not a guess.
4208 #[cfg(test)]
4209 pub(crate) fn history_len(&self) -> usize {
4210 self.history.len()
4211 }
4212
4213 /// Every part of the project that an edit can change, as comparable
4214 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4215 #[cfg(test)]
4216 pub(crate) fn parts(&self) -> SweepParts {
4217 SweepParts(
4218 self.sources.len(),
4219 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4220 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4221 )
4222 }
4223
4224 /// Restore every lane from before the last successful edit -- the clips and
4225 /// the lane list both. `false` when there is nothing left to undo.
4226 pub fn undo(&mut self) -> bool {
4227 match self.history.pop() {
4228 Some(prev) => {
4229 self.lanes = prev;
4230 true
4231 }
4232 None => false,
4233 }
4234 }
4235
4236 /// The project an export renders from: everything a render reads, with the
4237 /// undo history left behind. An export never walks the history back, and
4238 /// cloning it costs a copy of every lane list in the session -- this is
4239 /// taken on the UI thread, so it clones the lanes and the sources alone.
4240 pub fn export_snapshot(&self) -> Self {
4241 Self {
4242 sources: self.sources.clone(),
4243 lanes: self.lanes.clone(),
4244 eq: self.eq.clone(),
4245 color: self.color.clone(),
4246 history: Vec::new(),
4247 next_link: self.next_link,
4248 subtitles: self.subtitles.clone(),
4249 limiter: self.limiter,
4250 tone: self.tone,
4251 }
4252 }
4253
4254 /// Half-open `(source, start, end)` segments in *source* seconds, from
4255 /// `timeline_frame` to the end of the timeline -- the play list for the
4256 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4257 /// worker synthesises that many seconds of silence, which is what keeps the
4258 /// audio master clock counting across a hole instead of stalling on it.
4259 /// The first entry is partial when the position is mid-clip. Empty when the
4260 /// position is past the end or `fps` is not usable.
4261 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4262 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4263 }
4264
4265 /// [`segments_from`](Project::segments_from) for a named lane.
4266 pub fn lane_segments_from(
4267 &self,
4268 lane: Lane,
4269 timeline_frame: u32,
4270 fps: f64,
4271 ) -> Vec<(Option<usize>, f64, f64)> {
4272 if !(fps.is_finite() && fps > 0.0) {
4273 return Vec::new();
4274 }
4275 self.spans_from(lane, timeline_frame)
4276 .iter()
4277 .map(|span| match span.from {
4278 // A clip's window is in *source* seconds: where in the file it
4279 // reads from, which a delete before it never shifts. How many
4280 // source frames that is, is the span's own arithmetic -- at a
4281 // speed it is not the timeline length ([`Span::source_len`]).
4282 Some((source, in_frame)) => (
4283 Some(source),
4284 f64::from(in_frame) / fps,
4285 f64::from(in_frame + span.source_len()) / fps,
4286 ),
4287 // A gap has no file, so all it can say is how long it is.
4288 None => (None, 0.0, f64::from(span.len) / fps),
4289 })
4290 .collect()
4291 }
4292
4293 /// One play list per audio lane that *holds* something, in display order --
4294 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4295 /// what an export asks how many lanes it would have to mix.
4296 ///
4297 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4298 /// audio lane at all) still yields one all-gap list, so it plays silence
4299 /// against a master clock exactly as it did before there were lanes to
4300 /// count. Lanes with nothing on them are left out rather than mixed in as
4301 /// silence: they would cost a decode thread each and add zero.
4302 pub fn audio_segments_from(
4303 &self,
4304 timeline_frame: u32,
4305 fps: f64,
4306 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4307 self.audio_lanes()
4308 .into_iter()
4309 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4310 .collect()
4311 }
4312
4313 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4314 /// builds a play list for, in the same order. Public because everything
4315 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4316 /// which lane an mp4 export would copy -- has to read the very list the
4317 /// sound comes off, or the two answers drift apart (which is exactly how an
4318 /// `A2`-only project once exported silently, ledger).
4319 pub fn audio_lanes(&self) -> Vec<Lane> {
4320 let lanes: Vec<Lane> = self
4321 .lanes()
4322 .into_iter()
4323 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
4324 .collect();
4325 match lanes.is_empty() {
4326 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
4327 // no sound still plays silence against the master clock.
4328 true => vec![Lane::A1],
4329 false => lanes,
4330 }
4331 }
4332
4333 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
4334 /// segments plays at, and how long the timeline gives it: the same lanes in
4335 /// the same order, one entry per segment, `None` for a segment at real time
4336 /// -- which is every segment of a project nobody has speeded, and the path
4337 /// the audio worker leaves bit-identical.
4338 ///
4339 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
4340 /// the segment tuple is what every opener and a dozen tests speak, and a
4341 /// rate is not part of *which samples* a segment names.
4342 ///
4343 /// The seconds are what makes a resample exact: a segment's own window
4344 /// resolves to whole source frames, and dividing that by the rate would
4345 /// leave each clip a fraction of a frame short or long -- a drift that grows
4346 /// clip by clip. Told how much timeline it owes, the worker pads or trims
4347 /// the last few samples of each segment instead, so the sound stays locked
4348 /// to the picture however many speeded cuts it walks through.
4349 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
4350 self.audio_lanes()
4351 .into_iter()
4352 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
4353 .collect()
4354 }
4355
4356 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
4357 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4358 /// same walk, same `fps` refusal.
4359 pub fn lane_speeds_from(
4360 &self,
4361 lane: Lane,
4362 timeline_frame: u32,
4363 fps: f64,
4364 ) -> Vec<Option<Stretch>> {
4365 if !(fps.is_finite() && fps > 0.0) {
4366 return Vec::new();
4367 }
4368 self.spans_from(lane, timeline_frame)
4369 .iter()
4370 .map(|span| {
4371 (!span.speed.is_normal()).then(|| Stretch {
4372 step: span.speed.as_f64(),
4373 timeline_secs: f64::from(span.len) / fps,
4374 })
4375 })
4376 .collect()
4377 }
4378
4379 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
4380 /// segments plays through: the same lanes in the same order, one entry per
4381 /// segment, `None` where the segment is a gap or its clip plays flat.
4382 ///
4383 /// A parallel list rather than a fourth element of the segment tuple: that
4384 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
4385 /// and an effect is not part of *which samples* a segment names. A short
4386 /// list therefore means "flat from here on" rather than a length mismatch --
4387 /// see [`crate::AudioSession::open_mixed_streams_eq`].
4388 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
4389 self.audio_lanes()
4390 .into_iter()
4391 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
4392 .collect()
4393 }
4394
4395 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
4396 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4397 /// same walk, same `fps` refusal, so the two lists cannot come out different
4398 /// lengths.
4399 pub fn lane_eqs_from(
4400 &self,
4401 lane: Lane,
4402 timeline_frame: u32,
4403 fps: f64,
4404 ) -> Vec<Option<EqParams>> {
4405 if !(fps.is_finite() && fps > 0.0) {
4406 return Vec::new();
4407 }
4408 self.spans_from(lane, timeline_frame)
4409 .iter()
4410 // A span off a clip covers that clip's frames and no others, so its
4411 // own start names the clip -- the index a [`Span`] does not carry.
4412 .map(|span| {
4413 self.map(lane, span.start)
4414 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
4415 })
4416 .collect()
4417 }
4418
4419 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
4420 /// it has decided it will succeed -- a refusal must not cost an undo step.
4421 fn snapshot(&mut self) {
4422 if self.history.len() == HISTORY_CAP {
4423 self.history.remove(0);
4424 }
4425 self.history.push(self.lanes.clone());
4426 }
4427
4428 fn new_link(&mut self) -> u32 {
4429 let id = self.next_link;
4430 self.next_link = self.next_link.saturating_add(1);
4431 id
4432 }
4433
4434}
4435
4436/// The handle of every lane, in storage order -- the one definition of what
4437/// [`Lane::ord`] counts.
4438fn handles(lanes: &[LaneData]) -> Vec<Lane> {
4439 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
4440 lanes
4441 .iter()
4442 .map(|l| match l.kind {
4443 LaneKind::Video => {
4444 video += 1;
4445 Lane::new(LaneKind::Video, video - 1)
4446 }
4447 LaneKind::Audio => {
4448 audio += 1;
4449 Lane::new(LaneKind::Audio, audio - 1)
4450 }
4451 LaneKind::Subtitle => {
4452 subtitle += 1;
4453 Lane::new(LaneKind::Subtitle, subtitle - 1)
4454 }
4455 })
4456 .collect()
4457}
4458
4459/// The one law a caption re-time scales by: frame `f` moves about the held
4460/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
4461/// commits it, [`Project::speeded_playhead`] previews it -- both build their
4462/// [`TimelineMap`] piece from this single answer so the two cannot drift
4463/// apart by a frame the way they once did.
4464fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
4465 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
4466 .round()
4467 .clamp(0., f64::from(u32::MAX)) as u32
4468}
4469
4470/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
4471/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
4472/// a speed cannot be applied twice or forgotten in one of them.
4473fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
4474 // Clamped inside the clip's own range: rounding at a slow rate can put the
4475 // last timeline frame of a clip a frame past its out-point, and a source
4476 // frame outside the range is one the next clip owns.
4477 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
4478}
4479
4480/// Index of the clip covering `frame`, or `None` for a gap or past the end.
4481/// Binary search: the sorted-disjoint invariant is what makes it legal.
4482fn at(clips: &[Clip], frame: u32) -> Option<usize> {
4483 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
4484 (frame < clips[idx].end()).then_some(idx)
4485}
4486
4487/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
4488/// there would cut in two. A placement's own first frame is not inside it.
4489fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
4490 let idx = at(clips, frame)?;
4491 // ...and, on a speeded clip, one its rate can actually address
4492 // ([`Speed::split_at`]): a cut between two showings of one source frame
4493 // would leave halves that no longer add up to the clip that was cut.
4494 (frame > clips[idx].start)
4495 .then_some(idx)
4496 .filter(|&idx| split_source(&clips[idx], frame).is_some())
4497}
4498
4499/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
4500/// rate cannot address that frame.
4501fn split_source(c: &Clip, frame: u32) -> Option<u32> {
4502 c.speed
4503 .split_at(c.len(), frame - c.start)
4504 .map(|src| c.in_frame + src)
4505}
4506
4507/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
4508/// rejoin: they must touch there, and be consecutive frames of one source.
4509fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
4510 let idx = clips.iter().position(|c| c.end() == frame)?;
4511 let next = clips.get(idx + 1)?;
4512 let joined = clips[idx].len() + next.len();
4513 (next.start == frame
4514 && next.source == clips[idx].source
4515 && next.in_frame == clips[idx].out_frame
4516 // ...at one rate, and one that puts the rejoined clip back in exactly
4517 // the room the two took up: what a split could have produced, which is
4518 // all this undoes.
4519 && next.speed == clips[idx].speed
4520 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
4521 .then_some(idx)
4522}
4523
4524/// The lane invariant: sorted by `start`, no two placements overlapping, no
4525/// empty placement. Checked at every constructor and asserted after every
4526/// mutation -- the offset model is only tractable while it holds.
4527/// The one thing an equalizer setting may not be: a value the text format
4528/// cannot write and read back as itself. Checked wherever params come in, so
4529/// what an edit produces is always what a save writes and a load reads.
4530fn finite(params: &EqParams) -> bool {
4531 params
4532 .bands
4533 .iter()
4534 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
4535}
4536
4537/// The same for a colour grade: [`crate::color`] itself falls back to identity
4538/// on a non-finite value, but a value that cannot be written and read back as
4539/// itself has no business reaching the model.
4540fn color_finite(p: &ColorParams) -> bool {
4541 p.brightness.is_finite()
4542 && p.contrast.is_finite()
4543 && p.saturation.is_finite()
4544 && p.tint.is_finite()
4545}
4546
4547fn sorted_disjoint(clips: &[Clip]) -> bool {
4548 clips.iter().all(|c| c.out_frame > c.in_frame)
4549 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
4550}
4551
4552/// The very same invariant on a subtitle lane, in that lane's own two units:
4553/// sorted by `start`, no two placements overlapping, no empty placement at
4554/// either end. Asserted after every mutation, exactly as its twin is.
4555fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
4556 subs.iter()
4557 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
4558 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
4559}
4560
4561/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
4562/// the one conversion between a lane's clock and a cue's, and `0` for a rate
4563/// that is not one (every caller of this has already refused such a rate).
4564fn us_of(frames: i64, fps: f64) -> i64 {
4565 match fps.is_finite() && fps > 0.0 {
4566 true => ((frames as f64) / fps * 1e6).round() as i64,
4567 false => 0,
4568 }
4569}
4570
4571/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
4572/// dropping what is inside the hole, splitting what straddles it and trimming
4573/// what overlaps an edge. The windows follow the cut by proportion
4574/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
4575fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
4576 let mut out = Vec::with_capacity(subs.len() + 1);
4577 for s in subs.drain(..) {
4578 if s.end() <= start || s.start >= end {
4579 out.push(s);
4580 continue;
4581 }
4582 if s.start < start {
4583 out.push(SubClip {
4584 frames: start - s.start,
4585 out_us: s.window_at(start),
4586 // Both pieces lose the group id, for [`clear`]'s reason: one
4587 // id on two boxes of one lane is the one thing it may never
4588 // mean.
4589 link: None,
4590 ..s
4591 });
4592 }
4593 if s.end() > end {
4594 out.push(SubClip {
4595 start: end,
4596 frames: s.end() - end,
4597 in_us: s.window_at(end),
4598 link: None,
4599 ..s
4600 });
4601 }
4602 }
4603 *subs = out;
4604}
4605
4606/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
4607/// `len`, splitting a placement that straddles `at` so the two halves end up on
4608/// either side of the hole. A `len` of 0 is that split alone, which is what a
4609/// [`Project::split`] over a subtitle lane is.
4610fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
4611 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
4612 let s = subs[idx];
4613 let cut = s.window_at(at);
4614 subs[idx] = SubClip {
4615 frames: at - s.start,
4616 out_us: cut,
4617 link: None,
4618 ..s
4619 };
4620 subs.insert(
4621 idx + 1,
4622 SubClip {
4623 start: at,
4624 frames: s.end() - at,
4625 in_us: cut,
4626 link: None,
4627 ..s
4628 },
4629 );
4630 }
4631 for s in subs.iter_mut().filter(|s| s.start >= at) {
4632 s.start += len;
4633 }
4634}
4635
4636/// [`joinable`] for a subtitle lane: the first of the two placements a
4637/// [`Project::regroup`] at `frame` would rejoin. What a split could have
4638/// produced and nothing else -- they touch on the timeline, they read the same
4639/// track, and the second one's window carries on where the first's stopped.
4640fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
4641 let idx = subs.iter().position(|s| s.end() == frame)?;
4642 let next = subs.get(idx + 1)?;
4643 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
4644 .then_some(idx)
4645}
4646
4647/// How far one `edge` of the caption at `idx` may travel against its own lane's
4648/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
4649/// rate, which a caption *following* a group's trim does not have to be exact
4650/// about -- its own walls, its own one surviving frame, and nothing that needs
4651/// a clock.
4652fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
4653 let s = &subs[idx];
4654 match edge {
4655 Edge::Start => (
4656 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
4657 s.end() - 1,
4658 ),
4659 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
4660 }
4661}
4662
4663/// Move one `edge` of `s` to timeline frame `to`, its window following by the
4664/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
4665/// forwards and backwards. The caption a group's trim is carrying has no rate
4666/// of its own and needs none: what one frame of it is worth in microseconds is
4667/// the window it already shows over the frames it already takes.
4668fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
4669 let per_frame = s.window_us() / i64::from(s.frames.max(1));
4670 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
4671 match edge {
4672 Edge::Start => {
4673 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
4674 s.frames = s.end() - to;
4675 s.start = to;
4676 }
4677 Edge::End => {
4678 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
4679 s.frames = to - s.start;
4680 }
4681 }
4682 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
4683}
4684
4685/// The grouping invariant, checked in release at [`Project::from_parts`] and
4686/// asserted by the tests after every edit: a link id names **at most one**
4687/// placement per lane -- a clip on a media lane or a caption on a subtitle
4688/// one, whichever carries it. That is all "these move together" can mean now
4689/// that a group is assembled by hand: the members keep their own spans and
4690/// their own offsets, and what binds them is the id alone.
4691///
4692/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
4693/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
4694/// placements of one group may cover different frames -- the offset-preserving
4695/// group a hand builds with [`Project::group_all`], which a drag moves by one
4696/// delta rather than by one span.
4697///
4698/// A link no other lane carries is legal and is not an error: lifting one half
4699/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
4700/// timeline has to load again.
4701/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
4702/// asked by the sweep suite's universal law.
4703#[cfg(test)]
4704pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
4705 links_are_consistent(&p.lanes)
4706}
4707
4708fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
4709 let handles = handles(lanes);
4710 for (data, lane) in lanes.iter().zip(&handles) {
4711 for (i, c) in data.clips.iter().enumerate() {
4712 let Some(id) = c.link else { continue };
4713 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
4714 return Err(
4715 format!("link {id} names two clips in the {} lane", lane.label()).into(),
4716 );
4717 }
4718 }
4719 // ...and the same for the captions, in their own list on the same lane:
4720 // a subtitle lane holds no `Clip`, so this is the only list a caption's
4721 // id could be doubled on.
4722 for (i, s) in data.subs.iter().enumerate() {
4723 let Some(id) = s.link else { continue };
4724 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
4725 return Err(format!(
4726 "link {id} names two captions in the {} lane",
4727 lane.label()
4728 )
4729 .into());
4730 }
4731 }
4732 }
4733 Ok(())
4734}
4735
4736/// Removes the timeline frames `[start, end)` from `clips`: placements inside
4737/// it go, one straddling it is split in two, one overlapping an edge is
4738/// trimmed. Source frames follow the trim, so what is left plays what it always
4739/// played. Leaves the lane sorted and disjoint.
4740///
4741/// A piece the hole cut is no longer the take its group id names -- and both
4742/// halves of a straddled placement carrying that id would be the same id twice
4743/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
4744fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
4745 let mut out = Vec::with_capacity(clips.len() + 1);
4746 for c in clips.drain(..) {
4747 // Disjoint from the hole: untouched.
4748 if c.end() <= start || c.start >= end {
4749 out.push(c);
4750 continue;
4751 }
4752 // The head that survives in front of the hole -- as much source as fits
4753 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
4754 // which at real time is that room itself. Never *more*: a head that
4755 // outgrew its room would reach into the hole it is being cut out of,
4756 // which is exactly the overlap a slow clip punched at a frame its rate
4757 // cannot address used to leave (at 0.25x a single source frame is four
4758 // timeline frames, and three frames of room hold none of it). `None`
4759 // there means no remainder at all, and the piece simply goes.
4760 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
4761 && c.start < start
4762 {
4763 out.push(Clip {
4764 out_frame: c.in_frame + keep.min(c.len()),
4765 link: None,
4766 ..c
4767 });
4768 }
4769 // ...and the tail behind it, which keeps reading up to where it would
4770 // have: measured from its out-point for the head's reason, so what it
4771 // occupies still ends where the whole clip did -- and dropped whole on
4772 // the same `None`.
4773 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
4774 && c.end() > end
4775 {
4776 out.push(Clip {
4777 start: end,
4778 in_frame: c.out_frame - keep.min(c.len()),
4779 link: None,
4780 ..c
4781 });
4782 }
4783 }
4784 *clips = out;
4785}
4786
4787/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
4788/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
4789/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
4790/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
4791/// the caller.
4792fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
4793 for &i in on {
4794 let clips = &mut lanes[i].clips;
4795 clear(clips, at, at + len);
4796 for c in clips.iter_mut().filter(|c| c.start >= at) {
4797 c.start -= len;
4798 }
4799 debug_assert!(sorted_disjoint(clips));
4800 // The subtitle lanes close the hole with everything else: a caption
4801 // left standing where the picture it belongs to was cut out is the
4802 // desync a lane model exists to make impossible.
4803 let subs = &mut lanes[i].subs;
4804 sub_clear(subs, at, at + len);
4805 for s in subs.iter_mut().filter(|s| s.start >= at) {
4806 s.start -= len;
4807 }
4808 debug_assert!(subs_sorted_disjoint(subs));
4809 }
4810}
4811
4812/// Every lane, as the index list the two above take: what "the whole timeline"
4813/// is spelled as, and the scope [`Project::ripple_delete`] and
4814/// [`Project::split`] have always had.
4815fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
4816 (0..lanes.len()).collect()
4817}
4818
4819/// A caller's region list as a batch may use it: sorted by start, empty entries
4820/// dropped, and touching or overlapping entries merged into one.
4821///
4822/// Overlapping regions are the one thing a batch cannot take -- cutting the
4823/// second would cut frames the first already moved -- and a detector handing
4824/// back two that touch means one silence, not two cuts. Merged rather than
4825/// refused: this is arithmetic on a preview, not a user's mistake.
4826fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
4827 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
4828 sorted.sort_by_key(|&(at, _)| at);
4829 let mut out: Vec<(u32, u32)> = Vec::new();
4830 for (at, len) in sorted {
4831 let end = at.saturating_add(len);
4832 match out.last_mut() {
4833 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
4834 _ => out.push((at, len)),
4835 }
4836 }
4837 out
4838}
4839
4840/// Slides everything from `at` on later by `len`, splitting a placement that
4841/// straddles `at` so the two halves end up on either side of the hole. The
4842/// insert half of a rippling paste. The two halves lose the group id for the
4843/// reason [`clear`] gives.
4844fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
4845 if let Some(idx) = splittable(clips, at) {
4846 let mut tail = clips[idx];
4847 // The cut in *source* frames, at the clip's own rate. `splittable` has
4848 // already refused a frame the rate cannot address, which is why
4849 // [`Project::paste`] refuses one too rather than opening room inside a
4850 // clip that cannot be cut there.
4851 tail.in_frame = split_source(&tail, at).expect("splittable said so");
4852 tail.start = at;
4853 tail.link = None;
4854 clips[idx].out_frame = tail.in_frame;
4855 clips[idx].link = None;
4856 clips.insert(idx + 1, tail);
4857 }
4858 for c in clips.iter_mut().filter(|c| c.start >= at) {
4859 c.start += len;
4860 }
4861}
4862
4863/// Absolute, symlink-resolved when the file is reachable; the path as given
4864/// when it is not -- an unreadable path still deserves an index, it simply
4865/// dedups by spelling.
4866pub(crate) fn canonical(path: &Path) -> PathBuf {
4867 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
4868}
4869
4870#[cfg(test)]
4871mod tests {
4872 use super::*;
4873
4874 const FPS: f64 = 30.0;
4875 /// Never opened -- `Project` is pure data, so a path that does not exist is
4876 /// simply a path that dedups by spelling.
4877 const FILE: &str = "/nonexistent/a.mp4";
4878 const FILE2: &str = "/nonexistent/b.mp4";
4879
4880 /// A contiguous placement, group id ignored: what most assertions compare.
4881 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
4882 Clip {
4883 start,
4884 in_frame,
4885 out_frame,
4886 source,
4887 link: None,
4888 eq: None,
4889 color: None,
4890 fit: FitPolicy::default(),
4891 speed: Speed::NORMAL,
4892 }
4893 }
4894
4895 /// A recognisable equalizer setting: one peak band, `n` telling two of them
4896 /// apart -- which is what makes the table's dedup and its prune visible.
4897 fn band_at(n: u32) -> EqParams {
4898 EqParams {
4899 bands: vec![crate::eq::Band {
4900 freq_hz: 1000.0,
4901 gain_db: f64::from(n) as f32 * 1.5,
4902 q: 0.707,
4903 kind: crate::eq::BandKind::Peak,
4904 }],
4905 }
4906 }
4907
4908 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
4909 /// for the colour table.
4910 fn grade_at(n: u32) -> ColorParams {
4911 ColorParams {
4912 brightness: f64::from(n) as f32 * 0.05,
4913 ..Default::default()
4914 }
4915 }
4916
4917 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
4918 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
4919 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
4920 }
4921
4922 /// Every lane with its group ids blanked, for comparing shape.
4923 fn shape(p: &Project) -> Vec<Vec<Clip>> {
4924 p.lanes()
4925 .into_iter()
4926 .map(|l| {
4927 p.lane(l)
4928 .iter()
4929 .map(|c| Clip { link: None, ..*c })
4930 .collect()
4931 })
4932 .collect()
4933 }
4934
4935 /// The *source frame* every timeline frame reads, per lane -- the traversal
4936 /// a player performs. Deliberately not the clip index: a split changes which
4937 /// clip a frame belongs to, and nothing else.
4938 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
4939 (0..p.timeline_frames() + 2)
4940 .map(|f| {
4941 p.lanes()
4942 .into_iter()
4943 .map(|l| p.map(l, f).map(|(_, source)| source))
4944 .collect()
4945 })
4946 .collect()
4947 }
4948
4949 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
4950 /// fixture. Built through `split` so the constructor path is exercised too.
4951 fn three() -> Project {
4952 let mut p = Project::single(FILE, 9);
4953 assert!(p.split(3));
4954 assert!(p.split(5));
4955 assert_eq!(
4956 shape(&p),
4957 [
4958 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
4959 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
4960 ]
4961 );
4962 p
4963 }
4964
4965 #[test]
4966 fn single_is_the_whole_file_on_both_lanes() {
4967 let p = Project::single(FILE, 150);
4968 assert_eq!(p.clips().len(), 1);
4969 assert_eq!(p.lane(Lane::A1).len(), 1);
4970 assert_eq!(p.timeline_frames(), 150);
4971 assert_eq!(p.clip_spans(), vec![(0, 150)]);
4972 // grouped: video and audio carry the same link
4973 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
4974 assert!(p.clips()[0].link.is_some());
4975 // degenerate mapping: timeline == source
4976 assert_eq!(p.map_timeline(0), Some((0, 0)));
4977 assert_eq!(p.map_timeline(149), Some((0, 149)));
4978 assert_eq!(p.map_timeline(150), None);
4979 // never-empty invariant survives a bogus frame count
4980 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
4981 }
4982
4983 #[test]
4984 fn split_cuts_every_lane_and_regroups_it_back() {
4985 let mut p = Project::single(FILE, 9);
4986 let before = traversal(&p);
4987 let before_shape = shape(&p);
4988
4989 assert!(p.split(4));
4990 for l in p.lanes() {
4991 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
4992 }
4993 // The two sides are two groups, one per side, matching across the lanes.
4994 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
4995 assert_eq!(v[0].link, a[0].link);
4996 assert_eq!(v[1].link, a[1].link);
4997 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
4998 // A split changes no mapping, in either lane.
4999 assert_eq!(traversal(&p), before, "a split moves nothing");
5000
5001 assert!(p.regroup(4), "the inverse rejoins them");
5002 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5003 assert_eq!(traversal(&p), before);
5004 assert_eq!(
5005 p.lane(Lane::V1)[0].link,
5006 p.lane(Lane::A1)[0].link,
5007 "and the rejoined clip is one group again"
5008 );
5009 }
5010
5011 /// The music video's own path: the take comes apart into halves that carry
5012 /// ids of their own, one undo puts it back, and two clips over the same
5013 /// frames become one take again by hand.
5014 #[test]
5015 fn a_take_comes_apart_and_goes_back_together() {
5016 let mut p = Project::single(FILE, 9);
5017 let one = p.clips()[0].link.expect("a fresh project is one take");
5018 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5019
5020 // A third lane in the same group -- and the merge case with it: a
5021 // placement is in no group, and grouping it in leaves *one* group.
5022 let v2 = p.add_lane(LaneKind::Video);
5023 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5024 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
5025 p.group(Lane::V1, 0, v2, 0)
5026 .expect("the same frames, one lane over");
5027 let id = p.clips()[0].link.expect("still a group");
5028 assert!(
5029 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5030 "one id over the three, not two groups sharing a span"
5031 );
5032 links_are_consistent(&p.lanes).expect("one id, one span");
5033
5034 // Detached by the sound: every half of the group, not only the two.
5035 assert!(p.ungroup(Lane::A1, 0));
5036 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
5037 assert!(
5038 ids.iter().all(Option::is_some),
5039 "a half keeps an id of its own"
5040 );
5041 assert!(
5042 ids.iter()
5043 .enumerate()
5044 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
5045 "and no two halves are the same group any more: {ids:?}"
5046 );
5047 links_are_consistent(&p.lanes).expect("a lone id is legal");
5048
5049 // One snapshot for the whole detach.
5050 assert!(p.undo());
5051 assert!(
5052 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5053 "one undo puts the whole group back"
5054 );
5055
5056 // And back together by hand: the two the pointer named, and only them.
5057 assert!(p.ungroup(Lane::V1, 0));
5058 p.group(Lane::V1, 0, Lane::A1, 0)
5059 .expect("both cover [0, 9)");
5060 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
5061 assert_ne!(
5062 p.lane(v2)[0].link,
5063 p.lane(Lane::V1)[0].link,
5064 "the third half stayed detached"
5065 );
5066 links_are_consistent(&p.lanes).expect("one id, one span");
5067 }
5068
5069 /// What a group may not be, and what a detach has nothing to take apart --
5070 /// none of which may cost an undo step.
5071 #[test]
5072 fn a_group_is_one_span_and_one_clip_per_lane() {
5073 let mut p = three();
5074 let before = shape(&p);
5075 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
5076
5077 assert!(
5078 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
5079 "two clips of one lane are never one take"
5080 );
5081 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
5082 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
5083 assert!(
5084 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
5085 "{spans}"
5086 );
5087 assert!(
5088 spans.contains("trim them to matching bounds first"),
5089 "{spans}"
5090 );
5091 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
5092
5093 // A half nothing else is grouped with is already detached, a placement
5094 // is in no group at all, and an index that is not there has nothing to
5095 // detach either.
5096 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
5097 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
5098 assert!(p.lift(Lane::A1, 0));
5099 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
5100 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
5101
5102 // Two undos, one per edit: not one of the refusals pushed a snapshot.
5103 assert!(p.undo());
5104 assert!(p.undo());
5105 assert_eq!(shape(&p), before);
5106 }
5107
5108 /// Where a re-rate puts a playhead: the scene under the cursor stays the
5109 /// scene under the cursor, measured the way a viewer would -- the source
5110 /// frame playing at the playhead is the same frame after the write, at
5111 /// every playhead position the re-rate can catch one.
5112 #[test]
5113 fn a_re_rate_keeps_the_frame_under_the_playhead() {
5114 let caption = |start: u32, frames: u32| SubClip {
5115 start,
5116 frames,
5117 track: 0,
5118 in_us: 0,
5119 out_us: i64::from(frames) * 1_000_000,
5120 link: None,
5121 };
5122 let track = || SubtitleTrack {
5123 path: FILE.into(),
5124 track: None,
5125 language: "eng".into(),
5126 name: String::new(),
5127 label: "eng".into(),
5128 cues: Vec::new(),
5129 bitmap: false,
5130 refused: None,
5131 };
5132 // A group of a 300-frame clip and a caption offset 30 frames into it.
5133 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
5134 let s1 = p.add_lane(LaneKind::Subtitle);
5135 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
5136 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5137
5138 // The frame playing at `at`: which clip, and which source frame of it.
5139 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
5140 p.span_at(Lane::V1, at)
5141 .and_then(|s| s.from.map(|(source, from)| (source, from)))
5142 };
5143
5144 // Inside the held clip: the source frame under the playhead is the
5145 // same one after the re-rate, at 2x and at half speed both.
5146 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
5147 let at = 120;
5148 let before = playing(&p, at).expect("a clip under the playhead");
5149 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
5150 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
5151 .expect("room for it");
5152 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
5153 assert_eq!(before, after, "{what}: the same source frame plays");
5154 // ...and the write itself is untouched by the question.
5155 assert!(p.undo(), "{what}: one step back");
5156 }
5157
5158 // Past the group -- the clip ends at 300 and the caption at 270, so
5159 // from 300 on nothing is re-timed under the playhead: unmoved.
5160 for at in [300u32, 301, 1_000] {
5161 assert_eq!(
5162 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
5163 Some(at),
5164 "at {at}: outside every member, unmoved"
5165 );
5166 }
5167 // The boundary is exact: the held clip's own last frame (299) maps
5168 // to its new one (149 -- the last frame inside [0, 150), where the
5169 // shrunken clip's last source frame plays), and its first stays put.
5170 assert_eq!(
5171 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
5172 Some(149)
5173 );
5174 assert_eq!(
5175 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
5176 Some(0)
5177 );
5178 // A spot the caption shares with the clip maps by the clip (it is
5179 // what is *playing* there): the held clip's own proportion, which on
5180 // this fixture is also its head.
5181 assert_eq!(
5182 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
5183 Some(45),
5184 "the clip under the caption owns the spot"
5185 );
5186 }
5187
5188 /// A playhead inside another clip member of the group: that member keeps
5189 /// its own head, so the mapping is by its proportion and not the held
5190 /// clip's -- and the frame under the cursor is still the frame that was.
5191 #[test]
5192 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
5193 let mut p = Project::single(FILE, 300);
5194 // A second clip, grouped with the first but starting 300 later: the
5195 // head the group shares and its own differ by exactly that.
5196 let v2 = p.add_lane(LaneKind::Video);
5197 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
5198 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
5199 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
5200
5201 let at = 450; // inside the second member, 150 past its head
5202 let before = p.span_at(v2, at).and_then(|s| s.from);
5203 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
5204 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5205 .expect("room for it");
5206 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
5207 assert_eq!(before, after, "the second member's own frame plays");
5208 // ...and the mapping itself: 150 past its head halves, the head stays.
5209 assert_eq!(mapped, Some(375));
5210 }
5211
5212 /// The link counter a load seeds sits past every id the file names,
5213 /// captions included: a hand-grouped caption may carry the highest id there
5214 /// is, and a counter that read the clips alone would hand it to the next
5215 /// group that asked -- silently grouping the caption with clips it never
5216 /// met.
5217 #[test]
5218 fn the_link_counter_sits_past_a_caption_only_id() {
5219 let track = || SubtitleTrack {
5220 path: FILE.into(),
5221 track: None,
5222 language: "eng".into(),
5223 name: String::new(),
5224 label: "eng".into(),
5225 cues: Vec::new(),
5226 bitmap: false,
5227 refused: None,
5228 };
5229 let mut p = Project::single(FILE, 9);
5230 p.add_lane(LaneKind::Subtitle);
5231 let caption = SubClip {
5232 start: 0,
5233 frames: 6,
5234 track: 0,
5235 in_us: 0,
5236 out_us: 6_000_000,
5237 // The highest id in the file, and only a caption carries it.
5238 link: Some(1),
5239 };
5240 let mut p = p
5241 .with_subtitles(vec![track()])
5242 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
5243 .expect("a caption may carry the file's highest id");
5244
5245 // A new group on lanes the caption is not on mints the next id -- which
5246 // must not be the caption's.
5247 let v2 = p.add_lane(LaneKind::Video);
5248 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5249 p.group_all(&[(Lane::V1, 0), (v2, 0)])
5250 .expect("the clips group");
5251 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
5252 assert_ne!(
5253 minted,
5254 1,
5255 "the caption's id is not re-issued to clips"
5256 );
5257 assert_eq!(
5258 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
5259 Some(1),
5260 "the caption keeps its own group"
5261 );
5262 assert!(links_are_consistent(&p.lanes).is_ok());
5263 }
5264
5265 /// A rate re-times the caption members of the group by the ratio it gives
5266 /// the held clip: the span on the timeline compresses about the held clip's
5267 /// head, the words' own window untouched -- and one undo puts it back.
5268 #[test]
5269 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
5270 let caption = |start: u32, frames: u32| SubClip {
5271 start,
5272 frames,
5273 track: 0,
5274 in_us: 0,
5275 out_us: i64::from(frames) * 1_000_000,
5276 link: None,
5277 };
5278 let track = || SubtitleTrack {
5279 path: FILE.into(),
5280 track: None,
5281 language: "eng".into(),
5282 name: String::new(),
5283 label: "eng".into(),
5284 cues: Vec::new(),
5285 bitmap: false,
5286 refused: None,
5287 };
5288 let grouped = || {
5289 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5290 let s1 = p.add_lane(LaneKind::Subtitle);
5291 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5292 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5293 (p, s1)
5294 };
5295
5296 // An aligned take, doubled: the caption plays in half the frames.
5297 let (mut p, s1) = grouped();
5298 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5299 .expect("room for it");
5300 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
5301 let s = p.sub_lane(s1)[0];
5302 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
5303 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
5304 assert!(links_are_consistent(&p.lanes).is_ok());
5305 assert!(p.undo());
5306 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
5307
5308 // An offset group, slowed to half: the caption's *offset from the held
5309 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
5310 // 0.5x, and still ends where the clip does.
5311 let (mut p, s1) = grouped();
5312 p.lift_sub(s1, 0);
5313 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
5314 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5315 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
5316 .expect("room for it");
5317 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
5318 let s = p.sub_lane(s1)[0];
5319 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
5320 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
5321
5322 // A stretch that runs the caption into its neighbour is refused, by
5323 // lane and frame, and costs no undo step.
5324 let (mut p, s1) = grouped();
5325 p.lift_sub(s1, 0);
5326 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5327 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
5328 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5329 let history = p.history.len();
5330 let err = p
5331 .set_speed(Lane::V1, 0, Speed::from_permille(500))
5332 .unwrap_err()
5333 .to_string();
5334 assert!(
5335 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
5336 "{err}"
5337 );
5338 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
5339 }
5340
5341 /// The silence scan's speed-up re-times the captions on a scoped lane with
5342 /// everything else: the piece inside the region plays in the region's new
5343 /// frames, and what sits behind the region slides up with the clips.
5344 #[test]
5345 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
5346 let caption = |start: u32, frames: u32| SubClip {
5347 start,
5348 frames,
5349 track: 0,
5350 in_us: 0,
5351 out_us: i64::from(frames) * 1_000_000,
5352 link: None,
5353 };
5354 let track = || SubtitleTrack {
5355 path: FILE.into(),
5356 track: None,
5357 language: "eng".into(),
5358 name: String::new(),
5359 label: "eng".into(),
5360 cues: Vec::new(),
5361 bitmap: false,
5362 refused: None,
5363 };
5364 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5365 let s1 = p.add_lane(LaneKind::Subtitle);
5366 // Words over the region [30, 60) and words behind it.
5367 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5368 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
5369
5370 // The region [30, 60) plays at 4x: 30 frames become 8, everything
5371 // behind slides up 22.
5372 // The scope is what the card's Take row says, caption lane included.
5373 p.speed_regions(
5374 &[(30, 30)],
5375 Speed::from_permille(4000),
5376 &[Lane::V1, Lane::A1, s1],
5377 )
5378 .expect("the region speeds up");
5379 let subs = p.sub_lane(s1);
5380 assert_eq!(
5381 (subs[0].start, subs[0].frames),
5382 (30, 8),
5383 "the piece inside plays in the region's new frames"
5384 );
5385 assert_eq!(
5386 (subs[1].start, subs[1].frames),
5387 (38, 30),
5388 "the piece behind slides up by what the region gave back"
5389 );
5390 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
5391 }
5392
5393 /// [`Project::speeded_playhead`]'s caption arm fires only when the
5394 /// playhead is inside a caption member and outside every clip member --
5395 /// a shape every other fixture avoids by keeping its caption inside the
5396 /// held clip. Here the caption overhangs the clip's tail, and the
5397 /// playhead standing in that overhang is answered by the caption's own
5398 /// piece: it scales about the held clip's head by the held clip's own
5399 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
5400 #[test]
5401 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
5402 let caption = |start: u32, frames: u32| SubClip {
5403 start,
5404 frames,
5405 track: 0,
5406 in_us: 0,
5407 out_us: i64::from(frames) * 1_000_000,
5408 link: None,
5409 };
5410 let track = || SubtitleTrack {
5411 path: FILE.into(),
5412 track: None,
5413 language: "eng".into(),
5414 name: String::new(),
5415 label: "eng".into(),
5416 cues: Vec::new(),
5417 bitmap: false,
5418 refused: None,
5419 };
5420 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5421 let s1 = p.add_lane(LaneKind::Subtitle);
5422 // The caption spans [80, 100) -- ten frames past the clip's own end
5423 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
5424 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
5425 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5426 // At 2x the clip halves to 45 frames; the overhang frame 95, which
5427 // no clip member's old span reaches, is the caption's own question:
5428 // half of 95 is 47.5, rounded to 48.
5429 assert_eq!(
5430 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
5431 Some(48),
5432 "the overhang frame answers through the caption's own piece"
5433 );
5434 }
5435
5436 /// `write_speed` and `speeded_playhead` are two questions of the SAME
5437 /// map ([`map`]'s architecture law): a caption's landed span comes from
5438 /// the map's own ends, and the playhead standing at the caption's own
5439 /// last frame before the write has to land exactly where the write put
5440 /// it -- across clip lengths and rates that round differently, and an
5441 /// odd-length caption straddling the clip's own tail edge, the corner
5442 /// where `write_speed` used to answer a frame short.
5443 #[test]
5444 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
5445 let caption = |start: u32, frames: u32| SubClip {
5446 start,
5447 frames,
5448 track: 0,
5449 in_us: 0,
5450 out_us: i64::from(frames) * 1_000_000,
5451 link: None,
5452 };
5453 let track = || SubtitleTrack {
5454 path: FILE.into(),
5455 track: None,
5456 language: "eng".into(),
5457 name: String::new(),
5458 label: "eng".into(),
5459 cues: Vec::new(),
5460 bitmap: false,
5461 refused: None,
5462 };
5463 for &len in &[90u32, 91, 177, 300, 301] {
5464 for &permille in &[500u16, 2000, 2500, 3000] {
5465 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
5466 let s1 = p.add_lane(LaneKind::Subtitle);
5467 // An odd-length caption straddling the clip's tail edge: its
5468 // own last frame lands past the held clip.
5469 let c_start = len.saturating_sub(3);
5470 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
5471 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5472 let speed = Speed::from_permille(permille);
5473 let last = c_start + 7 - 1;
5474 let mapped = p
5475 .speeded_playhead(Lane::V1, 0, speed, last)
5476 .expect("the caption is there");
5477 if p.set_speed(Lane::V1, 0, speed).is_err() {
5478 continue; // a refusal changes nothing: not this law's cell
5479 }
5480 let landed = p.sub_lane(s1)[0];
5481 if permille >= 1000 {
5482 // A speed-up compresses the timeline: many old frames
5483 // share one new frame, so the caption's own last old
5484 // frame lands flush with the write's own boundary --
5485 // the exact law [`write_speed`]'s worked drift-fix case
5486 // is stated against.
5487 assert_eq!(
5488 mapped,
5489 landed.end() - 1,
5490 "len {len} permille {permille}: the playhead at the caption's own \
5491 last frame lands where the write actually put it"
5492 );
5493 } else {
5494 // A slow-down expands it: one old frame becomes several
5495 // new ones, and `apply` answers where that frame's own
5496 // block *starts*, not where the caption's last new
5497 // frame (the end of that same block) sits -- a
5498 // one-frame gap inherent to the piece's own semantics,
5499 // not a drift between the two callers. Both still have
5500 // to agree the answer sits inside the caption the write
5501 // actually landed.
5502 assert!(
5503 (landed.start..landed.end()).contains(&mapped),
5504 "len {len} permille {permille}: the playhead lands inside the \
5505 caption the write actually put ({landed:?}), got {mapped}"
5506 );
5507 }
5508 }
5509 }
5510 }
5511
5512 /// A grouped caption's cues re-time with its clip: the placement's window
5513 /// crossed the timeline at its own proportion before any rate, and a
5514 /// re-rate changes that proportion (the frames compress, the window does
5515 /// not). A cue eight seconds into a window played at 2x crosses the screen
5516 /// four seconds in -- and at unity every cue lands exactly where it always
5517 /// did, byte for byte.
5518 #[test]
5519 fn a_grouped_captions_cues_re_time_with_its_clip() {
5520 let track = SubtitleTrack {
5521 path: FILE.into(),
5522 track: None,
5523 language: "eng".into(),
5524 name: String::new(),
5525 label: "eng".into(),
5526 cues: vec![crate::subtitle::Cue {
5527 start_us: 8_000_000,
5528 end_us: 9_000_000,
5529 text: "late line".into(),
5530 image: None,
5531 }],
5532 bitmap: false,
5533 refused: None,
5534 };
5535 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
5536 let s1 = p.add_lane(LaneKind::Subtitle);
5537 // Ten seconds of the track over ten seconds of timeline: unity.
5538 p.place_sub(
5539 s1,
5540 0,
5541 SubClip {
5542 start: 0,
5543 frames: 300,
5544 track: 0,
5545 in_us: 0,
5546 out_us: 10_000_000,
5547 link: None,
5548 },
5549 )
5550 .expect("placed");
5551
5552 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
5553 let unity = p.sub_lane_cues(s1, FPS);
5554 assert_eq!(
5555 unity
5556 .iter()
5557 .map(|c| (c.start_us, c.end_us, &*c.text))
5558 .collect::<Vec<_>>(),
5559 [(8_000_000, 9_000_000, "late line")],
5560 "a unity placement maps exactly as it always did"
5561 );
5562
5563 // Grouped with the clip and re-rated to 2x: the same window now crosses
5564 // in half the time, so the cue at 8s of it lands 4s in.
5565 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5566 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5567 .expect("room for it");
5568 let re_timed = p.sub_lane_cues(s1, FPS);
5569 assert_eq!(
5570 re_timed
5571 .iter()
5572 .map(|c| (c.start_us, c.end_us))
5573 .collect::<Vec<_>>(),
5574 [(4_000_000, 4_500_000)],
5575 "the cue crosses with the clip's new rate"
5576 );
5577 }
5578
5579 /// A video arriving on a timeline of words mutates none of them: the
5580 /// import's rippling insert used to open room on the subtitle lanes too,
5581 /// splitting a caption it landed inside and sliding the rest behind the
5582 /// video -- the hand asked for an add, and got a cut it never made. The
5583 /// words keep their own clock; co-travel is what a group is for.
5584 #[test]
5585 fn an_arriving_clip_never_touches_the_captions() {
5586 let caption = |start: u32, frames: u32| SubClip {
5587 start,
5588 frames,
5589 track: 0,
5590 in_us: i64::from(start) * 1_000_000 / 30,
5591 out_us: i64::from(start + frames) * 1_000_000 / 30,
5592 link: None,
5593 };
5594 let track = || SubtitleTrack {
5595 path: FILE.into(),
5596 track: None,
5597 language: "eng".into(),
5598 name: String::new(),
5599 label: "eng".into(),
5600 cues: Vec::new(),
5601 bitmap: false,
5602 refused: None,
5603 };
5604 // A timeline of words alone: 60 frames of caption, no media clips.
5605 let mut p = Project::single(FILE, 60)
5606 .with_subtitles(vec![track()]);
5607 for l in [Lane::V1, Lane::A1] {
5608 while !p.lane(l).is_empty() {
5609 p.lift(l, 0);
5610 }
5611 }
5612 let s1 = p.add_lane(LaneKind::Subtitle);
5613 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
5614 let before = p.sub_lane(s1).to_vec();
5615
5616 // The video lands BEFORE the caption's span: nothing moves.
5617 let vid = clip(0, 0, 30, 0);
5618 assert!(p.paste(0, vid), "the video goes down at the head");
5619 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
5620
5621 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
5622 // byte the placement the hand made.
5623 assert!(p.paste(15, vid), "a second video lands inside the caption");
5624 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
5625 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
5626 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
5627 assert!(links_are_consistent(&p.lanes).is_ok());
5628 }
5629
5630 /// The region's caption pieces re-time by mapped boundaries forced apart:
5631 /// rounding start and length independently can land two cues on one frame,
5632 /// and the artifact is clamped -- one frame each, in order, none past the
5633 /// region's new end -- never an overlap on the lane.
5634 #[test]
5635 fn a_regions_caption_pieces_never_round_onto_one_another() {
5636 let caption = |start: u32, frames: u32| SubClip {
5637 start,
5638 frames,
5639 track: 0,
5640 in_us: 0,
5641 out_us: i64::from(frames) * 1_000_000,
5642 link: None,
5643 };
5644 let track = |n| SubtitleTrack {
5645 path: FILE.into(),
5646 track: None,
5647 language: "eng".into(),
5648 name: String::new(),
5649 label: format!("eng{n}"),
5650 cues: Vec::new(),
5651 bitmap: false,
5652 refused: None,
5653 };
5654 // Three lanes, one repro shape each: adjacent one-frame cues, a
5655 // three-frame pair, and the region's last cue against the first
5656 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
5657 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
5658 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
5659 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
5660 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
5661 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
5662 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
5663 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
5664 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
5665
5666 let mut scope = vec![Lane::V1, Lane::A1];
5667 scope.extend(lanes.iter().copied());
5668 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
5669 .expect("the region speeds up");
5670 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
5671 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
5672 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
5673 };
5674 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
5675 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
5676 // and the walk pushes the second to where the first ends.
5677 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
5678 // The last cue of the region ends exactly where the region now does
5679 // (frame 15), and the caption behind it lands on that same frame:
5680 // touching, never overlapping.
5681 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
5682 for &lane in &lanes {
5683 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
5684 }
5685 }
5686
5687 /// The scope law names a caption half too: a scoped cut that would move one
5688 // track of a group whose caption sits outside the scope is refused.
5689 #[test]
5690 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
5691 let caption = |start: u32, frames: u32| SubClip {
5692 start,
5693 frames,
5694 track: 0,
5695 in_us: 0,
5696 out_us: i64::from(frames) * 1_000_000,
5697 link: None,
5698 };
5699 let track = || SubtitleTrack {
5700 path: FILE.into(),
5701 track: None,
5702 language: "eng".into(),
5703 name: String::new(),
5704 label: "eng".into(),
5705 cues: Vec::new(),
5706 bitmap: false,
5707 refused: None,
5708 };
5709 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5710 let s1 = p.add_lane(LaneKind::Subtitle);
5711 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5712 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5713
5714 // The subtitle lane is not in the scope, so the group's caption half
5715 // sits outside it: refused, in the law's own words.
5716 let err = p
5717 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
5718 .unwrap_err()
5719 .to_string();
5720 assert!(
5721 err.contains("is one take with the S1 caption at frame 0"),
5722 "{err}"
5723 );
5724
5725 // ...and with the caption's lane in the scope, the cut carries it:
5726 // the words over the hole go, and the words behind slide up.
5727 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
5728 .expect("the whole group is in the scope");
5729 let subs = p.sub_lane(s1);
5730 assert_eq!(
5731 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
5732 [(0, 10), (10, 75)],
5733 "the caption is cut and shifted with the clips"
5734 );
5735 }
5736
5737 /// The caption a hand groups: `group_all` over clips *and* a caption, the
5738 /// mates riding along, the offsets kept, the refusals in words.
5739 #[test]
5740 fn a_hand_built_group_holds_clips_and_a_caption() {
5741 let caption = |start: u32, frames: u32| SubClip {
5742 start,
5743 frames,
5744 track: 0,
5745 in_us: 0,
5746 out_us: i64::from(frames) * 1_000_000,
5747 link: None,
5748 };
5749 let track = || SubtitleTrack {
5750 path: FILE.into(),
5751 track: None,
5752 language: "eng".into(),
5753 name: String::new(),
5754 label: "eng".into(),
5755 cues: Vec::new(),
5756 bitmap: false,
5757 refused: None,
5758 };
5759 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5760 let v2 = p.add_lane(LaneKind::Video);
5761 let s1 = p.add_lane(LaneKind::Subtitle);
5762 // A layer at its own offset, and a caption over the head of the take.
5763 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
5764 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
5765
5766 // Too few, one lane twice, and an index that is not there: words, no
5767 // snapshot.
5768 let history = p.history.len();
5769 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
5770 assert!(p
5771 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
5772 .unwrap_err()
5773 .to_string()
5774 .contains("V1 is picked twice"));
5775 assert!(p
5776 .group_all(&[(Lane::V1, 0), (s1, 9)])
5777 .unwrap_err()
5778 .to_string()
5779 .contains("no subtitle 9"));
5780 assert_eq!(p.history.len(), history, "refusals cost no undo step");
5781
5782 // The group: the picture, the layer, and the caption -- and the sound
5783 // the picture was already grouped with comes along unasked.
5784 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
5785 .expect("three picks, three lanes");
5786 let id = p.lane(Lane::V1)[0].link.expect("grouped");
5787 for lane in [Lane::V1, Lane::A1, v2] {
5788 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
5789 }
5790 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
5791 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
5792 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
5793 assert!(links_are_consistent(&p.lanes).is_ok());
5794 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
5795
5796 // ...and one undo takes it apart again.
5797 assert!(p.undo());
5798 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
5799
5800 // Detach names a caption like it names a clip: every member an id of
5801 // its own, which is never `None` (see `ungroup`).
5802 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
5803 assert!(p.ungroup(s1, 0));
5804 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
5805 assert!(loose_sub.is_some() && loose_clip.is_some());
5806 assert_ne!(loose_sub, loose_clip);
5807 assert!(links_are_consistent(&p.lanes).is_ok());
5808 }
5809
5810 /// Two captions on one sub lane, each already grouped with a *different*
5811 /// clip: `group_all` over both those clips would merge the two existing
5812 /// groups into one id and leave both captions on `s1` carrying it --
5813 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
5814 /// group closes. Refused by name, and nothing moves.
5815 #[test]
5816 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
5817 let caption = |start: u32, frames: u32| SubClip {
5818 start,
5819 frames,
5820 track: 0,
5821 in_us: 0,
5822 out_us: i64::from(frames) * 1_000_000,
5823 link: None,
5824 };
5825 let track = || SubtitleTrack {
5826 path: FILE.into(),
5827 track: None,
5828 language: "eng".into(),
5829 name: String::new(),
5830 label: "eng".into(),
5831 cues: Vec::new(),
5832 bitmap: false,
5833 refused: None,
5834 };
5835 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5836 let v2 = p.add_lane(LaneKind::Video);
5837 let s1 = p.add_lane(LaneKind::Subtitle);
5838 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
5839 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
5840 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5841 // V1 grouped with the first caption, v2 with the second -- two
5842 // separate groups, each already one member per lane.
5843 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5844 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
5845 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
5846
5847 let history = p.history.len();
5848 let err = p
5849 .group_all(&[(Lane::V1, 0), (v2, 0)])
5850 .unwrap_err()
5851 .to_string();
5852 assert!(err.contains("one placement per lane"), "{err}");
5853 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
5854 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
5855 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
5856 assert!(links_are_consistent(&p.lanes).is_ok());
5857 }
5858
5859 /// A split hands the caption of a group the same ids it hands the clips:
5860 /// the left halves keep the group, the right halves share a fresh one.
5861 #[test]
5862 fn a_split_cuts_a_grouped_caption_with_its_clips() {
5863 let caption = |start: u32, frames: u32| SubClip {
5864 start,
5865 frames,
5866 track: 0,
5867 in_us: 0,
5868 out_us: i64::from(frames) * 1_000_000,
5869 link: None,
5870 };
5871 let track = || SubtitleTrack {
5872 path: FILE.into(),
5873 track: None,
5874 language: "eng".into(),
5875 name: String::new(),
5876 label: "eng".into(),
5877 cues: Vec::new(),
5878 bitmap: false,
5879 refused: None,
5880 };
5881 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5882 let s1 = p.add_lane(LaneKind::Subtitle);
5883 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
5884 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5885 let take = p.lane(Lane::V1)[0].link.expect("the group id");
5886
5887 assert!(p.split(4));
5888 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
5889 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
5890 assert_eq!(left.frames, 4);
5891 assert_eq!(
5892 right.link,
5893 p.lane(Lane::V1)[1].link,
5894 "the caption's tail shares the clips' fresh id"
5895 );
5896 assert_ne!(right.link, Some(take));
5897 assert!(links_are_consistent(&p.lanes).is_ok());
5898
5899 // Regroup at the seam restores the take, caption included.
5900 assert!(p.regroup(4));
5901 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
5902 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
5903 }
5904
5905 /// Deleting a member of a hand-built group takes the group: every
5906 /// member's own span out of its own lane, hole closed -- the lanes may
5907 /// end up out of step, which is what one undo restores together.
5908 #[test]
5909 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
5910 let caption = |start: u32, frames: u32| SubClip {
5911 start,
5912 frames,
5913 track: 0,
5914 in_us: 0,
5915 out_us: i64::from(frames) * 1_000_000,
5916 link: None,
5917 };
5918 let track = || SubtitleTrack {
5919 path: FILE.into(),
5920 track: None,
5921 language: "eng".into(),
5922 name: String::new(),
5923 label: "eng".into(),
5924 cues: Vec::new(),
5925 bitmap: false,
5926 refused: None,
5927 };
5928 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
5929 let s1 = p.add_lane(LaneKind::Subtitle);
5930 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
5931 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5932 // A neighbour on a lane the group does not touch.
5933 let v2 = p.add_lane(LaneKind::Video);
5934 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
5935
5936 // By the picture or by the caption, the same whole-group delete.
5937 assert!(p.delete_sub_in(s1, 0));
5938 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
5939 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
5940 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
5941 assert!(links_are_consistent(&p.lanes).is_ok());
5942 assert!(p.undo(), "one step puts the group back");
5943 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
5944 }
5945
5946 /// The delete law, one statement for every anchor: a caption deleted
5947 /// WITH its group ripples its lane exactly as its clip siblings do --
5948 /// the hole closes and what follows slides up -- while a caption lifted
5949 /// alone leaves its gap, as it always has. And the delete of a grouped
5950 /// clip takes the group from whichever member was clicked.
5951 #[test]
5952 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
5953 let caption = |start: u32, frames: u32| SubClip {
5954 start,
5955 frames,
5956 track: 0,
5957 in_us: 0,
5958 out_us: i64::from(frames) * 1_000_000,
5959 link: None,
5960 };
5961 let track = || SubtitleTrack {
5962 path: FILE.into(),
5963 track: None,
5964 language: "eng".into(),
5965 name: String::new(),
5966 label: "eng".into(),
5967 cues: Vec::new(),
5968 bitmap: false,
5969 refused: None,
5970 };
5971 // V+A+S grouped, with a second caption BEHIND the group's caption:
5972 // closing the hole is what the second caption's position says.
5973 let group = || {
5974 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5975 let s1 = p.add_lane(LaneKind::Subtitle);
5976 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
5977 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
5978 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5979 (p, s1)
5980 };
5981
5982 // Deleted by the picture: all three lanes close.
5983 let (mut p, s1) = group();
5984 assert!(p.delete_in(Lane::V1, 0));
5985 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
5986 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
5987 assert_eq!(
5988 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
5989 [60],
5990 "the caption's lane closed by its own span: the follower slid up"
5991 );
5992 assert!(p.undo(), "one step");
5993 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
5994
5995 // By the sound: the same whole-group delete.
5996 let (mut p, s1) = group();
5997 assert!(p.delete_in(Lane::A1, 0));
5998 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
5999 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6000
6001 // By the caption itself: the same again.
6002 let (mut p, s1) = group();
6003 assert!(p.delete_sub_in(s1, 0));
6004 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6005 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6006 assert!(links_are_consistent(&p.lanes).is_ok());
6007
6008 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6009 // unchanged.
6010 let (mut p, s1) = group();
6011 assert!(p.ungroup(s1, 0), "the caption stands alone");
6012 assert!(p.lift_sub(s1, 0));
6013 assert_eq!(
6014 p.sub_lane(s1)[0].start, 90,
6015 "the follower stayed put: a lone caption's lift is a gap"
6016 );
6017 }
6018
6019 /// Dragging a grouped caption carries its clips, one delta for all of them
6020 /// -- and a caption in no group refuses an overlap exactly as it always did.
6021 #[test]
6022 fn dragging_a_grouped_caption_carries_its_group() {
6023 let caption = |start: u32, frames: u32| SubClip {
6024 start,
6025 frames,
6026 track: 0,
6027 in_us: 0,
6028 out_us: i64::from(frames) * 1_000_000,
6029 link: None,
6030 };
6031 let track = || SubtitleTrack {
6032 path: FILE.into(),
6033 track: None,
6034 language: "eng".into(),
6035 name: String::new(),
6036 label: "eng".into(),
6037 cues: Vec::new(),
6038 bitmap: false,
6039 refused: None,
6040 };
6041 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6042 let s1 = p.add_lane(LaneKind::Subtitle);
6043 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6044 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6045
6046 // Same lane, further along: everyone moves by the same eight frames.
6047 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
6048 assert_eq!(p.sub_lane(s1)[0].start, 10);
6049 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
6050 assert!(links_are_consistent(&p.lanes).is_ok());
6051
6052 // ...and an ungrouped caption is the caption it always was.
6053 assert!(p.ungroup(s1, 0));
6054 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
6055 let s1 = q.add_lane(LaneKind::Subtitle);
6056 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
6057 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
6058 assert!(q
6059 .move_sub(s1, 0, s1, 3)
6060 .unwrap_err()
6061 .to_string()
6062 .contains("already covers"));
6063 }
6064
6065 /// A trim carries a group's caption by the same delta as its clips, clamped
6066 /// to the caption's own walls -- the offsets between the members survive.
6067 #[test]
6068 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
6069 let caption = |start: u32, frames: u32| SubClip {
6070 start,
6071 frames,
6072 track: 0,
6073 in_us: 0,
6074 out_us: i64::from(frames) * 1_000_000,
6075 link: None,
6076 };
6077 let track = || SubtitleTrack {
6078 path: FILE.into(),
6079 track: None,
6080 language: "eng".into(),
6081 name: String::new(),
6082 label: "eng".into(),
6083 cues: Vec::new(),
6084 bitmap: false,
6085 refused: None,
6086 };
6087 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6088 let s1 = p.add_lane(LaneKind::Subtitle);
6089 // The caption sits two frames into the take and ends one early. The
6090 // source runs past the clip, or there is no tail to pull out.
6091 let src = &[20];
6092 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
6093 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6094
6095 // The tail goes out by three: the clip to 12, the caption to 11.
6096 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
6097 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
6098 assert_eq!(
6099 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
6100 (2, 11),
6101 "the caption follows by the delta"
6102 );
6103 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
6104
6105 // The head comes in by two: everyone's start moves two along.
6106 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
6107 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
6108 assert!(links_are_consistent(&p.lanes).is_ok());
6109 }
6110
6111 #[test]
6112 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
6113 let mut p = three();
6114 let before = shape(&p);
6115 assert!(!p.split(0), "timeline 0 has nothing before it");
6116 assert!(!p.split(3), "existing boundary");
6117 assert!(!p.split(5), "existing boundary");
6118 assert!(!p.split(9), "one past the last frame");
6119 assert!(!p.split(1_000));
6120 assert_eq!(shape(&p), before);
6121 // one undo lands before the *second* split, so the refusals pushed nothing
6122 assert!(p.undo());
6123 assert_eq!(p.clips().len(), 2, "refused splits push no history");
6124
6125 // ...and a frame that is a gap in both lanes has nothing to split.
6126 let mut p = three();
6127 assert!(p.lift(Lane::V1, 1));
6128 assert!(p.lift(Lane::A1, 1));
6129 assert!(!p.split(4), "a gap is not a clip");
6130 }
6131
6132 #[test]
6133 fn regroup_refuses_what_a_split_could_not_have_made() {
6134 let mut p = three();
6135 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
6136 assert!(p.regroup(5));
6137 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
6138 // A boundary with a gap on one side, and one where the sources do not
6139 // meet, are both refused.
6140 let mut p = three();
6141 assert!(p.lift(Lane::V1, 1));
6142 assert!(p.lift(Lane::A1, 1));
6143 assert!(!p.regroup(3), "nothing starts at 3 any more");
6144 let mut p = three();
6145 for l in p.lanes() {
6146 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
6147 }
6148 assert!(!p.regroup(3), "source 100 does not follow source 3");
6149 assert!(!p.regroup(0), "nothing ends at 0");
6150 assert!(!p.regroup(1_000));
6151 }
6152
6153 #[test]
6154 fn map_and_spans_sweep_every_boundary() {
6155 let p = three();
6156 assert_eq!(p.timeline_frames(), 9);
6157 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
6158 // contiguous source here, so the clip index is what actually moves
6159 let expect = [
6160 (0, (0, 0)),
6161 (1, (0, 1)),
6162 (2, (0, 2)),
6163 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
6164 (4, (1, 4)),
6165 (5, (2, 5)),
6166 (6, (2, 6)),
6167 (7, (2, 7)),
6168 (8, (2, 8)),
6169 ];
6170 for (t, want) in expect {
6171 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
6172 }
6173 assert_eq!(p.map_timeline(9), None);
6174 // A span is the rest of the clip from where it was asked about.
6175 assert_eq!(
6176 p.span_at(Lane::V1, 6),
6177 Some(Span {
6178 start: 6,
6179 len: 3,
6180 from: Some((0, 6)),
6181 speed: Speed::NORMAL
6182 })
6183 );
6184 assert_eq!(p.span_at(Lane::V1, 9), None);
6185 }
6186
6187 /// The fit policy is one byte *in* the clip rather than an index into a
6188 /// table like the eq and the grade: there is nothing for a table to share.
6189 /// It costs the clip nothing at all -- the fields before it (a `usize`
6190 /// source and two `Option<u16>`s) already left the struct padded to 40
6191 /// bytes, and the byte landed in that padding. This is the assert that says
6192 /// so: a clip that grew a word grew every undo snapshot and every clipboard
6193 /// copy with it.
6194 #[test]
6195 fn a_fit_policy_costs_the_clip_no_word() {
6196 assert_eq!(
6197 std::mem::size_of::<Clip>(),
6198 40,
6199 "Clip changed size: {} bytes",
6200 std::mem::size_of::<Clip>()
6201 );
6202 }
6203
6204 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
6205 /// anything in `three()` so it is recognisable wherever it lands.
6206 const PASTED: Clip = Clip {
6207 start: 0,
6208 in_frame: 100,
6209 out_frame: 102,
6210 source: 0,
6211 link: None,
6212 eq: None,
6213 color: None,
6214 fit: FitPolicy::Fit,
6215 speed: Speed::NORMAL,
6216 };
6217
6218 #[test]
6219 fn paste_mid_clip_splits_around_it() {
6220 let mut p = three();
6221 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
6222 assert_eq!(p.timeline_frames(), 11);
6223 assert_eq!(
6224 shape(&p)[0],
6225 vec![
6226 clip(0, 0, 3, 0),
6227 clip(3, 3, 5, 0),
6228 clip(5, 5, 6, 0),
6229 clip(6, 100, 102, 0),
6230 clip(8, 6, 9, 0),
6231 ]
6232 );
6233 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
6234 // The pasted frames are exactly where they were asked for, and the
6235 // split-off remainder resumes after them.
6236 assert_eq!(p.map_timeline(6), Some((3, 100)));
6237 assert_eq!(p.map_timeline(7), Some((3, 101)));
6238 assert_eq!(p.map_timeline(8), Some((4, 6)));
6239 }
6240
6241 #[test]
6242 fn paste_at_boundary_zero_and_end() {
6243 let mut p = three();
6244 assert!(p.paste(3, PASTED), "existing boundary: no split");
6245 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
6246 assert_eq!(p.map_timeline(3), Some((1, 100)));
6247
6248 let mut p = three();
6249 assert!(p.paste(0, PASTED));
6250 assert_eq!(p.map_timeline(0), Some((0, 100)));
6251 assert_eq!(p.map_timeline(2), Some((1, 0)));
6252
6253 // At the end: appended, there being nothing in front to leave black.
6254 let mut p = three();
6255 assert!(p.paste(9, PASTED));
6256 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
6257 // Past it: down on the frame it was asked for, black in front of it --
6258 // a row let go on the open bed lands under the ghost that promised it.
6259 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
6260 assert!(p.paste(1_000, PASTED));
6261 assert_eq!(p.timeline_frames(), 1_002);
6262 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
6263 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
6264
6265 // An empty clip is the one thing refused, and it pushes no history.
6266 let mut p = three();
6267 assert!(!p.paste(4, clip(0, 7, 7, 0)));
6268 assert_eq!(p.clips().len(), 3);
6269 }
6270
6271 /// The data-loss paste: a clip of a source with no picture used to land on
6272 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
6273 /// carried it was refused on the way back in ("a box with a larger size").
6274 #[test]
6275 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
6276 let mut p = three();
6277 let wav = p.import("/nonexistent/song.wav", 0);
6278 let copied = Clip {
6279 source: wav,
6280 ..PASTED
6281 };
6282 assert!(p.paste(3, copied));
6283 // The room is opened on every lane, or the two would slide apart...
6284 assert_eq!(p.timeline_frames(), 11);
6285 assert_eq!(
6286 shape(&p)[0],
6287 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
6288 "the video lane got room and nothing else"
6289 );
6290 // ...but the clip itself only reaches the lane that can play it.
6291 assert_eq!(
6292 shape(&p)[1],
6293 vec![
6294 clip(0, 0, 3, 0),
6295 clip(3, 100, 102, wav),
6296 clip(5, 3, 5, 0),
6297 clip(7, 5, 9, 0)
6298 ]
6299 );
6300 // A source with a picture is unchanged: still the grouped pair.
6301 let mut p = three();
6302 assert!(p.paste(3, PASTED));
6303 assert_eq!(shape(&p)[0], shape(&p)[1]);
6304 }
6305
6306 /// A hand-written file may hold a clip that ends at the very last frame
6307 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
6308 /// to wrap its start round to the front of the lane: an overlap in debug, a
6309 /// project no reload would accept in release.
6310 #[test]
6311 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
6312 let far = clip(u32::MAX - 90, 0, 90, 0);
6313 let parts = |c: Clip| {
6314 Project::from_parts(
6315 vec![Source::new(FILE, 0)],
6316 two(vec![c], vec![c]),
6317 Vec::new(),
6318 Vec::new(),
6319 )
6320 .expect("valid parts")
6321 };
6322 let mut p = parts(far);
6323 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
6324 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
6325 assert!(!p.undo(), "...and pushes no history either");
6326 assert!(
6327 !p.paste(u32::MAX, PASTED),
6328 "appending has nowhere to go either: the timeline ends at the last frame"
6329 );
6330 // With room for exactly those frames the same paste is taken.
6331 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
6332 assert!(p.paste(0, PASTED));
6333 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
6334 }
6335
6336 #[test]
6337 fn paste_undoes_in_one_step() {
6338 let mut p = three();
6339 let before = shape(&p);
6340 assert!(p.paste(6, PASTED));
6341 assert!(p.undo());
6342 assert_eq!(shape(&p), before, "a paste is one undo step");
6343 }
6344
6345 #[test]
6346 fn a_copy_outlives_the_clip_it_came_from() {
6347 let mut p = three();
6348 let copied = p.clips()[1]; // [3,5)
6349 assert!(p.delete(1));
6350 // Just a frame range: the source is still on disk either way.
6351 assert!(p.paste(0, copied));
6352 assert_eq!(p.map_timeline(0), Some((0, 3)));
6353 assert_eq!(p.timeline_frames(), 9);
6354 }
6355
6356 #[test]
6357 fn delete_closes_the_gap_on_both_lanes() {
6358 let mut p = three();
6359 assert!(p.delete(1));
6360 assert_eq!(p.timeline_frames(), 7);
6361 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
6362 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
6363 // timeline 3 used to be source 3; the gap closed so it is source 5 now
6364 assert_eq!(p.map_timeline(3), Some((1, 5)));
6365 assert_eq!(p.map_timeline(6), Some((1, 8)));
6366 assert_eq!(p.map_timeline(7), None);
6367 }
6368
6369 #[test]
6370 fn delete_first_last_and_only() {
6371 let mut p = three();
6372 assert!(p.delete(0));
6373 assert_eq!(p.map_timeline(0), Some((0, 3)));
6374 assert_eq!(p.timeline_frames(), 6);
6375
6376 let mut p = three();
6377 assert!(p.delete(2));
6378 assert_eq!(p.timeline_frames(), 5);
6379 assert_eq!(p.map_timeline(4), Some((1, 4)));
6380
6381 assert!(!p.delete(2), "index past the end");
6382 assert!(p.delete(1));
6383 assert!(p.delete(0), "and the last remaining clip goes too");
6384 assert_eq!(p.clips().len(), 0);
6385 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
6386 assert!(!p.delete(0), "there is nothing left to delete");
6387 assert!(p.undo(), "one gesture, one undo");
6388 assert_eq!(p.clips().len(), 1);
6389 }
6390
6391 /// The offset model's point: one lane loses a clip, the other does not move.
6392 #[test]
6393 fn a_lift_leaves_a_gap_and_moves_nothing() {
6394 let mut p = three();
6395 let video_before = shape(&p)[0].clone();
6396 assert!(p.lift(Lane::A1, 1));
6397 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
6398 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
6399 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
6400 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
6401 assert_eq!(p.map(Lane::A1, 4), None);
6402 assert_eq!(
6403 p.span_at(Lane::A1, 3),
6404 Some(Span {
6405 start: 3,
6406 len: 2,
6407 from: None,
6408 speed: Speed::NORMAL
6409 })
6410 );
6411 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
6412 assert!(p.undo());
6413 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
6414 }
6415
6416 #[test]
6417 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
6418 let mut p = three();
6419 assert!(p.lift(Lane::A1, 2));
6420 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
6421 assert_eq!(
6422 p.span_at(Lane::A1, 5),
6423 Some(Span {
6424 start: 5,
6425 len: 4,
6426 from: None,
6427 speed: Speed::NORMAL
6428 }),
6429 "the audio lane holds silence to the end of the picture"
6430 );
6431 assert_eq!(p.span_at(Lane::A1, 9), None);
6432 // Every lane covers the timeline exactly, gaps included.
6433 for l in p.lanes() {
6434 let spans = p.spans_from(l, 0);
6435 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
6436 assert_eq!(spans[0].start, 0);
6437 }
6438 }
6439
6440 /// The timeline is emptiable: the last placement comes off like any other,
6441 /// the project holds "nothing on any lane" as a state, and one undo per
6442 /// gesture brings it back.
6443 #[test]
6444 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
6445 let mut p = Project::single(FILE, 9);
6446 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
6447 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
6448 assert_eq!(p.timeline_frames(), 0);
6449 assert_eq!(p.composite_span_at(0), None, "nothing to show");
6450 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
6451 assert!(!p.lift(Lane::A1, 0), "index past the end");
6452 assert!(p.undo(), "and the last lift comes back");
6453 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
6454 // A saved-and-loaded empty timeline is a project like any other, and it
6455 // still names the file its frame rate came from.
6456 assert!(p.lift(Lane::V1, 0));
6457 let (sources, lanes, eq, color) = p.without_orphan_sources();
6458 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
6459 let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
6460 assert_eq!(back.timeline_frames(), 0);
6461 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
6462 }
6463
6464 /// What a keyboard selection walks: one answer per lane, gaps included --
6465 /// the composite's own answer is one lane's and cannot say what the audio
6466 /// lane holds under the same playhead.
6467 #[test]
6468 fn lane_clip_at_answers_for_each_lane_separately() {
6469 let mut p = Project::single(FILE, 9);
6470 assert!(p.split(3), "both lanes split");
6471 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
6472 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
6473 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
6474 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
6475 // A gap on one lane leaves the other's clip selectable there.
6476 assert!(p.lift(Lane::A1, 0));
6477 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
6478 assert_eq!(
6479 p.lane_clip_at(Lane::A1, 3),
6480 Some(0),
6481 "indices moved with it"
6482 );
6483 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
6484 // A lane that is not there is not a panic.
6485 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
6486 }
6487
6488 #[test]
6489 fn place_overwrites_only_its_own_lane() {
6490 let mut p = three();
6491 let audio_before = shape(&p)[1].clone();
6492 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
6493 // is trimmed, nothing shifts.
6494 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
6495 assert_eq!(
6496 shape(&p)[0],
6497 vec![
6498 clip(0, 0, 3, 0),
6499 clip(3, 3, 4, 0),
6500 clip(4, 100, 102, 0),
6501 clip(6, 6, 9, 0),
6502 ]
6503 );
6504 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
6505 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
6506
6507 // Placed inside one clip, it splits it in two.
6508 let mut p = Project::single(FILE, 9);
6509 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
6510 assert_eq!(
6511 shape(&p)[0],
6512 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
6513 );
6514 // ...and placed past the end it makes a gap, which is the whole point.
6515 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
6516 assert_eq!(p.timeline_frames(), 22);
6517 assert_eq!(
6518 p.span_at(Lane::V1, 9),
6519 Some(Span {
6520 start: 9,
6521 len: 11,
6522 from: None,
6523 speed: Speed::NORMAL
6524 })
6525 );
6526 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
6527 }
6528
6529 /// A file with sound let go over a further video track: both halves go down,
6530 /// on the same frames, and the audio row is added when the `+ V` button left
6531 /// the project without one. One undo takes the lane and both clips back.
6532 #[test]
6533 fn a_take_placed_on_a_layer_lands_with_its_sound() {
6534 let mut p = three();
6535 let v2 = p.add_lane(LaneKind::Video);
6536 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
6537
6538 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
6539 let a2 = Lane::new(LaneKind::Audio, 1);
6540 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
6541 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
6542 assert_eq!(p.lane(v2)[0].start, 4);
6543 assert_eq!(p.lane(v2)[0].end(), 6);
6544 assert_eq!(
6545 p.lane(v2)[0].link,
6546 p.lane(a2)[0].link,
6547 "one take, not two placements"
6548 );
6549 assert!(p.lane(v2)[0].link.is_some());
6550 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
6551 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
6552
6553 // The pair overwrites its own two lanes and nothing else, exactly as a
6554 // one-lane place does.
6555 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
6556 assert_eq!(p.lane(v2), p.lane(a2));
6557 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
6558 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
6559
6560 assert!(p.undo(), "one step for the second pair");
6561 assert_eq!(p.lane(v2).len(), 1);
6562 assert!(p.undo(), "one step for the first pair *and* its lane");
6563 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
6564 assert!(p.lane(v2).is_empty());
6565
6566 // Refusals cost nothing: sound placed alone is `place`'s door.
6567 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
6568 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
6569 assert!(
6570 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
6571 "a lane that is not there"
6572 );
6573 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
6574 }
6575
6576 /// The drag between tracks: let go at the frames it already covers the clip
6577 /// keeps them, one undo takes it back, and every way it can be refused
6578 /// leaves the project untouched.
6579 #[test]
6580 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
6581 let v2 = Lane::new(LaneKind::Video, 1);
6582 let mut p = three();
6583 assert_eq!(p.add_lane(LaneKind::Video), v2);
6584 let before = shape(&p);
6585
6586 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
6587 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
6588 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
6589 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
6590 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
6591 // One snapshot: a single undo, and the lane list survives it.
6592 assert!(p.undo());
6593 assert_eq!(shape(&p), before);
6594
6595 // A lane that is not there, the lane and frame it is already at, an
6596 // index that is not there, and a move across kinds: all refused,
6597 // nothing changed.
6598 let history = p.history.len();
6599 for (from, idx, to, start) in [
6600 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
6601 (Lane::V1, 1, Lane::V1, 3),
6602 (Lane::V1, 9, v2, 3),
6603 (Lane::V1, 1, Lane::A1, 3),
6604 (Lane::A1, 1, v2, 3),
6605 ] {
6606 assert!(
6607 !p.move_clip(from, idx, to, start),
6608 "{from:?} {idx} -> {to:?} at {start}"
6609 );
6610 }
6611 assert_eq!(shape(&p), before);
6612 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
6613
6614 // Landing on another clip is refused rather than overwriting it: the
6615 // pointer named the lane, never the take already sitting there.
6616 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
6617 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
6618 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
6619 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
6620 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
6621 }
6622
6623 /// The drag *along* a track, which is the one every other editor has: the
6624 /// clip lands on the frame the pointer let it go at, and stops dead against
6625 /// the neighbour rather than overwriting it.
6626 #[test]
6627 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
6628 let sources = vec![Source::new(FILE, 0)];
6629 let lanes = vec![
6630 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
6631 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
6632 ];
6633 let mut p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
6634 let before = shape(&p);
6635
6636 // Into the gap, exactly where it was let go -- nothing else moves.
6637 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
6638 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
6639 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
6640 // Dragged past the clip in front of it: clamped to its wall, laid end
6641 // to end with it, never over it.
6642 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
6643 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
6644 // One undo per drag, and both of them together are the state it started
6645 // in -- the frames each clip plays never changed.
6646 assert!(p.undo() && p.undo());
6647 assert_eq!(shape(&p), before);
6648
6649 // A drop that changes nothing is a click, not an edit.
6650 let history = p.history.len();
6651 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
6652 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
6653 }
6654
6655 /// A drag carries the whole take: the sound half travels exactly as far as
6656 /// the picture does, and the tighter of their two walls stops both.
6657 #[test]
6658 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
6659 let mut p = three();
6660 assert!(
6661 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
6662 "room to the right"
6663 );
6664 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
6665 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
6666 // Something in the sound's way, and nothing at all in the picture's.
6667 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
6668 let before = shape(&p);
6669
6670 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
6671 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
6672 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
6673 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6674 assert!(p.undo());
6675 assert_eq!(shape(&p), before, "one undo for the whole take");
6676 }
6677
6678 /// The drag that does both at once -- another lane *and* another frame --
6679 /// which is what a pointer let go over a lane always names.
6680 #[test]
6681 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
6682 let v2 = Lane::new(LaneKind::Video, 1);
6683 let mut p = three();
6684 assert_eq!(p.add_lane(LaneKind::Video), v2);
6685
6686 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
6687 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
6688 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
6689 assert_eq!(
6690 p.lane(Lane::A1)[2].start,
6691 20,
6692 "its sound travelled the same distance"
6693 );
6694 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6695 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
6696 }
6697
6698 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
6699 /// [`three`] cuts up all nine of its frames.
6700 const SRC: &[u32] = &[9];
6701
6702 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
6703 /// else on the lane moves, and every wall stops the edge rather than
6704 /// refusing the gesture.
6705 #[test]
6706 fn trimming_the_tail_stops_at_every_wall() {
6707 let mut p = three();
6708
6709 // Pulled in: a gap opens behind it and the clip after it stays put.
6710 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
6711 assert_eq!(
6712 shape(&p)[0],
6713 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
6714 );
6715 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
6716 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
6717
6718 // ...and back out, no further than the clip behind it.
6719 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
6720 assert_eq!(
6721 shape(&p)[0][1],
6722 clip(3, 3, 5, 0),
6723 "stopped at the neighbour"
6724 );
6725 assert!(
6726 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
6727 "already at the wall"
6728 );
6729
6730 // One frame of clip always survives, however far back the pointer went.
6731 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
6732 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
6733
6734 // The last clip has no neighbour, so what stops it is the file: nine
6735 // frames is nine frames.
6736 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
6737 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
6738 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
6739 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
6740 // A source nobody told us the length of may not grow at all -- an
6741 // out-point past the end of a file is a save that will not open again.
6742 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
6743 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
6744 }
6745
6746 /// The head pulled in takes the in-point with it -- what stays plays what it
6747 /// always played -- and stops at the source's own first frame.
6748 #[test]
6749 fn trimming_the_head_moves_the_in_point() {
6750 let mut p = three();
6751 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
6752 assert_eq!(
6753 shape(&p)[0][0],
6754 clip(2, 2, 3, 0),
6755 "two frames off the front"
6756 );
6757 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
6758 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
6759 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
6760 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
6761 // One frame survives here too.
6762 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
6763 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
6764
6765 // A clip that does not begin at its source's first frame: its head goes
6766 // back to source frame 0 and not one frame further.
6767 let mut p = Project::single(FILE, 9);
6768 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
6769 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
6770 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
6771 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
6772 }
6773
6774 /// A clip whose in-point is *past* its own start -- what a ripple delete
6775 /// leaves, the piece in front of it gone and this one slid back to frame 0
6776 /// carrying the in-point the cut gave it. Its head has more source behind it
6777 /// than the timeline has room for, and the timeline's own first frame is the
6778 /// wall: asking is not an overflow, and the answer is 0.
6779 #[test]
6780 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
6781 let mut p = Project::single(FILE, 9);
6782 assert!(p.split(5));
6783 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
6784 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
6785
6786 assert_eq!(
6787 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
6788 Some((0, 3)),
6789 "back to frame 0 at most, and one frame of clip always survives"
6790 );
6791 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
6792 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
6793 assert_eq!(
6794 shape(&p)[0],
6795 vec![clip(2, 7, 9, 0)],
6796 "the in-point followed"
6797 );
6798 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
6799 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
6800 }
6801
6802 /// A still is trimmed from its head exactly as it is from its tail: it has
6803 /// no earlier frame to walk an in-point back to, so the wall is the length
6804 /// the caller's table allows it, measured back from the tail. Measured from
6805 /// the in-point -- which a placed picture has at 0 -- its left edge could
6806 /// never be dragged outwards at all.
6807 #[test]
6808 fn a_stills_head_stretches_out_like_its_tail() {
6809 const STILL: &str = "/nonexistent/card.png";
6810 /// What a still is held to, as `PlaybackSession` fills the table in.
6811 const CAP: &[u32] = &[60];
6812
6813 let mut p = Project::single(STILL, 20);
6814 assert!(p.lift(Lane::A1, 0), "a picture is silent");
6815 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
6816 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
6817
6818 // A source with no entry in the table may not grow, here as at the tail.
6819 assert_eq!(
6820 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
6821 Some((100, 119)),
6822 "a length nobody told us buys no head room"
6823 );
6824 assert_eq!(
6825 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
6826 Some((60, 119)),
6827 "back to a whole cap's worth, one frame of clip surviving"
6828 );
6829 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
6830 assert_eq!(
6831 shape(&p)[0][0],
6832 clip(80, 0, 40, 0),
6833 "twenty frames longer, and still read from the source's first frame"
6834 );
6835 // Past the cap is clamped, exactly as the tail is -- not refused.
6836 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
6837 assert_eq!(
6838 shape(&p)[0][0],
6839 clip(60, 0, 60, 0),
6840 "a cap's worth, no more"
6841 );
6842 // ...and the clip in front is the nearer wall of the two: no head trim
6843 // may open an overlap.
6844 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
6845 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
6846 assert_eq!(
6847 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
6848 Some((85, 119)),
6849 "up to the neighbour's last frame and not over it"
6850 );
6851 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
6852 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
6853 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
6854 }
6855
6856 /// Linked halves trim as one: a link is one span on however many lanes, so
6857 /// the sound follows the picture's edge -- and the tightest wall of the two
6858 /// is what stops both.
6859 #[test]
6860 fn linked_halves_trim_together() {
6861 let mut p = three();
6862 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
6863 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
6864
6865 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
6866 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
6867 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
6868 assert!(
6869 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
6870 "either half drags it"
6871 );
6872 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
6873 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6874
6875 // Something in the way on the *audio* lane stops the picture's tail as
6876 // well: the group can only go as far as its tightest member.
6877 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
6878 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
6879 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
6880 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
6881 links_are_consistent(&p.lanes).expect("still one span");
6882 }
6883
6884 /// A whole drag is one undo step -- the front-end commits once, at the
6885 /// release -- and an edge asked to stay where it is costs none at all.
6886 #[test]
6887 fn a_trim_is_one_undo_step() {
6888 let mut p = three();
6889 let before = shape(&p);
6890 let history = p.history.len();
6891
6892 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
6893 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
6894 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
6895 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
6896 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
6897 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
6898
6899 assert!(p.undo());
6900 assert_eq!(shape(&p), before, "both halves back, in one step");
6901 }
6902
6903 /// A moved half stays in its group: a link names a span, not a lane, so the
6904 /// picture on `V2` is still the same take as the sound under it on `A1`.
6905 #[test]
6906 fn move_clip_keeps_the_group() {
6907 let v2 = Lane::new(LaneKind::Video, 1);
6908 let mut p = three();
6909 p.add_lane(LaneKind::Video);
6910 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
6911 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
6912 assert!(p.move_clip(Lane::V1, 1, v2, 3));
6913 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
6914 links_are_consistent(&p.lanes).expect("one id per lane, one span");
6915 assert_eq!(
6916 p.lane(v2)[0].start,
6917 p.lane(Lane::A1)[1].start,
6918 "and still covers the same span as its sound"
6919 );
6920 }
6921
6922 #[test]
6923 fn ripple_delete_spans_partial_clips() {
6924 let mut p = three();
6925 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
6926 assert!(p.ripple_delete(2, 4));
6927 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
6928 assert_eq!(shape(&p)[1], shape(&p)[0]);
6929 assert_eq!(p.timeline_frames(), 5);
6930 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
6931 assert!(p.undo());
6932 assert_eq!(shape(&p), shape(&three()));
6933 // One that takes everything is a delete like any other: the timeline
6934 // empties, and the undo it cost brings it back whole.
6935 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
6936 assert_eq!(p.timeline_frames(), 0);
6937 assert!(
6938 !p.ripple_delete(0, 100),
6939 "and a delete with nothing left to take is not an undo step"
6940 );
6941 assert!(p.undo());
6942 assert_eq!(shape(&p), shape(&three()));
6943 }
6944
6945 #[test]
6946 fn undo_restores_exactly() {
6947 let mut p = three();
6948 let after_splits = shape(&p);
6949 assert!(p.delete(1));
6950 assert!(p.undo());
6951 assert_eq!(shape(&p), after_splits);
6952
6953 // walk all the way back through both splits, then run dry
6954 assert!(p.undo());
6955 assert_eq!(p.clips().len(), 2);
6956 assert!(p.undo());
6957 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
6958 assert!(!p.undo(), "empty history");
6959 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
6960 }
6961
6962 /// Past the cap the *oldest* step goes, so a long session undoes exactly
6963 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
6964 #[test]
6965 fn history_stops_at_the_cap() {
6966 let mut p = Project::single(FILE, 400);
6967 for frame in 1..=150 {
6968 assert!(p.split(frame), "split {frame} is an edit");
6969 }
6970 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
6971 for step in 0..HISTORY_CAP {
6972 assert!(p.undo(), "undo {step} is inside the cap");
6973 }
6974 assert!(!p.undo(), "and the 101st has nothing left to take");
6975 // 100 undos off 150 splits is the timeline after the 50th: the older
6976 // steps were dropped, not the newer ones.
6977 assert_eq!(p.clips().len(), 51);
6978 }
6979
6980 /// Undo/redo by hand across a split must never merge two takes into one
6981 /// group by reusing an id.
6982 #[test]
6983 fn group_ids_are_never_reused() {
6984 let mut p = Project::single(FILE, 9);
6985 assert!(p.split(3));
6986 let first = p.clips()[1].link;
6987 assert!(p.undo());
6988 assert!(p.split(5));
6989 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
6990 }
6991
6992 #[test]
6993 fn segments_from_reads_the_audio_lane() {
6994 let p = three();
6995 // mid-clip: partial first segment, whole clips after it
6996 assert_eq!(
6997 p.segments_from(4, FPS),
6998 vec![
6999 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7000 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7001 ]
7002 );
7003 // on a boundary: nothing partial
7004 assert_eq!(
7005 p.segments_from(3, FPS),
7006 vec![
7007 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
7008 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7009 ]
7010 );
7011 // from the top: one entry per clip
7012 assert_eq!(p.segments_from(0, FPS).len(), 3);
7013 // last clip only
7014 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
7015 // past the end / unusable fps
7016 assert!(p.segments_from(9, FPS).is_empty());
7017 assert!(p.segments_from(0, 0.0).is_empty());
7018 assert!(p.segments_from(0, f64::NAN).is_empty());
7019 }
7020
7021 #[test]
7022 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
7023 let mut p = three();
7024 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
7025 assert_eq!(
7026 p.segments_from(0, FPS),
7027 vec![
7028 (Some(0), 0.0, 3.0 / 30.0),
7029 (None, 0.0, 2.0 / 30.0),
7030 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7031 ]
7032 );
7033 // The list still covers exactly the timeline: that is what stops the
7034 // master clock stalling at the hole.
7035 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7036 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
7037 // Starting inside the gap trims the silence, not the clip after it.
7038 assert_eq!(
7039 p.segments_from(4, FPS),
7040 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
7041 );
7042 // ...and a lane that is nothing but gap is a run of silence.
7043 assert!(p.lift(Lane::A1, 0));
7044 assert!(p.lift(Lane::A1, 0));
7045 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
7046 }
7047
7048 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
7049 /// of source 0 then [0,4) of source 1.
7050 fn two_sources() -> Project {
7051 let mut p = three();
7052 let s = p.import(FILE2, 0);
7053 assert_eq!(s, 1);
7054 assert!(p.append_clip(s, 4));
7055 p
7056 }
7057
7058 #[test]
7059 fn import_dedups_and_appends() {
7060 let mut p = Project::single(FILE, 9);
7061 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
7062 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
7063 assert_eq!(p.import(FILE2, 0), 1);
7064 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
7065 // ...but the same file on another audio stream is another source: it is
7066 // what a clip names, and a clip plays exactly one stream.
7067 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
7068 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
7069 assert_eq!(p.sources()[2].audio_stream, 1);
7070 assert!(p.append_clip(2, 4), "a stream entry is placeable");
7071 assert!(p.undo());
7072 assert_eq!(p.sources().len(), 3);
7073 assert!(!p.append_clip(3, 5), "unknown source index");
7074 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
7075
7076 // Two spellings of one real file are one source: this is the case the
7077 // raw-path comparison above would get wrong.
7078 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
7079 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
7080 let mut p = Project::single(here, 9);
7081 assert_eq!(p.import(detour, 0), 0);
7082 assert_eq!(p.sources().len(), 1);
7083 }
7084
7085 #[test]
7086 fn append_clip_is_one_undo_step() {
7087 let mut p = two_sources();
7088 assert_eq!(p.timeline_frames(), 13);
7089 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
7090 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
7091 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
7092 assert!(p.undo());
7093 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
7094 assert_eq!(
7095 p.sources().len(),
7096 2,
7097 "the orphan source entry stays -- indexes are forever"
7098 );
7099 // ...and it is still usable, so a redo-by-hand costs no reimport.
7100 assert!(p.append_clip(1, 0));
7101 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
7102 }
7103
7104 #[test]
7105 fn edits_carry_the_source_along() {
7106 let mut p = two_sources();
7107 // A split inside the second source splits into two source-1 clips.
7108 assert!(p.split(11));
7109 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
7110 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
7111
7112 // A source-1 clip pasted into source-0 territory keeps its file, and so
7113 // does the source-0 half that got split off around it.
7114 let copied = p.clips()[4];
7115 assert!(p.paste(1, copied));
7116 assert_eq!(p.clips()[1].source, 1);
7117 assert_eq!(p.clips()[1].in_frame, 2);
7118 assert_eq!(p.clips()[2].source, 0);
7119 assert!(p.undo());
7120 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
7121 }
7122
7123 #[test]
7124 fn segments_from_names_the_source() {
7125 let p = two_sources();
7126 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
7127 assert_eq!(
7128 p.segments_from(4, FPS),
7129 vec![
7130 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7131 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7132 (Some(1), 0.0, 4.0 / 30.0),
7133 ]
7134 );
7135 // Mid-clip in source 1: only that source is left.
7136 assert_eq!(
7137 p.segments_from(10, FPS),
7138 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
7139 );
7140 assert!(p.segments_from(13, FPS).is_empty());
7141 // Segments still cover exactly the timeline across the join.
7142 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7143 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
7144 }
7145
7146 #[test]
7147 fn segments_follow_deletes_and_fps() {
7148 let mut p = three();
7149 assert!(p.delete(0));
7150 // source seconds, not timeline: deleting the head does not shift them
7151 let segs = p.segments_from(0, 25.0);
7152 assert_eq!(
7153 segs,
7154 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
7155 );
7156 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
7157 assert!(
7158 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
7159 "segments must cover exactly the timeline: {played}"
7160 );
7161 }
7162
7163 #[test]
7164 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
7165 // Import a second file, undo it: source 1 is now an orphan.
7166 let mut p = two_sources();
7167 assert!(p.undo());
7168 let (sources, lanes, eq, color) = p.without_orphan_sources();
7169 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
7170 assert!(eq.is_empty(), "and a project with no equalizer writes none");
7171 assert!(color.is_empty(), "nor a colour it never graded with");
7172 assert_eq!(
7173 lanes,
7174 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
7175 "the clips are untouched"
7176 );
7177
7178 // Three sources where only the middle one is orphaned: the survivors
7179 // renumber, and the clips follow.
7180 let mut p = Project::single(FILE, 9);
7181 assert_eq!(p.import(FILE2, 0), 1);
7182 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
7183 assert!(p.append_clip(2, 4));
7184 let (sources, lanes, eq, color) = p.without_orphan_sources();
7185 assert_eq!(
7186 sources,
7187 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
7188 );
7189 assert_eq!(
7190 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
7191 [0, 1]
7192 );
7193 // ...and what comes out is loadable, with the same timeline.
7194 let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts");
7195 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
7196 assert_eq!(reloaded.sources().len(), 2);
7197 }
7198
7199 /// Taking a file out of the library: refused by name -- lanes and counts --
7200 /// while a clip still plays from it, and once nothing does, the entry goes
7201 /// and every clip that indexed past it is renumbered onto the short list.
7202 #[test]
7203 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
7204 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
7205 // plus a second stream of FILE as source 2 with a take of its own.
7206 let mut p = two_sources();
7207 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
7208 assert!(p.append_clip(2, 4));
7209
7210 let refusal = p
7211 .remove_source(1)
7212 .expect_err("a source with clips on it cannot go")
7213 .to_string();
7214 assert!(refusal.contains(FILE2), "names the file: {refusal}");
7215 assert!(
7216 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
7217 "names the lanes holding it: {refusal}"
7218 );
7219 assert!(refusal.contains("still plays"), "{refusal}");
7220 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
7221 assert_eq!(shape(&p)[0][3].source, 1);
7222
7223 // Delete FILE2's take -- the whole span, on every lane -- and the entry
7224 // is free to go. Source 2's clips become source 1's.
7225 assert!(p.delete_in(Lane::V1, 3));
7226 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
7227 p.remove_source(1).expect("nothing plays FILE2 any more");
7228 assert_eq!(
7229 p.sources(),
7230 [Source::new(FILE, 0), Source::new(FILE, 1)],
7231 "the middle entry is gone"
7232 );
7233 assert_eq!(
7234 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
7235 [0, 0, 0, 1],
7236 "the clips past it renumbered"
7237 );
7238 assert_eq!(
7239 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
7240 [0, 0, 0, 1],
7241 "on every lane"
7242 );
7243 // What is left is a project that still loads, which is the whole point
7244 // of renumbering rather than leaving a hole.
7245 let (sources, lanes, eq, color) = p.without_orphan_sources();
7246 Project::from_parts(sources, lanes, eq, color).expect("from_parts");
7247 }
7248
7249 /// The two edges of a removal: it retires the undo stack (the corner-cut on
7250 /// [`Project::remove_source`]), and the last entry goes like any other
7251 /// once nothing plays it -- a project may name no file at all.
7252 #[test]
7253 fn remove_source_retires_undo_and_empties_the_library() {
7254 let mut p = two_sources();
7255 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
7256 assert!(!p.history.is_empty(), "there is something to undo");
7257 p.remove_source(1).expect("nothing plays FILE2");
7258 assert!(
7259 p.history.is_empty(),
7260 "a snapshot naming the removed source must not survive it"
7261 );
7262 assert!(!p.undo(), "and so there is nothing left to undo");
7263
7264 // The last file standing is held to the one rule every row is -- what
7265 // plays cannot go -- and to no other.
7266 assert_eq!(p.sources().len(), 1);
7267 let refusal = p
7268 .remove_source(0)
7269 .expect_err("its clips are still on the lanes")
7270 .to_string();
7271 assert!(refusal.contains("still plays"), "{refusal}");
7272 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
7273 while p.delete_in(Lane::V1, 0) {}
7274 p.remove_source(0)
7275 .expect("the last row goes like any other");
7276 assert!(
7277 p.sources().is_empty(),
7278 "a project may name no file at all: an empty library over an empty timeline"
7279 );
7280 assert_eq!(p.timeline_frames(), 0);
7281 assert!(
7282 p.remove_source(0).is_err(),
7283 "and an index that is not there is refused, not panicked on"
7284 );
7285 }
7286
7287 /// A clip's equalizer is the clip's: it survives every edit that copies a
7288 /// placement, and it comes back with an undo.
7289 #[test]
7290 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
7291 let mut p = three();
7292 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
7293 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
7294 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7295 assert!(
7296 p.eq_of(Lane::V1, 0).is_none(),
7297 "one clip, not the lane above"
7298 );
7299
7300 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
7301 assert!(p.split(1));
7302 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7303 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
7304 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
7305
7306 // A clipboard copy carries it -- onto another lane, at that.
7307 let copied = p.lane(Lane::A1)[1];
7308 assert!(p.place(Lane::V1, 20, copied));
7309 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
7310 assert!(p.undo());
7311 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
7312
7313 // ...and a change to one is one undo step, in both directions.
7314 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
7315 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
7316 assert!(p.undo());
7317 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7318 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
7319 assert!(p.eq_of(Lane::A1, 0).is_none());
7320 assert!(p.undo());
7321 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7322
7323 // Two refusals, neither of which costs an undo step.
7324 let mut nan = band_at(1);
7325 nan.bands[0].q = f32::INFINITY;
7326 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
7327 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
7328 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7329 assert!(p.undo());
7330 assert_eq!(
7331 p.lane(Lane::A1).len(),
7332 3,
7333 "one step back is before the split"
7334 );
7335 assert!(p.undo());
7336 assert!(
7337 p.eq_of(Lane::A1, 0).is_none(),
7338 "and the next is before the setting: the refusals pushed none"
7339 );
7340 }
7341
7342 /// The table is append-only within a session, exactly as the sources are, so
7343 /// an undone setting is still in it -- and a save is where it goes.
7344 #[test]
7345 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
7346 let mut p = three();
7347 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
7348 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
7349 assert!(p.undo(), "back to the first setting");
7350 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
7351
7352 let (_, lanes, eq, _) = p.without_orphan_sources();
7353 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
7354 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
7355 assert_eq!(lanes[0].1[1].eq, None);
7356
7357 // One curve on three clips is one entry: settings that are equal share.
7358 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
7359 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
7360 let (_, lanes, eq, _) = p.without_orphan_sources();
7361 assert_eq!(eq.len(), 1, "equal settings share their entry");
7362 assert_eq!(lanes[1].1[2].eq, Some(0));
7363 reloads(&p, "an equalizer that outlived an undo");
7364 }
7365
7366 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
7367 /// grade is the clip's, through every edit that copies a placement.
7368 #[test]
7369 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
7370 let mut p = three();
7371 assert!(
7372 p.color_of(Lane::V1, 0).is_none(),
7373 "a fresh clip is ungraded"
7374 );
7375 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7376 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7377 assert!(
7378 p.color_of(Lane::A1, 0).is_none(),
7379 "one clip, not the lane below"
7380 );
7381 assert!(
7382 p.eq_of(Lane::V1, 0).is_none(),
7383 "and a grade is not an equalizer"
7384 );
7385
7386 // Cutting a graded clip must not grade half of it: both halves inherit.
7387 assert!(p.split(1));
7388 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7389 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
7390 assert!(
7391 p.color_of(Lane::V1, 2).is_none(),
7392 "the clip after it is ungraded"
7393 );
7394
7395 // A clipboard copy carries it -- onto another lane, at that.
7396 let copied = p.lane(Lane::V1)[1];
7397 assert!(p.place(Lane::A1, 20, copied));
7398 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
7399 assert!(p.undo());
7400 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
7401
7402 // ...and a change to one is one undo step, in both directions.
7403 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
7404 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
7405 assert!(p.undo());
7406 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7407 assert!(
7408 p.set_color(Lane::V1, 0, None),
7409 "and taking it off is an edit"
7410 );
7411 assert!(p.color_of(Lane::V1, 0).is_none());
7412 assert!(p.undo());
7413 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7414
7415 // Two refusals, neither of which costs an undo step.
7416 let nan = ColorParams {
7417 contrast: f32::NAN,
7418 ..grade_at(1)
7419 };
7420 assert!(
7421 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
7422 "no clip there"
7423 );
7424 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
7425 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7426 assert!(p.undo());
7427 assert_eq!(
7428 p.lane(Lane::V1).len(),
7429 3,
7430 "one step back is before the split"
7431 );
7432 assert!(p.undo());
7433 assert!(
7434 p.color_of(Lane::V1, 0).is_none(),
7435 "and the next is before the grade: the refusals pushed none"
7436 );
7437 }
7438
7439 /// A slider drag is one gesture: the press snapshots, every sample after it
7440 /// only regrades, and the single undo lands on what the clip was *before*
7441 /// the hand touched it -- not one step back down the drag.
7442 #[test]
7443 fn a_whole_colour_drag_undoes_in_one_step() {
7444 let mut p = three();
7445 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
7446 for n in 2..=8 {
7447 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
7448 }
7449 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
7450 assert!(p.undo());
7451 assert!(
7452 p.color_of(Lane::V1, 0).is_none(),
7453 "one undo is the whole gesture, back to ungraded"
7454 );
7455
7456 // The live write refuses what the snapshotting one refuses, and a
7457 // refusal still costs no history either way.
7458 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
7459 assert!(!p.set_color_live(
7460 Lane::V1,
7461 0,
7462 Some(ColorParams {
7463 contrast: f32::NAN,
7464 ..grade_at(1)
7465 })
7466 ));
7467 assert!(p.undo());
7468 assert_eq!(
7469 p.lane(Lane::V1).len(),
7470 2,
7471 "the next step back is the split before the drag: no sample pushed one"
7472 );
7473 }
7474
7475 /// The colour table is append-only within a session, exactly as the eq one
7476 /// is -- and a save is where an undone grade goes.
7477 #[test]
7478 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
7479 let mut p = three();
7480 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
7481 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7482 assert!(p.undo(), "back to the first grade");
7483 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
7484
7485 let (_, lanes, _, color) = p.without_orphan_sources();
7486 assert_eq!(
7487 color,
7488 vec![grade_at(1)],
7489 "what nothing plays is not written"
7490 );
7491 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
7492 assert_eq!(lanes[0].1[1].color, None);
7493
7494 // One grade on three clips is one entry: settings that are equal share.
7495 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
7496 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
7497 let (_, lanes, _, color) = p.without_orphan_sources();
7498 assert_eq!(color.len(), 1, "equal grades share their entry");
7499 assert_eq!(lanes[1].1[2].color, Some(0));
7500 reloads(&p, "a colour that outlived an undo");
7501
7502 // An equalizer and a grade on one clip are two independent tables.
7503 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
7504 let (_, lanes, eq, color) = p.without_orphan_sources();
7505 assert_eq!((eq.len(), color.len()), (1, 1));
7506 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
7507 }
7508
7509 /// Not a claim about correctness but about cost: a clip is copied on every
7510 /// paste, every undo snapshot and every lane clone, so its size is worth
7511 /// knowing. The eq index fit the padding a `Copy` clip already had; the
7512 /// colour one did not, and the struct grew a word.
7513 #[test]
7514 fn a_clip_is_still_a_small_copy() {
7515 assert_eq!(
7516 std::mem::size_of::<Clip>(),
7517 40,
7518 "Clip changed size -- 32 before the colour index, 40 after"
7519 );
7520 }
7521
7522 #[test]
7523 fn from_parts_has_no_history_and_checks_the_invariants() {
7524 let (sources, lanes, eq, color) = three().without_orphan_sources();
7525 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
7526 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone())
7527 .expect("valid parts");
7528 assert_eq!(p.clips(), three().clips());
7529 assert!(!p.undo(), "a loaded project has nothing to undo");
7530 assert!(p.split(4), "...and is editable from there");
7531 assert!(p.undo());
7532
7533 // A lane may be empty, and so may every lane -- an emptied timeline is a
7534 // project. No lane at all is not one: there would be nothing to place on.
7535 assert!(
7536 Project::from_parts(
7537 sources.clone(),
7538 two(video.clone(), Vec::new()),
7539 Vec::new(),
7540 Vec::new(),
7541 )
7542 .is_ok()
7543 );
7544 assert!(
7545 Project::from_parts(
7546 sources.clone(),
7547 two(Vec::new(), Vec::new()),
7548 Vec::new(),
7549 Vec::new(),
7550 )
7551 .is_ok()
7552 );
7553 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
7554 let bad: [Vec<Clip>; 5] = [
7555 vec![clip(0, 0, 3, 1)], // source that is not there
7556 vec![clip(0, 3, 3, 0)], // empty clip
7557 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
7558 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
7559 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
7560 ];
7561 for clips in bad {
7562 assert!(
7563 Project::from_parts(
7564 sources.clone(),
7565 two(clips.clone(), Vec::new()),
7566 Vec::new(),
7567 Vec::new(),
7568 )
7569 .is_err(),
7570 "{clips:?}"
7571 );
7572 assert!(
7573 Project::from_parts(
7574 sources.clone(),
7575 two(video.clone(), clips.clone()),
7576 Vec::new(),
7577 Vec::new(),
7578 )
7579 .is_err()
7580 );
7581 // ...and on a third lane, which is checked by the same walk.
7582 assert!(
7583 Project::from_parts(
7584 sources.clone(),
7585 vec![
7586 (LaneKind::Video, video.clone()),
7587 (LaneKind::Audio, audio.clone()),
7588 (LaneKind::Video, clips),
7589 ],
7590 Vec::new(),
7591 Vec::new(),
7592 )
7593 .is_err()
7594 );
7595 }
7596 // An equalizer index no table entry answers, and a table entry the file
7597 // format could not have written, are refused at this door too.
7598 let eqd = |i: u16| {
7599 vec![Clip {
7600 eq: Some(i),
7601 ..video[0]
7602 }]
7603 };
7604 assert!(
7605 Project::from_parts(
7606 sources.clone(),
7607 two(eqd(0), Vec::new()),
7608 Vec::new(),
7609 Vec::new(),
7610 )
7611 .is_err()
7612 );
7613 let mut nan = band_at(1);
7614 nan.bands[0].freq_hz = f32::NAN;
7615 assert!(
7616 Project::from_parts(
7617 sources.clone(),
7618 two(eqd(0), Vec::new()),
7619 vec![nan],
7620 Vec::new(),
7621 )
7622 .is_err()
7623 );
7624 let loaded = Project::from_parts(
7625 sources.clone(),
7626 two(eqd(0), Vec::new()),
7627 vec![band_at(1)],
7628 Vec::new(),
7629 )
7630 .expect("an eq the table holds");
7631 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
7632
7633 // The same two refusals for a colour, at the same door.
7634 let graded = |i: u16| {
7635 vec![Clip {
7636 color: Some(i),
7637 fit: FitPolicy::default(),
7638 speed: Speed::NORMAL,
7639 ..video[0]
7640 }]
7641 };
7642 assert!(
7643 Project::from_parts(
7644 sources.clone(),
7645 two(graded(0), Vec::new()),
7646 Vec::new(),
7647 Vec::new(),
7648 )
7649 .is_err(),
7650 "a colour index no entry answers"
7651 );
7652 assert!(
7653 Project::from_parts(
7654 sources.clone(),
7655 two(graded(0), Vec::new()),
7656 Vec::new(),
7657 vec![ColorParams {
7658 tint: f32::NAN,
7659 ..grade_at(1)
7660 }],
7661 )
7662 .is_err(),
7663 "a value the file format could not have written"
7664 );
7665 let loaded = Project::from_parts(
7666 sources.clone(),
7667 two(graded(0), Vec::new()),
7668 Vec::new(),
7669 vec![grade_at(1)],
7670 )
7671 .expect("a colour the table holds");
7672 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
7673
7674 // Group ids survive a load, and the next split gets a fresh one.
7675 let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts");
7676 assert!(p.split(4));
7677 assert!(p.clips().iter().all(|c| c.link.is_some()));
7678 }
7679
7680 /// The grouping rules, at the untrusted door and after every edit that can
7681 /// touch a link. A link id is at most one placement per lane -- a clip or a
7682 /// caption, whichever carries it -- and no sequence of edits may produce
7683 /// otherwise, because what an edit produces is what a save writes and a load
7684 /// reads.
7685 ///
7686 /// Amended for the offset-preserving group: the members keep their own
7687 /// spans, so two placements of one id covering different frames is *legal*
7688 /// -- it is what a hand-built group is -- and the only refusal left is the
7689 /// doubled id inside one lane.
7690 #[test]
7691 fn a_link_id_is_never_two_clips_of_one_lane() {
7692 let sources = vec![Source::new(FILE, 0)];
7693 let linked = |start, in_frame, out_frame, link| Clip {
7694 start,
7695 in_frame,
7696 out_frame,
7697 source: 0,
7698 link: Some(link),
7699 eq: None,
7700 color: None,
7701 fit: FitPolicy::default(),
7702 speed: Speed::NORMAL,
7703 };
7704
7705 // The door: a doubled id inside one lane, refused by name.
7706 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
7707 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
7708 .expect_err("refused")
7709 .to_string()
7710 };
7711 assert!(
7712 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
7713 .contains("link 7 names two clips in the V1 lane"),
7714 "a duplicate id inside one lane is refused by name"
7715 );
7716 // ...and the same doubling on a subtitle lane, in its own words: a
7717 // caption is the other placement an id may name.
7718 let caption = |start: u32, frames: u32, link| SubClip {
7719 start,
7720 frames,
7721 track: 0,
7722 in_us: 0,
7723 out_us: i64::from(frames) * 1_000_000,
7724 link: Some(link),
7725 };
7726 let subs = LaneData {
7727 clips: Vec::new(),
7728 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
7729 ..LaneData::new(LaneKind::Subtitle, Vec::new())
7730 };
7731 assert_eq!(
7732 links_are_consistent(&[subs]).unwrap_err().to_string(),
7733 "link 7 names two captions in the S1 lane"
7734 );
7735 // A pair covering *different* frames is legal now: the members of a
7736 // hand-built group keep their own spans, and what binds them is the id.
7737 let apart = Project::from_parts(
7738 sources.clone(),
7739 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
7740 Vec::new(),
7741 Vec::new(),
7742 );
7743 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
7744 // A one-sided link is *not* an error: it is what a lift leaves behind.
7745 let mut p = Project::single(FILE, 9);
7746 assert!(p.lift(Lane::A1, 0));
7747 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
7748 assert!(
7749 Project::from_parts(sources, lanes, eq, color).is_ok(),
7750 "a lifted lane's project has to load again"
7751 );
7752
7753 // The edits: nothing below may break either rule.
7754 let consistent = |p: &Project, what: &str| {
7755 assert!(
7756 links_are_consistent(&p.lanes).is_ok(),
7757 "{what}: {:?}",
7758 p.lanes
7759 );
7760 };
7761 let mut p = three();
7762 let copied = p.clips()[0];
7763 assert!(
7764 copied.link.is_some(),
7765 "the clipboard clip carries its group"
7766 );
7767 assert!(p.lift(Lane::V1, 0));
7768 assert!(p.place(Lane::V1, 0, copied));
7769 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
7770 assert_eq!(
7771 p.clips().iter().filter(|c| c.link == copied.link).count(),
7772 0,
7773 "a placement belongs to no group, so it cannot duplicate one"
7774 );
7775 consistent(&p, "lift + place twice");
7776 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
7777 consistent(&p, "place through a grouped clip");
7778 assert!(p.paste(6, copied), "a rippling paste through another");
7779 consistent(&p, "paste");
7780 assert!(p.split(2));
7781 consistent(&p, "split");
7782 assert!(p.ripple_delete(1, 3));
7783 consistent(&p, "ripple_delete");
7784 assert!(p.undo());
7785 consistent(&p, "undo");
7786 }
7787
7788 /// What an edit produces is what a save writes, so *every* state the public
7789 /// API can reach has to load again. The two the verifier panel found where
7790 /// it did not: a split and a regroup handed one group id to two clips that
7791 /// were not the same span, because the lanes had been edited apart.
7792 #[test]
7793 fn every_reachable_state_reloads() {
7794 let mut p = Project::single(FILE, 150);
7795 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
7796 assert!(p.split(10), "the lanes are cut apart at 10");
7797 reloads(&p, "place on one lane, then split");
7798
7799 let mut p = Project::single(FILE, 150);
7800 assert!(p.split(30));
7801 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
7802 assert!(p.regroup(30), "only the audio lane can rejoin");
7803 assert!(p.split(60));
7804 reloads(&p, "lift, regroup one lane, split");
7805
7806 // Two audio streams of one file, both placed: two source entries with
7807 // one path between them, which is the state a stream picked out of the
7808 // library reaches -- and the state a save has to write and read back.
7809 let mut p = Project::single(FILE, 150);
7810 let second = p.import(FILE, 1);
7811 assert_eq!(second, 1, "the same file on another stream is a new source");
7812 assert!(p.append_clip(second, 150));
7813 assert!(p.split(200));
7814 reloads(
7815 &p,
7816 "a second audio stream of the same file, placed and split",
7817 );
7818 let (sources, ..) = p.without_orphan_sources();
7819 assert_eq!(
7820 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
7821 [0, 1],
7822 "both entries survive the orphan prune: both are played"
7823 );
7824 }
7825
7826 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
7827 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
7828 /// is the stamp playback puts on a decoded source frame -- and the *last*
7829 /// source frame the pump is still holding at a timeline frame has to be
7830 /// exactly the one the export encoded there, at every rate. Anything else is
7831 /// A/V drift that grows with the clip, and no test of either side alone
7832 /// would see it.
7833 ///
7834 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
7835 /// is a better answer than the floor/floor this had: floor/floor put the
7836 /// preview a whole held frame off the export at slow rates.)
7837 #[test]
7838 fn speed_maps_both_ways() {
7839 for permille in (250..=4000).step_by(1) {
7840 let speed = Speed::from_permille(permille);
7841 assert_eq!(speed.permille(), permille, "no clamping in range");
7842 for d in 0..200u32 {
7843 let want = speed.source_at(d);
7844 // What the pump shows at `d` is the last frame whose stamp has
7845 // come due -- and it is `want`, the frame the export encodes
7846 // there. Slowed, that is the frame it is still holding; sped up,
7847 // it is the newest of the several that arrived.
7848 let held = (0..=want + 8)
7849 .filter(|&s| speed.timeline_at(s) <= d)
7850 .next_back();
7851 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
7852 }
7853 for n in 1..300u32 {
7854 // A footprint is never zero: a clip occupying no timeline frame
7855 // is a placement the lane invariants cannot hold.
7856 let frames = speed.frames(n);
7857 assert!(frames >= 1, "{speed} of {n} frames");
7858 // ...and its last timeline frame never reads past the clip.
7859 assert!(
7860 speed.source_at(frames - 1) < n,
7861 "{speed}: the last timeline frame of {n} reads past the clip"
7862 );
7863 // The trim inverse never overshoots the room it was given, and
7864 // answers for every room a footprint can be.
7865 let fit = speed.fit(frames).expect("a clip fits its own footprint");
7866 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
7867 // A room narrower than one source frame's own footprint holds
7868 // nothing, and says so rather than rounding something into it.
7869 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
7870 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
7871 }
7872 }
7873 // Real time is the identity map, byte for byte.
7874 for d in 0..1000 {
7875 assert_eq!(Speed::NORMAL.source_at(d), d);
7876 assert_eq!(Speed::NORMAL.timeline_at(d), d);
7877 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
7878 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
7879 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
7880 }
7881 // The one door: no zero, no reverse, nothing past the ends.
7882 assert_eq!(Speed::from_permille(0), Speed::MIN);
7883 assert_eq!(Speed::from_permille(249), Speed::MIN);
7884 assert_eq!(Speed::from_permille(4001), Speed::MAX);
7885 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
7886 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
7887 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
7888 }
7889
7890 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
7891 /// export encodes at a timeline frame is the one playback is holding there,
7892 /// a file is as long in timeline frames as the seconds it lasts, and the two
7893 /// compose so a speeded clip at another rate is exactly both.
7894 #[test]
7895 fn rate_composes_with_speed() {
7896 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
7897 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
7898 // the identity map or a single-rate project would move.
7899 for (source_fps, timeline_fps) in [
7900 (24000. / 1001., 30.),
7901 (30., 24000. / 1001.),
7902 (60., 30.),
7903 (25., 30.),
7904 (30., 30.),
7905 ] {
7906 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
7907 for n in 0..2000u32 {
7908 let source = rate.source_at(n);
7909 // The stamp is the *first* timeline-rate frame that shows it, so
7910 // the picture on screen at `n` is the picture encoded at `n`.
7911 let held = (0..=source + 4)
7912 .filter(|&s| rate.timeline_at(s) <= n)
7913 .next_back();
7914 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
7915 }
7916 // A file of `count` frames is `timeline_at(count)` frames long here,
7917 // and its last one still reads a frame the file has.
7918 for count in 1..500u32 {
7919 let frames = rate.timeline_at(count);
7920 assert!(frames >= 1, "a file is never zero frames long");
7921 assert!(
7922 rate.source_at(frames - 1) < count,
7923 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
7924 );
7925 }
7926 // No drift: the mapping is one exact division of the *rate itself*,
7927 // not an accumulation and not a rounded rate, so an hour in is as
7928 // true as the first second. (Held to the real ratio of the two rates
7929 // the caller asked for -- `as_f64` would be true of a wrong rate.)
7930 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
7931 let want = f64::from(n) * source_fps / timeline_fps;
7932 assert!(
7933 (f64::from(rate.source_at(n)) - want).abs() < 1.,
7934 "{source_fps} on {timeline_fps}: frame {n} drifted"
7935 );
7936 }
7937 }
7938 // The timeline's own rate is the identity, whichever way it is written.
7939 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
7940 assert!(
7941 Rate::from_fps(30.0004, 30.)
7942 .expect("30.0004 over 30")
7943 .is_real_time(),
7944 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
7945 );
7946 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
7947 // one thing `matches_timeline` refuses a file for now that the rate gate
7948 // is gone.
7949 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
7950 assert!(Rate::from_fps(30., f64::NAN).is_err());
7951 for n in 0..1000 {
7952 assert_eq!(Rate::REAL_TIME.source_at(n), n);
7953 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
7954 }
7955 // ...and the composition, in the order the decoder's door applies it:
7956 // the speed picks the clip's (timeline-rate) frame, the rate picks the
7957 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
7958 // timeline frames per frame shown, each of them exactly 800/1001 of a
7959 // file frame.
7960 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
7961 let speed = Speed::from_permille(2000);
7962 for d in 0..100u32 {
7963 assert_eq!(
7964 rate.source_at(speed.source_at(d)),
7965 (u64::from(d) * 2 * 800 / 1001) as u32,
7966 "2x of a 23.976 fps file at timeline frame {d}"
7967 );
7968 }
7969 }
7970
7971 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
7972 /// source frames per timeline frame and still starts at its own in-point,
7973 /// and a half-speed one shows every source frame twice.
7974 #[test]
7975 fn a_rate_maps_timeline_frames_onto_source_frames() {
7976 let mut p = Project::single(FILE, 40);
7977 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
7978 .expect("room enough");
7979 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
7980 assert_eq!(
7981 p.map(Lane::V1, 0),
7982 Some((0, 0)),
7983 "and it starts where it did"
7984 );
7985 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
7986 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
7987 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
7988 // The span a decoder is handed: as many source frames as it will read,
7989 // which is the last shown frame's own and not one more -- timeline frame
7990 // 19 shows source frame 38, so 39 frames are read and the 40th is a
7991 // picture nothing would display.
7992 let span = p.span_at(Lane::V1, 0).expect("a span");
7993 assert_eq!((span.len, span.source_len()), (20, 39));
7994 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
7995 // ...and the same clip the other way round.
7996 let mut p = Project::single(FILE, 40);
7997 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
7998 .expect("room enough");
7999 assert_eq!(p.timeline_frames(), 80);
8000 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
8001 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
8002 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
8003 assert_eq!(
8004 p.map(Lane::V1, 79),
8005 Some((0, 39)),
8006 "and the last timeline frame is still inside the source range"
8007 );
8008 }
8009
8010 /// A trim of a speeded clip is still a trim of its *source*, and the edge
8011 /// still stops at the wall: the room a rate leaves is measured in timeline
8012 /// frames and the range it commits in source ones.
8013 #[test]
8014 fn trimming_a_speeded_clip_stays_inside_its_room() {
8015 let mut p = Project::single(FILE, 40);
8016 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8017 .expect("room enough");
8018 // A second clip butted against the first, so the wall is a real one.
8019 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
8020 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
8021 assert_eq!(room, (1, 20), "out to the neighbour and no further");
8022 assert!(
8023 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
8024 "clamped to the wall, which is where the edge already is"
8025 );
8026 let c = p.clips()[0];
8027 assert_eq!(c.end(), 20, "so nothing moved");
8028 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
8029 // ...and in: half the timeline frames is half the source range.
8030 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
8031 let c = p.clips()[0];
8032 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
8033 assert_eq!(c.end(), 10, "and ten timeline frames of them");
8034 assert!(sorted_disjoint(p.clips()));
8035 }
8036
8037 /// The frames a rate cannot address: at half speed each source frame is on
8038 /// screen twice, and the cut between the two showings is not a cut in the
8039 /// file. Refused, so the two halves always add up to the clip that was cut.
8040 #[test]
8041 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
8042 let mut p = Project::single(FILE, 10);
8043 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8044 .expect("room enough");
8045 assert_eq!(p.timeline_frames(), 20);
8046 assert!(
8047 !p.split(3),
8048 "an odd frame is between two showings of one frame"
8049 );
8050 assert_eq!(p.clips().len(), 1, "and nothing was cut");
8051 assert!(p.split(4), "an even one is a frame boundary");
8052 let halves = p.clips().to_vec();
8053 assert_eq!(
8054 (halves[0].end(), halves[1].start, halves[1].end()),
8055 (4, 4, 20),
8056 "the halves meet, and still end where the clip did"
8057 );
8058 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
8059 assert!(p.regroup(4), "and the inverse puts it back");
8060 assert_eq!(p.clips().len(), 1);
8061 }
8062
8063 /// The same claim, swept: random op sequences off the public surface, the
8064 /// project reloaded after every one of them. A failure prints its seed, and
8065 /// the seed replays the whole sequence.
8066 #[test]
8067 fn random_edit_sequences_reload() {
8068 // Two thousand, not two hundred: the overlap a hole punched into a slow
8069 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
8070 // sequences, and a 200-seed sweep walked straight past it (it took a
8071 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
8072 // has no business being the narrow one.
8073 for seed in 0..2000u64 {
8074 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8075 let mut next = move |n: u32| {
8076 // xorshift64*: no dependency, and the seed replays it exactly.
8077 rng ^= rng << 13;
8078 rng ^= rng >> 7;
8079 rng ^= rng << 17;
8080 (rng >> 33) as u32 % n
8081 };
8082 let mut p = Project::single(FILE, 40);
8083 for step in 0..24 {
8084 let frame = next(44);
8085 // A clipboard copy carries the group id of the take it came from
8086 // -- the input that made a placement duplicate an id -- and, one
8087 // time in three, a rate of its own: a *speeded clip placed over
8088 // a speeded clip* is the shape whose remainders have to be run
8089 // through `Speed::fit`, and it is not a shape the lanes hand out
8090 // on their own often enough to be sure of.
8091 let mut copied = *p
8092 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
8093 .get(next(4) as usize)
8094 .unwrap_or(&clip(0, 0, 5, 0));
8095 if next(3) == 0 {
8096 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
8097 }
8098 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
8099 let idx = next(4) as usize;
8100 let _ = match next(16) {
8101 // A clip dragged along its own lane to wherever the pointer
8102 // let it go: the op that moves a placement without changing
8103 // what it plays, so what it may not do is land on top of the
8104 // neighbour it was dragged at.
8105 15 => p.move_clip(lane, idx, lane, frame),
8106 // ...and a second `place`, so a punch lands inside a clip
8107 // far more often than one op in fourteen would put it there.
8108 14 => p.place(lane, frame, copied),
8109 0 => p.split(frame),
8110 1 => p.regroup(frame),
8111 2 => p.lift(lane, idx),
8112 3 => p.place(lane, frame, copied),
8113 4 => p.paste(frame, copied),
8114 5 => p.ripple_delete(frame, next(9)),
8115 6 => p.delete(idx),
8116 7 => p.undo(),
8117 // An equalizer put on and taken off in the mix: what a clip
8118 // carries has to reload with it, and the entries an undo
8119 // orphans must not come back out of the prune.
8120 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8121 9 => p.set_eq(lane, idx, None),
8122 // ...and a colour grade in the same mix, for the same
8123 // reason: it rides on the clip and its orphans must go.
8124 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
8125 11 => p.set_color(lane, idx, None),
8126 // ...and a rate in with them, which is the one of the three
8127 // that moves *placements*: a clip that grew has to be
8128 // refused rather than overlap, and one that shrank leaves a
8129 // lane that still loads. Both are what `reloads` asks.
8130 12 => p
8131 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8132 .is_ok(),
8133 _ => p.append_clip(0, 1 + next(9)),
8134 };
8135 reloads(&p, &format!("seed {seed}, step {step}"));
8136 }
8137 }
8138 }
8139
8140 /// The save/load round trip a project must survive: the parts a save writes,
8141 /// handed back to the constructor a load goes through -- every lane of them,
8142 /// and the reloaded timeline has to be the same lanes in the same order.
8143 fn reloads(p: &Project, what: &str) {
8144 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
8145 match Project::from_parts(sources, lanes, eq, color) {
8146 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
8147 Ok(back) => {
8148 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
8149 // Placements, not whole clips: an orphan prune renumbers the
8150 // sources a clip names, which is the point of it.
8151 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
8152 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
8153 };
8154 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
8155 // The prune renumbers the eq table too, so what has to survive
8156 // is the settings themselves, clip by clip.
8157 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
8158 p.lanes()
8159 .into_iter()
8160 .map(|l| {
8161 (0..p.lane(l).len())
8162 .map(|i| p.eq_of(l, i).cloned())
8163 .collect()
8164 })
8165 .collect()
8166 };
8167 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
8168 // The colour table renumbers in the same prune, so the same
8169 // claim: the params a clip names, not the index it names them by.
8170 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
8171 p.lanes()
8172 .into_iter()
8173 .map(|l| {
8174 (0..p.lane(l).len())
8175 .map(|i| p.color_of(l, i).copied())
8176 .collect()
8177 })
8178 .collect()
8179 };
8180 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
8181 }
8182 }
8183 }
8184
8185 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
8186 /// -- each one sorted and disjoint, and one span per group id -- asserted
8187 /// directly, where the point is the invariant rather than the round trip.
8188 fn invariants_hold(p: &Project, what: &str) {
8189 for lane in p.lanes() {
8190 assert!(
8191 sorted_disjoint(p.lane(lane)),
8192 "{what}: {} is out of order or overlaps itself: {:?}",
8193 lane.label(),
8194 p.lane(lane)
8195 );
8196 }
8197 if let Err(e) = links_are_consistent(&p.lanes) {
8198 panic!("{what}: {e}\n{:?}", p.lanes);
8199 }
8200 }
8201
8202 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
8203 /// edited without any other lane hearing about it. A handle naming a lane
8204 /// that is not there reads as empty and refuses to mutate.
8205 #[test]
8206 fn a_third_lane_is_a_peer() {
8207 let mut p = three();
8208 assert_eq!(p.lane_count(LaneKind::Video), 1);
8209 assert_eq!(p.lane_count(LaneKind::Audio), 1);
8210 let v2 = p.add_lane(LaneKind::Video);
8211 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
8212 assert_eq!(v2.label(), "V2");
8213 assert_eq!(p.lane_count(LaneKind::Video), 2);
8214 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8215 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
8216
8217 // A handle for a lane that is not there: empty, and no mutation takes.
8218 let v3 = Lane::new(LaneKind::Video, 2);
8219 assert!(p.lane(v3).is_empty());
8220 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
8221 assert!(!p.lift(v3, 0));
8222 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
8223
8224 // Placing on V2 moves nothing else, and the lane can outrun the rest.
8225 let before = shape(&p);
8226 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8227 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
8228 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
8229 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8230 assert_eq!(
8231 p.timeline_frames(),
8232 16,
8233 "the last lane to end sets the length"
8234 );
8235 assert_eq!(p.map(v2, 5), Some((0, 21)));
8236 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
8237 assert_eq!(
8238 p.span_at(v2, 0),
8239 Some(Span {
8240 start: 0,
8241 len: 4,
8242 from: None,
8243 speed: Speed::NORMAL
8244 })
8245 );
8246 // Every lane still covers the whole timeline, gaps included.
8247 for l in p.lanes() {
8248 let spans = p.spans_from(l, 0);
8249 assert_eq!(
8250 spans.iter().map(|s| s.len).sum::<u32>(),
8251 16,
8252 "{}",
8253 l.label()
8254 );
8255 }
8256 // ...and playback still reads V1 and A1, whatever else is there.
8257 assert_eq!(p.clips(), p.lane(Lane::V1));
8258 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
8259 let segments = p.segments_from(0, FPS);
8260 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
8261 assert_eq!(
8262 segments[3],
8263 (None, 0.0, 7.0 / FPS),
8264 "A1 keeps the clock counting over the picture V2 added"
8265 );
8266 invariants_hold(&p, "place on V2");
8267
8268 // A lift is that lane's business too, and the lane list undoes.
8269 assert!(p.lift(v2, 0));
8270 assert!(p.lane(v2).is_empty());
8271 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
8272 assert!(p.undo());
8273 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8274 assert!(p.undo());
8275 assert!(p.lane(v2).is_empty(), "the placement came off V2");
8276 assert!(p.undo(), "and one more step takes the lane itself back");
8277 assert_eq!(p.lane_count(LaneKind::Video), 1);
8278 assert_eq!(shape(&p), shape(&three()));
8279 }
8280
8281 /// The add taken back: an empty lane comes off, a lane holding clips never
8282 /// does (and says which clips), the last lane of a kind never does, the
8283 /// lanes below the one that went move up an `ord`, and one undo puts it
8284 /// back where it stood.
8285 #[test]
8286 fn an_empty_lane_comes_off_again() {
8287 let mut p = three();
8288 let v2 = p.add_lane(LaneKind::Video);
8289 let v3 = p.add_lane(LaneKind::Video);
8290 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
8291 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
8292 let history = p.history.len();
8293
8294 // The last lane of its kind stays: `V1`/`A1` are where an import and a
8295 // paste land, and a project missing one would swallow half of a file
8296 // dropped on it.
8297 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
8298 assert_eq!(
8299 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
8300 "there is no V10 to remove"
8301 );
8302
8303 // A lane with clips on it refuses and names them: a track removal never
8304 // deletes a take.
8305 let refusal = why(p.remove_lane(v3));
8306 assert!(refusal.contains("V3 still holds"), "{refusal}");
8307 assert!(refusal.contains(FILE), "{refusal}");
8308 assert!(refusal.contains("at frame 0"), "{refusal}");
8309 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
8310 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
8311
8312 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
8313 // all.
8314 p.remove_lane(v2).expect("V2 is empty");
8315 assert_eq!(p.lane_count(LaneKind::Video), 2);
8316 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8317 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
8318 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
8319 invariants_hold(&p, "remove V2");
8320
8321 // ...and one stroke puts the empty lane back above it.
8322 assert!(p.undo());
8323 assert_eq!(p.lane_count(LaneKind::Video), 3);
8324 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
8325 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
8326 }
8327
8328 /// A track dragged to another place in the stack: the whole lane travels --
8329 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
8330 /// a video one, a lane that crosses one of its own kind swaps names with it
8331 /// (and swaps the composite with it), one undo puts the order back, and a
8332 /// save carries it.
8333 #[test]
8334 fn a_track_is_dragged_to_another_place_in_the_stack() {
8335 let mut p = three();
8336 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
8337 let before = shape(&p);
8338 let history = p.history.len();
8339
8340 // A1 over V1: the screen is rearranged and nothing else is. Both keep
8341 // their names -- neither crossed a lane of its own kind -- so every
8342 // handle a front-end holds still names the track it named before.
8343 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
8344 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
8345 assert_eq!(
8346 shape(&p),
8347 vec![before[1].clone(), before[0].clone()],
8348 "each lane's clips travelled with it, and none was remapped"
8349 );
8350 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
8351 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
8352 invariants_hold(&p, "A1 over V1");
8353
8354 // Nothing moves for a lane that is not there, a slot that is not, or a
8355 // lane already standing in the one it was pointed at.
8356 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
8357 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
8358 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
8359 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
8360
8361 // ...and one stroke puts the order back.
8362 assert!(p.undo());
8363 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
8364 assert_eq!(shape(&p), before);
8365
8366 // A second video lane over the first: display order *is* the stack, so
8367 // the last video lane covering a frame is the picture that shows.
8368 let v2 = p.add_lane(LaneKind::Video);
8369 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
8370 let over = shape(&p)[2].clone();
8371 assert_eq!(
8372 p.composite_span_at(0).map(|s| s.len),
8373 Some(5),
8374 "V2's five frames are what frame 0 shows"
8375 );
8376
8377 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
8378 // a position among the lanes of its kind. The picture that wins changes
8379 // with it: the take that was covering is the covered one now.
8380 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
8381 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
8382 assert_eq!(
8383 shape(&p),
8384 vec![over.clone(), before[0].clone(), before[1].clone()],
8385 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
8386 );
8387 assert_eq!(
8388 p.composite_span_at(0).map(|s| s.len),
8389 Some(3),
8390 "the lower video lane wins, and it is the old V1 now"
8391 );
8392 invariants_hold(&p, "V2 over V1");
8393
8394 // A save writes that order and a load takes it back.
8395 let (sources, lanes, eq, color) = p.without_orphan_sources();
8396 assert_eq!(
8397 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
8398 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
8399 );
8400 let back = Project::from_parts(sources, lanes, eq, color).expect("three lanes load");
8401 assert_eq!(back.lanes(), p.lanes());
8402 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
8403
8404 assert!(p.undo(), "and the stack goes back to how it stood");
8405 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
8406 }
8407
8408 /// The grouping rule across more than two lanes, under the offset model: a
8409 /// split *keeps* the group on the left halves and hands the right halves of
8410 /// that group one fresh id of their own -- a clip in no group comes out of
8411 /// the cut in none. So a take cut apart is two takes, one per side, and a
8412 /// lane that was never part of it stays out of both.
8413 #[test]
8414 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
8415 let mut p = Project::single(FILE, 9);
8416 let take = p.clips()[0].link.expect("a fresh project is one take");
8417 let v2 = p.add_lane(LaneKind::Video);
8418 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
8419 assert!(p.split(4));
8420 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
8421 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
8422 };
8423 let (left, right) = (side(&p, 0), side(&p, 1));
8424 // The lanes in order are V1, A1, V2: the take's two keep its id on the
8425 // left, and the placed clip never had one for the cut to keep.
8426 assert_eq!(
8427 left,
8428 vec![Some(take), Some(take), None],
8429 "the left halves keep the take"
8430 );
8431 // ...and the right halves of that take are one fresh group.
8432 assert_eq!(right[0], right[1]);
8433 assert_ne!(right[0], Some(take));
8434 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
8435 invariants_hold(&p, "split across three lanes");
8436
8437 // V2 ends early: the left halves still keep what each clip carried --
8438 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
8439 // shared by exactly the take's lanes.
8440 let mut p = Project::single(FILE, 9);
8441 let v2 = p.add_lane(LaneKind::Video);
8442 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
8443 assert!(p.split(3));
8444 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
8445 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
8446 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
8447 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
8448 invariants_hold(&p, "split where one lane ends early");
8449
8450 // The inverse rejoins each lane into the group its left half kept.
8451 assert!(p.regroup(3));
8452 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
8453 assert_eq!(
8454 p.lane(Lane::V1)[0].link,
8455 Some(take),
8456 "the take's id is back, not a fresh one"
8457 );
8458 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
8459 invariants_hold(&p, "regroup across three lanes");
8460 }
8461
8462 /// A group is one placement per lane, on however many lanes carry the id --
8463 /// not a video/audio pair and not a pairing by `ord` -- and the members may
8464 /// cover whatever frames they cover: the offset between them is what a
8465 /// hand-built group keeps. Lanes built by hand, because the rule is checked
8466 /// at the untrusted door and no edit can produce the one thing it refuses.
8467 #[test]
8468 fn a_group_may_span_any_lane() {
8469 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
8470 let one = |start: u32, end: u32, link| Clip {
8471 start,
8472 in_frame: start,
8473 out_frame: end,
8474 source: 0,
8475 link: Some(link),
8476 eq: None,
8477 color: None,
8478 fit: FitPolicy::default(),
8479 speed: Speed::NORMAL,
8480 };
8481 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
8482 let kinds = [
8483 LaneKind::Video,
8484 LaneKind::Audio,
8485 LaneKind::Video,
8486 LaneKind::Audio,
8487 ];
8488 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
8489 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
8490 };
8491 let take = || vec![one(0, 4, 7)];
8492 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
8493 // The same take on V1 + A2 only, the lanes between it empty: legal, the
8494 // way a lifted half is legal.
8495 let across = build([take(), Vec::new(), Vec::new(), take()]);
8496 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
8497 // ...and so is a group whose members disagree about their spans: the
8498 // offset between them is the hand's business, not the loader's.
8499 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
8500 assert!(
8501 links_are_consistent(&apart).is_ok(),
8502 "[0, 4) on V1 and [2, 6) on A2 are one group"
8503 );
8504 // One id twice in one lane is still that lane's error, by name.
8505 let twice = build([
8506 Vec::new(),
8507 Vec::new(),
8508 vec![one(0, 4, 7), one(4, 8, 7)],
8509 Vec::new(),
8510 ]);
8511 assert_eq!(
8512 links_are_consistent(&twice).unwrap_err().to_string(),
8513 "link 7 names two clips in the V2 lane"
8514 );
8515 }
8516
8517 /// Every lane a save writes comes out, in display order and with its kind --
8518 /// an empty one included, since it is state a front-end shows -- and a
8519 /// two-lane project still writes exactly the parts it always did.
8520 #[test]
8521 fn a_save_writes_every_lane_it_has() {
8522 let mut p = three();
8523 let before = p.without_orphan_sources();
8524 assert_eq!(before.1.len(), 2, "V1 and A1");
8525 let v2 = p.add_lane(LaneKind::Video);
8526 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8527 let a2 = p.add_lane(LaneKind::Audio);
8528 let (sources, lanes, eq, color) = p.without_orphan_sources();
8529 assert_eq!(
8530 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
8531 [
8532 LaneKind::Video,
8533 LaneKind::Audio,
8534 LaneKind::Video,
8535 LaneKind::Audio
8536 ],
8537 "display order, not video-then-audio"
8538 );
8539 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
8540 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
8541 // ...and all four load again as the same four.
8542 let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load");
8543 assert_eq!(back.lanes(), p.lanes());
8544 assert_eq!(back.lane(a2), p.lane(a2));
8545
8546 // Taking the lanes back leaves exactly what a two-lane save wrote.
8547 for _ in 0..3 {
8548 assert!(p.undo());
8549 }
8550 assert_eq!(
8551 p.without_orphan_sources(),
8552 before,
8553 "byte for byte the same parts a two-lane save always wrote"
8554 );
8555 }
8556
8557 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
8558 /// three lanes and grows more: every lane's own order and the one
8559 /// span-per-id rule after every op, *and* the reload the v4 format restored
8560 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
8561 /// project of any number of lanes.
8562 #[test]
8563 fn random_edit_sequences_keep_many_lanes_consistent() {
8564 for seed in 0..2000u64 {
8565 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8566 let mut next = move |n: u32| {
8567 rng ^= rng << 13;
8568 rng ^= rng >> 7;
8569 rng ^= rng << 17;
8570 (rng >> 33) as u32 % n
8571 };
8572 let mut p = Project::single(FILE, 40);
8573 let v2 = p.add_lane(LaneKind::Video);
8574 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
8575 let lanes = [Lane::V1, Lane::A1, v2];
8576 for step in 0..24 {
8577 let frame = next(44);
8578 let copied = *p
8579 .lane(lanes[next(3) as usize])
8580 .get(next(4) as usize)
8581 .unwrap_or(&clip(0, 0, 5, 0));
8582 let lane = lanes[next(3) as usize];
8583 let idx = next(4) as usize;
8584 let _ = match next(14) {
8585 // The drag, in the mix: a clip dragged along its own lane
8586 // and onto another one, at a frame the pointer picked --
8587 // which is where the group rule and the sorted+disjoint one
8588 // meet, since every half travels the same distance.
8589 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
8590 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8591 11 => p.set_eq(lane, idx, None),
8592 // A rate, which on many lanes is the group rule as well:
8593 // every clip carrying the link moves together or none of
8594 // them does, and `invariants_hold` is what says so.
8595 12 => p
8596 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8597 .is_ok(),
8598 0 => p.split(frame),
8599 1 => p.regroup(frame),
8600 2 => p.lift(lane, idx),
8601 3 => p.place(lane, frame, copied),
8602 4 => p.paste(frame, copied),
8603 5 => p.ripple_delete(frame, next(9)),
8604 6 => p.delete(idx),
8605 7 => p.undo(),
8606 8 => {
8607 p.add_lane(if next(2) == 0 {
8608 LaneKind::Video
8609 } else {
8610 LaneKind::Audio
8611 });
8612 true
8613 }
8614 _ => p.append_clip(0, 1 + next(9)),
8615 };
8616 invariants_hold(&p, &format!("seed {seed}, step {step}"));
8617 reloads(&p, &format!("seed {seed}, step {step}"));
8618 }
8619 }
8620 }
8621
8622 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
8623 /// there, `V1` shows again on either side of it, and a frame no video lane
8624 /// covers is a gap however many lanes there are.
8625 #[test]
8626 fn the_composite_is_the_topmost_lane_with_a_clip() {
8627 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8628 let lanes = vec![
8629 // V1: the whole 30 frames of source 0.
8630 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8631 // V2: source 1 over the middle third.
8632 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
8633 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8634 ];
8635 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
8636 assert_eq!(
8637 p.composite_spans_from(0),
8638 vec![
8639 Span {
8640 start: 0,
8641 len: 10,
8642 from: Some((0, 0)),
8643 speed: Speed::NORMAL
8644 },
8645 Span {
8646 start: 10,
8647 len: 10,
8648 from: Some((1, 5)),
8649 speed: Speed::NORMAL
8650 },
8651 Span {
8652 start: 20,
8653 len: 10,
8654 from: Some((0, 20)),
8655 speed: Speed::NORMAL
8656 },
8657 ],
8658 "V2 takes over for its own span and hands V1 back"
8659 );
8660 // A mid-span ask resolves the same way, which is what a seek does.
8661 assert_eq!(
8662 p.composite_span_at(15),
8663 Some(Span {
8664 start: 15,
8665 len: 5,
8666 from: Some((1, 10)),
8667 speed: Speed::NORMAL
8668 })
8669 );
8670 assert_eq!(p.composite_span_at(30), None, "past the end");
8671
8672 // A hole in V1 under V2's clip: black between the two, and black after
8673 // both run out (the audio lane is still holding the timeline open).
8674 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8675 let holed = vec![
8676 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
8677 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
8678 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8679 ];
8680 let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts");
8681 assert_eq!(
8682 p.composite_spans_from(0),
8683 vec![
8684 Span {
8685 start: 0,
8686 len: 5,
8687 from: Some((0, 0)),
8688 speed: Speed::NORMAL
8689 },
8690 Span {
8691 start: 5,
8692 len: 5,
8693 from: None,
8694 speed: Speed::NORMAL
8695 },
8696 Span {
8697 start: 10,
8698 len: 10,
8699 from: Some((1, 0)),
8700 speed: Speed::NORMAL
8701 },
8702 Span {
8703 start: 20,
8704 len: 10,
8705 from: None,
8706 speed: Speed::NORMAL
8707 },
8708 ]
8709 );
8710
8711 // One video lane: the composite *is* that lane, span for span -- the
8712 // promise every existing two-lane project rests on.
8713 let p = Project::single(FILE, 30);
8714 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
8715 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
8716 }
8717
8718 /// Every audio lane holding something gets a play list, and only those.
8719 #[test]
8720 fn audio_segments_cover_every_lane_that_holds_something() {
8721 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
8722 let lanes = vec![
8723 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8724 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
8725 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
8726 (LaneKind::Audio, Vec::new()),
8727 ];
8728 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
8729 let lists = p.audio_segments_from(0, FPS);
8730 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
8731 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
8732 // A2 is a gap up to frame 15, then the whole of source 1.
8733 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
8734
8735 // No audio lane holds anything: one all-gap list, so such a timeline
8736 // still plays silence against a master clock.
8737 let p = Project::from_parts(
8738 vec![Source::new(FILE, 0)],
8739 vec![
8740 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
8741 (LaneKind::Audio, Vec::new()),
8742 ],
8743 vec![],
8744 vec![],
8745 )
8746 .expect("valid parts");
8747 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
8748 }
8749}