edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·33ae7d9·Tahinli·3 months ago·699 commits
| 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 | |
| 76 | use crate::map::TimelineMap; |
| 77 | use std::path::{Path, PathBuf}; |
| 78 | |
| 79 | use crate::color::ColorParams; |
| 80 | use crate::transform::TransformParams; |
| 81 | use crate::eq::EqParams; |
| 82 | use crate::limiter::{Limiter, db_to_linear}; |
| 83 | use crate::scale::FitPolicy; |
| 84 | use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack}; |
| 85 | |
| 86 | /// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). |
| 87 | /// -60 dB is a thousandth of the amplitude -- a track that is out of the mix |
| 88 | /// for every purpose but the honest one, which is that it is still a level and |
| 89 | /// not a mute. |
| 90 | pub const MIN_GAIN_DB: f32 = -60.0; |
| 91 | /// ...and how far up. +12 dB is four times the amplitude, which is as much as |
| 92 | /// a mix bus can take before the limiter is doing all the work. |
| 93 | pub const MAX_GAIN_DB: f32 = 12.0; |
| 94 | |
| 95 | /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it |
| 96 | /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for |
| 97 | /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly |
| 98 | /// comparable nor exactly writable, and `.edith` has to read back the very |
| 99 | /// number that was set. A thousandth is finer than any card can drag and coarser |
| 100 | /// than any rounding anyone can hear. |
| 101 | /// |
| 102 | /// The rate alone: the audio path time-stretches a speeded clip |
| 103 | /// (`crate::stretch`), so its pitch stays where it was recorded while its |
| 104 | /// seconds compress or stretch -- the tape effect this used to be is gone. |
| 105 | /// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed, |
| 106 | /// [`Speed::MAX`] four times. |
| 107 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] |
| 108 | pub struct Speed(u16); |
| 109 | |
| 110 | /// What [`Project::parts`] hands back: the comparable shape of everything an |
| 111 | /// edit can change, for the sweep's undo round-trip. Test-only, like every |
| 112 | /// accessor it exists for: the sweep lives behind `cfg(test)`. |
| 113 | #[cfg(test)] |
| 114 | #[derive(Clone, Debug, PartialEq)] |
| 115 | pub(crate) struct SweepParts( |
| 116 | pub(crate) usize, |
| 117 | pub(crate) Vec<(LaneKind, Vec<Clip>)>, |
| 118 | pub(crate) Vec<Vec<SubClip>>, |
| 119 | ); |
| 120 | |
| 121 | impl Speed { |
| 122 | /// Real time -- what every clip is until something says otherwise, and the |
| 123 | /// value every path in this engine short-circuits on. |
| 124 | pub const NORMAL: Speed = Speed(1000); |
| 125 | pub const MIN: Speed = Speed(250); |
| 126 | pub const MAX: Speed = Speed(4000); |
| 127 | |
| 128 | /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse) |
| 129 | /// unrepresentable rather than merely refused: nothing downstream divides |
| 130 | /// by a speed that could be nothing. |
| 131 | pub fn from_permille(permille: u16) -> Self { |
| 132 | Speed(permille.clamp(Self::MIN.0, Self::MAX.0)) |
| 133 | } |
| 134 | |
| 135 | pub fn permille(self) -> u16 { |
| 136 | self.0 |
| 137 | } |
| 138 | |
| 139 | pub fn is_normal(self) -> bool { |
| 140 | self == Self::NORMAL |
| 141 | } |
| 142 | |
| 143 | /// As a multiplier, for the sound worker and for a label. |
| 144 | pub fn as_f64(self) -> f64 { |
| 145 | f64::from(self.0) / 1000. |
| 146 | } |
| 147 | |
| 148 | /// How many *timeline* frames `source` source frames occupy at this rate -- |
| 149 | /// the clip's footprint. Rounded to the nearest frame and **never zero**: a |
| 150 | /// clip that occupied no frames would be an empty placement, which the lane |
| 151 | /// invariant forbids and which nothing could ever click on again. |
| 152 | pub fn frames(self, source: u32) -> u32 { |
| 153 | let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0); |
| 154 | n.clamp(1, u64::from(u32::MAX)) as u32 |
| 155 | } |
| 156 | |
| 157 | /// The mapping itself: which source frame of a clip the `offset`th timeline |
| 158 | /// frame of it plays. Floored, so the first timeline frame is the clip's own |
| 159 | /// in-point at every rate. |
| 160 | pub fn source_at(self, offset: u32) -> u32 { |
| 161 | (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32 |
| 162 | } |
| 163 | |
| 164 | /// Its inverse, for a decoder's frames on their way back out: which timeline |
| 165 | /// frame of the clip the `offset`th *source* frame of it lands on. |
| 166 | /// |
| 167 | /// **Ceil, and that is the whole point of the pair.** Playback stamps every |
| 168 | /// decoded frame with this and shows the newest whose stamp has come due, so |
| 169 | /// what is on screen at timeline offset `d` is the last source frame with |
| 170 | /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that |
| 171 | /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an |
| 172 | /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding |
| 173 | /// the two the same way would put the preview a frame off the export at some |
| 174 | /// speeds and a whole held frame off at slow ones -- drift that no test of |
| 175 | /// either side alone would catch. |
| 176 | pub fn timeline_at(self, offset: u32) -> u32 { |
| 177 | (u64::from(offset) * 1000) |
| 178 | .div_ceil(u64::from(self.0)) |
| 179 | .min(u64::from(u32::MAX)) as u32 |
| 180 | } |
| 181 | |
| 182 | /// The longest source range that still *fits* in `frames` timeline frames at |
| 183 | /// this rate -- and `None` when **nothing** does, which at a quarter speed is |
| 184 | /// any room narrower than the four timeline frames one source frame occupies. |
| 185 | /// |
| 186 | /// What a trim commits and what a hole-punch leaves behind: rounding could |
| 187 | /// otherwise hand back a range wider than the room, and a clip that outgrew |
| 188 | /// its room would overlap its neighbour -- the one thing a lane may never do. |
| 189 | /// `None` is not an error, it is "no remainder": the caller drops that piece |
| 190 | /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this |
| 191 | /// is `frames` itself, so nothing about an unspeeded edit changes. |
| 192 | pub fn fit(self, frames: u32) -> Option<u32> { |
| 193 | if frames == 0 || self.frames(1) > frames { |
| 194 | return None; |
| 195 | } |
| 196 | let mut src = self.source_at(frames).max(1); |
| 197 | // At most a step or two: `frames` is monotone in `src` and the rounding |
| 198 | // above can only overshoot by one source frame's worth. |
| 199 | while src > 1 && self.frames(src) > frames { |
| 200 | src -= 1; |
| 201 | } |
| 202 | Some(src) |
| 203 | } |
| 204 | |
| 205 | /// How many timeline frames `source` source frames of head (or tail) are |
| 206 | /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of |
| 207 | /// them, which is why this is not [`frames`](Speed::frames): a clip is never |
| 208 | /// empty, but the room in front of one may well be. |
| 209 | pub fn room(self, source: u32) -> u32 { |
| 210 | match source { |
| 211 | 0 => 0, |
| 212 | n => self.frames(n), |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// How many timeline frames from `offset` on show the **same** source frame: |
| 217 | /// one at real time and faster, more when the clip is slowed. What an export |
| 218 | /// encodes without decoding the same picture twice, and the count that makes |
| 219 | /// its frame walk exactly as long as the span. |
| 220 | pub fn repeats(self, offset: u32, len: u32) -> u32 { |
| 221 | let want = self.source_at(offset); |
| 222 | (offset..len) |
| 223 | .take_while(|&t| self.source_at(t) == want) |
| 224 | .count() as u32 |
| 225 | } |
| 226 | |
| 227 | /// Where in the source a cut `offset` timeline frames into a clip of `len` |
| 228 | /// source frames falls -- and `None` when this rate cannot address that |
| 229 | /// frame at all. |
| 230 | /// |
| 231 | /// At half speed a clip of ten source frames is twenty timeline frames long |
| 232 | /// and every source frame is on screen twice, so a cut between the two |
| 233 | /// showings of one frame is not a cut in the *file*: taking it would leave |
| 234 | /// two halves whose lengths no longer add up to the clip that was cut -- |
| 235 | /// a hole in the lane, or an overlap of the next clip. Refused instead, so |
| 236 | /// the model stays exact and the front-end can say why. At real time every |
| 237 | /// interior frame answers, which is the path a project without speeds is on. |
| 238 | pub fn split_at(self, len: u32, offset: u32) -> Option<u32> { |
| 239 | let src = self.source_at(offset); |
| 240 | (src > 0 |
| 241 | && src < len |
| 242 | && self.frames(src) == offset |
| 243 | && self.frames(len - src) == self.frames(len) - offset) |
| 244 | .then_some(src) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | impl Default for Speed { |
| 249 | fn default() -> Self { |
| 250 | Self::NORMAL |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | impl std::fmt::Display for Speed { |
| 255 | /// `2.00x` -- what a card prints and what a clip box is marked with. |
| 256 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 257 | write!(f, "{:.2}x", self.as_f64()) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// What a file's own frame rate is against the timeline's, as an exact |
| 262 | /// rational: how many frames of the *file* one frame of the timeline is worth. |
| 263 | /// |
| 264 | /// Every frame number in this module counts **timeline** frames -- a clip's |
| 265 | /// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps |
| 266 | /// timeline is as many frames long as the seconds it lasts, and every edit |
| 267 | /// (trim, split, speed, paste) is the same arithmetic it always was. This is the |
| 268 | /// one conversion, and it happens at the decoder's door: [`PlaybackSession`] |
| 269 | /// opens a worker with it and [`crate::export`] pulls pictures through it. The |
| 270 | /// file's own numbering exists nowhere else. |
| 271 | /// |
| 272 | /// The same floor/ceil pair as [`Speed`], for the same reason: the frame an |
| 273 | /// export encodes at a timeline frame has to be the frame playback is holding |
| 274 | /// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps |
| 275 | /// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`). |
| 276 | /// |
| 277 | /// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and |
| 278 | /// stays `800/1001` however far the timeline runs, where a rate rounded to |
| 279 | /// (say) milli-fps would leave a fraction of a frame per clip to pile up into a |
| 280 | /// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`). |
| 281 | /// |
| 282 | /// [`PlaybackSession`]: crate::PlaybackSession |
| 283 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 284 | pub struct Rate { |
| 285 | /// Frames of the file... |
| 286 | source: u32, |
| 287 | /// ...per this many frames of the timeline it plays on. Never zero. |
| 288 | timeline: u32, |
| 289 | } |
| 290 | |
| 291 | impl Rate { |
| 292 | /// A file shot at the timeline's own rate: every conversion below is the |
| 293 | /// identity, which is the path a single-rate project is on. |
| 294 | pub const REAL_TIME: Self = Self { |
| 295 | source: 1, |
| 296 | timeline: 1, |
| 297 | }; |
| 298 | |
| 299 | /// The rate of a file at `source_fps` on a timeline at `timeline_fps`, |
| 300 | /// exactly. |
| 301 | /// |
| 302 | /// Both rates come out of a container as a division, so neither is ever the |
| 303 | /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what |
| 304 | /// already knows how to name one exactly -- it is the same pair the muxer |
| 305 | /// counts an export's frames in -- and this is that pair divided by that |
| 306 | /// pair, reduced. A rate no timescale can name is an `Err` in that |
| 307 | /// function's own words rather than a silent 1:1 -- `matches_timeline` is |
| 308 | /// where a file carrying one is refused by name, beside the codec. |
| 309 | /// |
| 310 | /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every |
| 311 | /// timeline that had ever opened in this editor before mixed rates. |
| 312 | pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> { |
| 313 | let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?; |
| 314 | let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?; |
| 315 | // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). |
| 316 | let num = u64::from(src_scale) * u64::from(tl_ticks); |
| 317 | let den = u64::from(src_ticks) * u64::from(tl_scale); |
| 318 | Ok(Self::reduced(num, den)) |
| 319 | } |
| 320 | |
| 321 | /// `num` frames of a file per `den` frames of a timeline, in lowest terms. |
| 322 | fn reduced(num: u64, den: u64) -> Self { |
| 323 | let g = gcd(num, den); |
| 324 | let (mut num, mut den) = (num / g, den / g); |
| 325 | // A ratio no pair of real frame rates produces, but the fields are `u32` |
| 326 | // so that every multiplication below fits a `u64` at any frame count. |
| 327 | while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { |
| 328 | (num, den) = (num.div_ceil(2), den.div_ceil(2)); |
| 329 | } |
| 330 | Self { |
| 331 | source: num.max(1) as u32, |
| 332 | timeline: den.max(1) as u32, |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /// The same file against a timeline that has itself been retimed: `self` is |
| 337 | /// its frames per frame of the old timeline and `k` is old frames per new |
| 338 | /// one, so this is its frames per frame of the *new* one -- exactly, without |
| 339 | /// going back through an `f64` fps that names neither rate |
| 340 | /// ([`crate::PlaybackSession::set_frame_rate`]). |
| 341 | pub fn then(self, k: Rate) -> Self { |
| 342 | Self::reduced( |
| 343 | u64::from(self.source) * u64::from(k.source), |
| 344 | u64::from(self.timeline) * u64::from(k.timeline), |
| 345 | ) |
| 346 | } |
| 347 | |
| 348 | pub fn is_real_time(self) -> bool { |
| 349 | self.source == self.timeline |
| 350 | } |
| 351 | |
| 352 | /// As a multiplier of the timeline's rate: what a *file's* own frame rate |
| 353 | /// is, given the timeline's, for a library row that names it. |
| 354 | pub fn as_f64(self) -> f64 { |
| 355 | f64::from(self.source) / f64::from(self.timeline) |
| 356 | } |
| 357 | |
| 358 | /// Which frame of the file the `frame`th timeline-rate frame of it is: |
| 359 | /// floored, [`Speed::source_at`]'s half of the pair. |
| 360 | pub fn source_at(self, frame: u32) -> u32 { |
| 361 | (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline)) |
| 362 | .min(u64::from(u32::MAX)) as u32 |
| 363 | } |
| 364 | |
| 365 | /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first |
| 366 | /// timeline-rate frame that shows source frame `source_frame` -- which is |
| 367 | /// the stamp playback puts on a decoded picture, and, applied to a file's |
| 368 | /// frame *count*, how long that file is in timeline frames. |
| 369 | pub fn timeline_at(self, source_frame: u32) -> u32 { |
| 370 | (u64::from(source_frame) * u64::from(self.timeline)) |
| 371 | .div_ceil(u64::from(self.source)) |
| 372 | .min(u64::from(u32::MAX)) as u32 |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | /// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its |
| 377 | /// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it. |
| 378 | fn gcd(a: u64, b: u64) -> u64 { |
| 379 | match b { |
| 380 | 0 => a.max(1), |
| 381 | b => gcd(b, a % b), |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | /// A half-open `[in_frame, out_frame)` range of frames of source |
| 386 | /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). |
| 387 | /// Never empty. |
| 388 | /// |
| 389 | /// Counted at the **timeline's** frame rate, not the file's: a source shot at |
| 390 | /// another rate is converted at the decoder's door ([`Rate`]), so every edit |
| 391 | /// here is frames of one clock. |
| 392 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 393 | pub struct Clip { |
| 394 | /// Timeline frame the clip's first frame is shown at. Meaningless on a |
| 395 | /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it |
| 396 | /// with where the caller asked for. |
| 397 | pub start: u32, |
| 398 | pub in_frame: u32, |
| 399 | pub out_frame: u32, |
| 400 | /// Index into [`Project::sources`]. |
| 401 | pub source: usize, |
| 402 | /// Group id: clips sharing one were split from the same take. `None` for a |
| 403 | /// clip that belongs to no group. |
| 404 | pub link: Option<u32>, |
| 405 | /// Index into the project's equalizer table |
| 406 | /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays |
| 407 | /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this |
| 408 | /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a |
| 409 | /// plain assignment. The table is append-only within a session, so an index |
| 410 | /// on a clipboard clip or inside an undo snapshot can never dangle. |
| 411 | pub eq: Option<u16>, |
| 412 | /// Index into the project's colour table |
| 413 | /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that |
| 414 | /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same |
| 415 | /// promises: `Copy`, append-only within a session, never dangling. |
| 416 | pub color: Option<u16>, |
| 417 | /// Index into the project's transform table |
| 418 | /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a |
| 419 | /// clip that plays at its fit policy's own placement. An index for |
| 420 | /// [`Clip::color`]'s reason and with the same promises. |
| 421 | pub transform: Option<u16>, |
| 422 | /// How this clip's picture meets a project canvas of another shape |
| 423 | /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the |
| 424 | /// two above: it is one byte with no parameters, so there is nothing for a |
| 425 | /// table to share, and a clip that is the project's own size never consults |
| 426 | /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars |
| 427 | /// where the aspect does not agree. |
| 428 | pub fit: FitPolicy, |
| 429 | /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the |
| 430 | /// eq and colour indexes: it is two bytes with nothing to share, and a table |
| 431 | /// would put a level of indirection between the mapping and the one number |
| 432 | /// every frame of it is divided by. |
| 433 | /// |
| 434 | /// It does **not** move `in_frame`/`out_frame`: those stay the source range |
| 435 | /// the clip plays, so a trim and a split still address the file. What it |
| 436 | /// changes is how many *timeline* frames that range is spread over |
| 437 | /// ([`Clip::frames`]). |
| 438 | pub speed: Speed, |
| 439 | /// Timeline frames of ramp-up from silence at the clip's own start, inline |
| 440 | /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small |
| 441 | /// number with nothing to share, and every consumer (mixer, exporter) wants |
| 442 | /// it sitting right next to the frame range it shapes. Clamped to the |
| 443 | /// clip's own length by the setter -- never wider than the clip is long. |
| 444 | pub fade_in: u32, |
| 445 | /// Timeline frames of ramp-down to silence at the clip's own end. Same |
| 446 | /// promises as [`Clip::fade_in`]. |
| 447 | pub fade_out: u32, |
| 448 | /// Timeline frames of cross-dissolve into the clip immediately after this |
| 449 | /// one on the same video lane, at this clip's own end -- `0` for a hard |
| 450 | /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same |
| 451 | /// reason, and clamped the same way by its setter |
| 452 | /// ([`Project::set_transition_out`]): never wider than this clip's own |
| 453 | /// length, nor than the successor it dissolves into. Meaningless -- and |
| 454 | /// left as whatever it was -- the moment the next clip stops abutting |
| 455 | /// this one; a reader that cares checks adjacency itself rather than |
| 456 | /// trusting this field alone, exactly as a stored fade is trusted only |
| 457 | /// because a clip's own length is checked beside it. |
| 458 | pub transition_out: u32, |
| 459 | } |
| 460 | |
| 461 | impl Clip { |
| 462 | /// Source frame count; `>= 1` by the never-empty invariant. What the clip |
| 463 | /// reads out of its file -- not how long it is on the timeline, which is |
| 464 | /// [`Clip::frames`] and differs the moment it is speeded. |
| 465 | pub fn len(&self) -> u32 { |
| 466 | self.out_frame - self.in_frame |
| 467 | } |
| 468 | |
| 469 | /// Timeline frames it occupies: its source range at its own speed, never |
| 470 | /// zero (see [`Speed::frames`]). Every placement question -- where it ends, |
| 471 | /// what it overlaps, how wide its box is -- is asked of this and not of |
| 472 | /// [`Clip::len`]. |
| 473 | pub fn frames(&self) -> u32 { |
| 474 | self.speed.frames(self.len()) |
| 475 | } |
| 476 | |
| 477 | /// One past the last timeline frame it covers. |
| 478 | pub fn end(&self) -> u32 { |
| 479 | self.start + self.frames() |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// A file the timeline plays from, and *which* of its audio streams it plays: |
| 484 | /// a file carrying one track per language is several sources, one per stream, |
| 485 | /// sharing a path. Two entries differing only in the stream are two sources -- |
| 486 | /// they are what a clip names, and a clip plays exactly one stream. |
| 487 | /// |
| 488 | /// The path is always canonical ([`Source::new`]), so the same file reached by |
| 489 | /// two paths is one source. |
| 490 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 491 | pub struct Source { |
| 492 | pub path: PathBuf, |
| 493 | /// Position among the file's audio tracks in file order, the numbering |
| 494 | /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a |
| 495 | /// single track, and for a silent one. |
| 496 | pub audio_stream: usize, |
| 497 | } |
| 498 | |
| 499 | impl Source { |
| 500 | pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self { |
| 501 | Self { |
| 502 | path: canonical(path.as_ref()), |
| 503 | audio_stream, |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// What a lane carries, which is what a *gap* in it means: black frames on a |
| 509 | /// video lane, silence on an audio one, nothing over the picture on a subtitle |
| 510 | /// one. |
| 511 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 512 | pub enum LaneKind { |
| 513 | Video, |
| 514 | Audio, |
| 515 | /// Words over the picture, placed and trimmed like everything else |
| 516 | /// ([`SubClip`]). A lane of its own rather than a setting on the project, |
| 517 | /// so a caption is dragged, cut, rippled and undone by the machinery every |
| 518 | /// other clip already goes through. |
| 519 | /// |
| 520 | /// It carries no [`Clip`] at all, and that is what keeps the media paths |
| 521 | /// free of it: [`Project::lane`] hands back an empty slice, so every |
| 522 | /// clip-indexed call ([`Project::trim`], [`Project::set_eq`], |
| 523 | /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds |
| 524 | /// check it already had, [`Project::composite_span_at`] and |
| 525 | /// [`Project::audio_lanes`] never look at it, and the three doors that |
| 526 | /// could still put a picture on one -- [`Project::from_parts`], |
| 527 | /// [`Project::place`], [`Project::append_clip`] -- say so by name. |
| 528 | Subtitle, |
| 529 | } |
| 530 | |
| 531 | /// Which lane an operation acts on: a kind plus a 0-based position among the |
| 532 | /// lanes of that kind, so [`Lane::V1`] is the first video lane and |
| 533 | /// `Lane::new(LaneKind::Audio, 1)` is `A2`. |
| 534 | /// |
| 535 | /// A handle, not the lane itself. It stays meaningful while lanes are added, |
| 536 | /// and one naming a lane that is not there reads as an empty lane and refuses |
| 537 | /// every mutation -- a front-end that always asks for `V1`/`A1` needs no |
| 538 | /// bounds check of its own. |
| 539 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 540 | pub struct Lane { |
| 541 | pub kind: LaneKind, |
| 542 | pub ord: usize, |
| 543 | } |
| 544 | |
| 545 | impl Lane { |
| 546 | /// The first video lane: what a decoder plays and what an export renders. |
| 547 | pub const V1: Lane = Lane::new(LaneKind::Video, 0); |
| 548 | /// The first audio lane: what the audio worker plays. |
| 549 | pub const A1: Lane = Lane::new(LaneKind::Audio, 0); |
| 550 | /// The first subtitle lane -- the one a project has only once something |
| 551 | /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1` |
| 552 | /// alone. |
| 553 | pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0); |
| 554 | |
| 555 | pub const fn new(kind: LaneKind, ord: usize) -> Self { |
| 556 | Self { kind, ord } |
| 557 | } |
| 558 | |
| 559 | /// `V1`, `A2`: how a lane is written in a header column and named in an |
| 560 | /// error about it. |
| 561 | pub fn label(self) -> String { |
| 562 | let kind = match self.kind { |
| 563 | LaneKind::Video => 'V', |
| 564 | LaneKind::Audio => 'A', |
| 565 | LaneKind::Subtitle => 'S', |
| 566 | }; |
| 567 | format!("{kind}{}", self.ord + 1) |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | /// A placed subtitle: a `[in_us, out_us)` window of one of the project's |
| 572 | /// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from |
| 573 | /// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames) |
| 574 | /// frames. Never empty at either end. |
| 575 | /// |
| 576 | /// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle |
| 577 | /// actually has, and placed by the same one number: the window is in the |
| 578 | /// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the |
| 579 | /// placement is in timeline frames like everything else on a lane. So the lane |
| 580 | /// invariant is the lane's ([`subs_sorted_disjoint`] is |
| 581 | /// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing |
| 582 | /// else, and only the two calls that change a *duration* -- a trim, and the |
| 583 | /// mapping out -- ever need the timeline's rate. |
| 584 | /// |
| 585 | /// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a |
| 586 | /// paste and an undo snapshot are a plain assignment and can never dangle. |
| 587 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 588 | pub struct SubClip { |
| 589 | /// Timeline frame its first frame is shown at. |
| 590 | pub start: u32, |
| 591 | /// How many timeline frames it covers; `>= 1`. Held rather than derived |
| 592 | /// from the window because a [`Project`] has no frame rate -- the rate |
| 593 | /// enters at the door of the two calls that need it -- and every placement |
| 594 | /// question (where it ends, what it overlaps) is asked in frames. |
| 595 | pub frames: u32, |
| 596 | /// Index into [`Project::subtitles`]: *which* track's words these are. |
| 597 | pub track: usize, |
| 598 | /// The half-open window of that track it shows, in microseconds from the |
| 599 | /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are |
| 600 | /// timed in, so no conversion stands between a cue and the window that |
| 601 | /// keeps it. |
| 602 | pub in_us: i64, |
| 603 | pub out_us: i64, |
| 604 | /// Group id: `Some` exactly when a hand put this caption in a group with |
| 605 | /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in |
| 606 | /// no group, and what a cut cuts apart loses the one it had |
| 607 | /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a |
| 608 | /// clip is what makes the caption move, trim and delete with it. |
| 609 | pub link: Option<u32>, |
| 610 | } |
| 611 | |
| 612 | impl SubClip { |
| 613 | /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and |
| 614 | /// what every overlap question is asked of. |
| 615 | pub fn end(&self) -> u32 { |
| 616 | self.start + self.frames |
| 617 | } |
| 618 | |
| 619 | /// How much of its track it shows, in microseconds; `>= 1` by the |
| 620 | /// never-empty invariant. |
| 621 | pub fn window_us(&self) -> i64 { |
| 622 | self.out_us - self.in_us |
| 623 | } |
| 624 | |
| 625 | /// Where in its window the timeline frame `frame` falls, in microseconds -- |
| 626 | /// the cut a split, a ripple and a trim all land on. |
| 627 | /// |
| 628 | /// By proportion and not by the timeline's rate: the window and the frame |
| 629 | /// count measure the same stretch of time, so the fraction of the frames |
| 630 | /// before `frame` is the fraction of the microseconds before it. That is |
| 631 | /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins |
| 632 | /// without either of them learning an fps. |
| 633 | fn window_at(&self, frame: u32) -> i64 { |
| 634 | let into = i64::from(frame.saturating_sub(self.start)); |
| 635 | self.in_us + self.window_us() * into / i64::from(self.frames.max(1)) |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | /// One lane: what it is and what it holds. A struct rather than a bare |
| 640 | /// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a |
| 641 | /// compositing mode, a name -- and it belongs next to the clips it applies to. |
| 642 | #[derive(Clone, Debug)] |
| 643 | struct LaneData { |
| 644 | kind: LaneKind, |
| 645 | /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a |
| 646 | /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from |
| 647 | /// ever seeing a subtitle: they all read this list. |
| 648 | clips: Vec<Clip>, |
| 649 | /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always |
| 650 | /// empty on a video or audio one. Beside the clips rather than an enum over |
| 651 | /// them so that everything a lane *is* -- its place in the stack, its |
| 652 | /// label, its undo snapshot, its removal -- stays one code path for all |
| 653 | /// three kinds. |
| 654 | subs: Vec<SubClip>, |
| 655 | /// How loud this lane plays, in dB, `0.0` for one nobody has touched -- |
| 656 | /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what |
| 657 | /// makes it a different thing from a clip's equalizer: it moves everything |
| 658 | /// on the track by the same amount, cuts included. Meaningless on a video |
| 659 | /// lane, where it is kept at 0 and asked by nothing. |
| 660 | gain_db: f32, |
| 661 | } |
| 662 | |
| 663 | impl LaneData { |
| 664 | fn new(kind: LaneKind, clips: Vec<Clip>) -> Self { |
| 665 | Self { |
| 666 | kind, |
| 667 | clips, |
| 668 | subs: Vec::new(), |
| 669 | gain_db: 0.0, |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | /// The two lanes a project starts with: `V1` then `A1`, in display order. |
| 674 | /// One place, because a freshly opened file is exactly this pair. |
| 675 | fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> { |
| 676 | vec![ |
| 677 | LaneData::new(LaneKind::Video, video), |
| 678 | LaneData::new(LaneKind::Audio, audio), |
| 679 | ] |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | /// The placements one group id names, split by the two lists a lane holds: |
| 684 | /// what a drag, a trim and a delete each have to walk, now that a group may |
| 685 | /// hold a caption beside its clips ([`Project::group_all`]). A clip and a |
| 686 | /// caption of one group never share a lane -- a subtitle lane holds no `Clip` |
| 687 | /// -- so the pairs are `(lane storage index, index into that lane's list)`. |
| 688 | #[derive(Default)] |
| 689 | struct Members { |
| 690 | clips: Vec<(usize, usize)>, |
| 691 | subs: Vec<(usize, usize)>, |
| 692 | } |
| 693 | |
| 694 | impl Members { |
| 695 | /// Whether the group is the one placement and no more: what a lift leaves |
| 696 | /// behind, and what every whole-group question answers "not one" for. |
| 697 | fn alone(&self) -> bool { |
| 698 | self.clips.len() + self.subs.len() < 2 |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | /// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed. |
| 703 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 704 | pub enum Edge { |
| 705 | /// Its first timeline frame; moving it changes where in the source the clip |
| 706 | /// starts reading, so the picture behind the edge slides with it. |
| 707 | Start, |
| 708 | /// One past its last timeline frame; moving it only says how much of the |
| 709 | /// source to keep. |
| 710 | End, |
| 711 | } |
| 712 | |
| 713 | /// What a lane holds over one stretch of the timeline: either a placed clip or |
| 714 | /// a gap. Returned already trimmed to the position it was asked about, so a |
| 715 | /// caller can hand `len` straight to a decoder (or to a black-frame generator). |
| 716 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 717 | pub struct Span { |
| 718 | /// Timeline frame the span starts at. |
| 719 | pub start: u32, |
| 720 | /// Frames it covers; `>= 1`. |
| 721 | pub len: u32, |
| 722 | /// `(source index, first source frame)`, or `None` for a gap -- which the |
| 723 | /// engine renders as black frames and as silence. |
| 724 | pub from: Option<(usize, u32)>, |
| 725 | /// The rate the clip this came off plays at ([`Clip::speed`]); |
| 726 | /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is |
| 727 | /// timeline frames whatever it says -- the speed is how many *source* frames |
| 728 | /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers |
| 729 | /// come back to the timeline. |
| 730 | pub speed: Speed, |
| 731 | } |
| 732 | |
| 733 | impl Span { |
| 734 | /// One past the last timeline frame it covers. |
| 735 | pub fn end(&self) -> u32 { |
| 736 | self.start + self.len |
| 737 | } |
| 738 | |
| 739 | /// How many source frames it reads: what a decoder is asked for and how wide |
| 740 | /// an audio window is. `len` at real time, and the one arithmetic both the |
| 741 | /// picture and the sound go through, so they cannot disagree about where a |
| 742 | /// speeded clip ends. |
| 743 | pub fn source_len(&self) -> u32 { |
| 744 | match self.from { |
| 745 | // The last timeline frame's own source frame is the last one needed |
| 746 | // -- never one more, which at a slow rate would read a frame the |
| 747 | // next clip owns and at a fast one would decode a picture nothing |
| 748 | // shows. |
| 749 | Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1, |
| 750 | None => self.len, |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | /// Where a source frame of this span lands on the timeline: the stamp |
| 755 | /// playback puts on a decoded frame, through the ceil half of the pair |
| 756 | /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source |
| 757 | /// frame, so a frame before it stamps at the span's start. |
| 758 | pub fn timeline_at(&self, source_frame: u32) -> u32 { |
| 759 | let base = self.from.map_or(0, |(_, in_frame)| in_frame); |
| 760 | self.start + self.speed.timeline_at(source_frame.saturating_sub(base)) |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | /// What one speeded audio segment asks of the worker: how many source frames to |
| 765 | /// consume per output frame, and how many seconds of timeline it has to fill. |
| 766 | /// [`Project::audio_speeds_from`] builds it; `None` there means real time and no |
| 767 | /// resampling at all. |
| 768 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 769 | pub struct Stretch { |
| 770 | /// Source frames per output frame -- the speed as a multiplier. |
| 771 | pub step: f64, |
| 772 | /// What the segment owes the timeline, which is what it is padded or |
| 773 | /// trimmed to. |
| 774 | pub timeline_secs: f64, |
| 775 | } |
| 776 | |
| 777 | /// What one audio segment's gain envelope is: [`Project::audio_fades_from`] |
| 778 | /// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved |
| 779 | /// against where in the *clip* -- not the segment, which may start mid-clip |
| 780 | /// on a seek -- this segment's first frame lands. |
| 781 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 782 | pub struct Fade { |
| 783 | /// How many of the clip's own frames already played before this |
| 784 | /// segment's first frame: `0` unless playback started mid-clip. |
| 785 | pub elapsed: u32, |
| 786 | /// The clip's [`Clip::fade_in`]. |
| 787 | pub fade_in: u32, |
| 788 | /// The clip's [`Clip::fade_out`]. |
| 789 | pub fade_out: u32, |
| 790 | /// The clip's own [`Clip::frames`] -- the envelope's whole width, of |
| 791 | /// which this segment may only cover the tail. |
| 792 | pub total: u32, |
| 793 | } |
| 794 | |
| 795 | impl Fade { |
| 796 | /// The gain at clip-relative frame `pos`, an equal-power curve on each |
| 797 | /// edge that plays through unchanged (gain `1.0`) wherever neither ramp |
| 798 | /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the |
| 799 | /// ramp, so a fade lands on silence at its very first (or very last) |
| 800 | /// frame and reaches unity smoothly rather than at a constant slope -- |
| 801 | /// the same curve [`Project::crossfade`] relies on to keep two clips' |
| 802 | /// sum around one level through the join. Both ramps multiply where a |
| 803 | /// clip is short enough for them to overlap. |
| 804 | fn gain_at(self, pos: u32) -> f32 { |
| 805 | let mut g = 1.0f32; |
| 806 | if self.fade_in > 0 && pos < self.fade_in { |
| 807 | let t = pos as f32 / self.fade_in as f32; |
| 808 | g *= (t * std::f32::consts::FRAC_PI_2).sin(); |
| 809 | } |
| 810 | if self.fade_out > 0 { |
| 811 | let out_start = self.total.saturating_sub(self.fade_out); |
| 812 | if pos >= out_start { |
| 813 | let remaining = self.total.saturating_sub(pos); |
| 814 | let t = remaining as f32 / self.fade_out as f32; |
| 815 | g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin(); |
| 816 | } |
| 817 | } |
| 818 | g |
| 819 | } |
| 820 | |
| 821 | /// Multiplies `frames` in place -- `channels`-wide interleaved samples, |
| 822 | /// starting at this segment's own frame `0` -- by [`Self::gain_at`]. |
| 823 | pub fn apply(self, frames: &mut [f32], channels: usize) { |
| 824 | for (i, block) in frames.chunks_mut(channels).enumerate() { |
| 825 | let g = self.gain_at(self.elapsed.saturating_add(i as u32)); |
| 826 | for s in block { |
| 827 | *s *= g; |
| 828 | } |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | /// Every field re-counted at `ratio` frames-out per frame-in, rounded to |
| 833 | /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade` |
| 834 | /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip |
| 835 | /// position is in) but [`Self::apply`] multiplies *audio* frames -- |
| 836 | /// `channels`-wide sample blocks at whatever rate the mix is running at, |
| 837 | /// which is almost never the video's fps. Left unconverted, `elapsed` (an |
| 838 | /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a |
| 839 | /// few milliseconds into any clip, so a fade-out silenced the rest of the |
| 840 | /// clip outright and a fade-in finished before a listener's ear caught up |
| 841 | /// -- audible on nothing shorter than a clip a few fps-frames long, which |
| 842 | /// is why 338 green tests never once ran the two curves out of step. |
| 843 | /// `ratio` is `sample_rate / fps`, applied once where the audio session |
| 844 | /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]). |
| 845 | pub fn scaled(self, ratio: f64) -> Fade { |
| 846 | let conv = |f: u32| (f64::from(f) * ratio).round() as u32; |
| 847 | Fade { |
| 848 | elapsed: conv(self.elapsed), |
| 849 | fade_in: conv(self.fade_in), |
| 850 | fade_out: conv(self.fade_out), |
| 851 | total: conv(self.total), |
| 852 | } |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | /// What a save writes and a load takes back: the sources, every lane in |
| 857 | /// display order with its kind, and the equalizer and colour tables their clips |
| 858 | /// index into -- [`Project::without_orphan_sources`] out, |
| 859 | /// [`Project::from_parts`] in. |
| 860 | pub type Parts = ( |
| 861 | Vec<Source>, |
| 862 | Vec<(LaneKind, Vec<Clip>)>, |
| 863 | Vec<EqParams>, |
| 864 | Vec<ColorParams>, |
| 865 | Vec<TransformParams>, |
| 866 | ); |
| 867 | |
| 868 | /// How many undo steps a project keeps. One gesture is one step, so 100 is past |
| 869 | /// any chain a person walks back by hand, and the oldest step is dropped rather |
| 870 | /// than the history growing without end: a snapshot is the whole lane list, so |
| 871 | /// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak |
| 872 | /// that grows for as long as the session lasts. |
| 873 | const HISTORY_CAP: usize = 100; |
| 874 | |
| 875 | /// One gap a close-all sweep left open, with the frame it still starts on and |
| 876 | /// the same refusal a single [`Project::gap_take_scope`] close would have said. |
| 877 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 878 | pub struct GapSkip { |
| 879 | pub start: u32, |
| 880 | pub reason: String, |
| 881 | } |
| 882 | |
| 883 | /// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits, |
| 884 | /// skipped gaps are the take-safety refusals the sweep did not hide. |
| 885 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 886 | pub struct GapSweep { |
| 887 | pub closed: usize, |
| 888 | pub skipped: Vec<GapSkip>, |
| 889 | } |
| 890 | |
| 891 | /// The edit list plus its undo history. |
| 892 | #[derive(Clone, Debug)] |
| 893 | pub struct Project { |
| 894 | /// Append-only: never popped, never reordered. See the module docs. |
| 895 | sources: Vec<Source>, |
| 896 | /// In display order, which is the order [`Lane::ord`] counts in: the nth |
| 897 | /// lane of a kind here is that kind's `ord` n. Never empty. |
| 898 | lanes: Vec<LaneData>, |
| 899 | /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into. |
| 900 | eq: Vec<EqParams>, |
| 901 | /// The same, for [`Clip::color`]. |
| 902 | color: Vec<ColorParams>, |
| 903 | /// The same, for [`Clip::transform`]. |
| 904 | transform: Vec<TransformParams>, |
| 905 | /// Snapshots pushed *before* each successful edit; `undo` pops one. The |
| 906 | /// whole lane list, so adding a lane undoes as well. Bounded by |
| 907 | /// [`HISTORY_CAP`]: at the cap the oldest step goes. |
| 908 | history: Vec<Vec<LaneData>>, |
| 909 | /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by |
| 910 | /// [`Project::snapshot`], since a fresh edit invalidates whatever branch |
| 911 | /// the undone steps came from. Not saved to `.edith`, matching `history`. |
| 912 | redo: Vec<Vec<LaneData>>, |
| 913 | /// Never rolled back by an undo: an id retired by an undone split must not |
| 914 | /// come back and group two clips that were never together. |
| 915 | next_link: u32, |
| 916 | /// The subtitle tracks this timeline shows, in the order they were added. |
| 917 | /// Not in the lane list and not in the history snapshots, for the reason |
| 918 | /// the limiter is not: which subtitles a project carries is a setting on |
| 919 | /// it, and it is saved as a *reference* to the file the cues came out of |
| 920 | /// ([`crate::subtitle`]). |
| 921 | subtitles: Vec<SubtitleTrack>, |
| 922 | /// The master limiter every lane's sound is summed *through* |
| 923 | /// ([`Project::limiter`]). Off by default, and not in the lane list, which |
| 924 | /// is what the history snapshots hold: it is a setting on the mix, like the |
| 925 | /// project's resolution is a setting on the picture, and neither is an undo |
| 926 | /// step. |
| 927 | limiter: Limiter, |
| 928 | /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and |
| 929 | /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like |
| 930 | /// the resolution, and not in the lane snapshots for the same reason. |
| 931 | tone: crate::tonemap::Preset, |
| 932 | } |
| 933 | |
| 934 | impl Project { |
| 935 | /// `V1` and `A1`, one clip each covering the whole of `path` and the two |
| 936 | /// grouped -- the state of a freshly opened video, where the timeline is the |
| 937 | /// source. `frame_count` of 0 would break the never-empty invariant, so it |
| 938 | /// is clamped to one frame. |
| 939 | pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self { |
| 940 | let clip = Clip { |
| 941 | fade_in: 0, |
| 942 | fade_out: 0, |
| 943 | transition_out: 0, |
| 944 | start: 0, |
| 945 | in_frame: 0, |
| 946 | out_frame: frame_count.max(1), |
| 947 | source: 0, |
| 948 | link: Some(0), |
| 949 | eq: None, |
| 950 | color: None, |
| 951 | transform: None, |
| 952 | fit: FitPolicy::default(), |
| 953 | speed: Speed::NORMAL, |
| 954 | }; |
| 955 | Self { |
| 956 | // A file is opened on its first audio stream: nothing has picked |
| 957 | // one yet, and every file with audio at all has that one. |
| 958 | sources: vec![Source::new(path, 0)], |
| 959 | lanes: LaneData::two_lanes(vec![clip], vec![clip]), |
| 960 | eq: Vec::new(), |
| 961 | color: Vec::new(), |
| 962 | transform: Vec::new(), |
| 963 | history: Vec::new(), |
| 964 | redo: Vec::new(), |
| 965 | next_link: 1, |
| 966 | subtitles: Vec::new(), |
| 967 | limiter: Limiter::default(), |
| 968 | tone: crate::tonemap::Preset::default(), |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | /// A project rebuilt from a saved edit list -- the load half of |
| 973 | /// [`crate::edith`]. The lanes come in display order, each with its kind, and |
| 974 | /// an `ord` is a lane's position among the lanes of that kind, exactly as |
| 975 | /// [`Project::lanes`] hands them back. History is *not* saved, so |
| 976 | /// [`Project::undo`] is `false` until the first edit of the new session. |
| 977 | /// This is the one door untrusted parts come in through, so every invariant |
| 978 | /// every other constructor keeps is checked here, by name and in release: |
| 979 | /// no lanes at all, an empty clip, a clip naming a source (or an equalizer, |
| 980 | /// or a colour) that is not there, a clip whose end overflows, a lane that is |
| 981 | /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`] |
| 982 | /// below. |
| 983 | /// |
| 984 | /// A project whose lanes are all *empty* is not among them: an emptied |
| 985 | /// timeline is a project like any other -- it plays black and silent, it |
| 986 | /// saves, and it loads back. What a project cannot be is laneless, because |
| 987 | /// [`Project::lanes`] is what a front-end lays out and what every `Lane` |
| 988 | /// handle indexes into. |
| 989 | pub fn from_parts( |
| 990 | sources: Vec<Source>, |
| 991 | lanes: Vec<(LaneKind, Vec<Clip>)>, |
| 992 | eq: Vec<EqParams>, |
| 993 | color: Vec<ColorParams>, |
| 994 | transform: Vec<TransformParams>, |
| 995 | ) -> crate::Result<Self> { |
| 996 | if let Some(bad) = eq.iter().position(|p| !finite(p)) { |
| 997 | return Err(format!("eq {bad} holds a band that is not a finite number").into()); |
| 998 | } |
| 999 | if let Some(bad) = color.iter().position(|p| !color_finite(p)) { |
| 1000 | return Err(format!("color {bad} holds a value that is not a finite number").into()); |
| 1001 | } |
| 1002 | if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) { |
| 1003 | return Err(format!("transform {bad} holds a value that is not a finite number").into()); |
| 1004 | } |
| 1005 | if lanes.is_empty() { |
| 1006 | return Err("no lanes at all: that is not a project".into()); |
| 1007 | } |
| 1008 | let lanes: Vec<LaneData> = lanes |
| 1009 | .into_iter() |
| 1010 | .map(|(kind, clips)| LaneData::new(kind, clips)) |
| 1011 | .collect(); |
| 1012 | for (data, lane) in lanes.iter().zip(handles(&lanes)) { |
| 1013 | let name = lane.label(); |
| 1014 | // A subtitle lane carries words and never a picture |
| 1015 | // ([`LaneKind::Subtitle`]); a file that puts one there names a |
| 1016 | // source on a lane that has nothing to play it with, and every |
| 1017 | // media path below would then read a clip off a lane it does not |
| 1018 | // know about. |
| 1019 | if data.kind == LaneKind::Subtitle && !data.clips.is_empty() { |
| 1020 | return Err(format!( |
| 1021 | "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one", |
| 1022 | data.clips.len() |
| 1023 | ) |
| 1024 | .into()); |
| 1025 | } |
| 1026 | for c in &data.clips { |
| 1027 | if c.out_frame <= c.in_frame { |
| 1028 | return Err(format!( |
| 1029 | "{name} clip at {} plays the empty range [{}, {})", |
| 1030 | c.start, c.in_frame, c.out_frame |
| 1031 | ) |
| 1032 | .into()); |
| 1033 | } |
| 1034 | if c.source >= sources.len() { |
| 1035 | return Err(format!( |
| 1036 | "{name} clip at {} names source {} of {}", |
| 1037 | c.start, |
| 1038 | c.source, |
| 1039 | sources.len() |
| 1040 | ) |
| 1041 | .into()); |
| 1042 | } |
| 1043 | if c.start.checked_add(c.frames()).is_none() { |
| 1044 | return Err(format!( |
| 1045 | "{name} clip at {} runs past the last frame there is", |
| 1046 | c.start |
| 1047 | ) |
| 1048 | .into()); |
| 1049 | } |
| 1050 | if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) { |
| 1051 | return Err(format!( |
| 1052 | "{name} clip at {} names eq {} of {}", |
| 1053 | c.start, |
| 1054 | c.eq.unwrap_or_default(), |
| 1055 | eq.len() |
| 1056 | ) |
| 1057 | .into()); |
| 1058 | } |
| 1059 | if c.color.is_some_and(|i| usize::from(i) >= color.len()) { |
| 1060 | return Err(format!( |
| 1061 | "{name} clip at {} names color {} of {}", |
| 1062 | c.start, |
| 1063 | c.color.unwrap_or_default(), |
| 1064 | color.len() |
| 1065 | ) |
| 1066 | .into()); |
| 1067 | } |
| 1068 | if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) { |
| 1069 | return Err(format!( |
| 1070 | "{name} clip at {} names transform {} of {}", |
| 1071 | c.start, |
| 1072 | c.transform.unwrap_or_default(), |
| 1073 | transform.len() |
| 1074 | ) |
| 1075 | .into()); |
| 1076 | } |
| 1077 | } |
| 1078 | if !sorted_disjoint(&data.clips) { |
| 1079 | return Err(format!("the {name} lane is out of order or overlaps itself").into()); |
| 1080 | } |
| 1081 | } |
| 1082 | links_are_consistent(&lanes)?; |
| 1083 | // The counter sits past every id the file names, on either of a lane's |
| 1084 | // lists: a v16 caption may carry the highest link there is, and a |
| 1085 | // re-issued id would silently group it with the next placement that |
| 1086 | // asks for one -- the loader refusing a save the editor just wrote. |
| 1087 | let next_link = lanes |
| 1088 | .iter() |
| 1089 | .flat_map(|l| { |
| 1090 | let clips = l.clips.iter().filter_map(|c| c.link); |
| 1091 | let subs = l.subs.iter().filter_map(|s| s.link); |
| 1092 | clips.chain(subs) |
| 1093 | }) |
| 1094 | .max() |
| 1095 | // Saturating so a crafted file cannot make the counter wrap: at the |
| 1096 | // ceiling ids stop being fresh, which loses grouping, not memory. |
| 1097 | .map_or(0, |m| m.saturating_add(1)); |
| 1098 | Ok(Self { |
| 1099 | sources: sources |
| 1100 | .iter() |
| 1101 | .map(|s| Source::new(&s.path, s.audio_stream)) |
| 1102 | .collect(), |
| 1103 | lanes, |
| 1104 | eq, |
| 1105 | color, |
| 1106 | transform, |
| 1107 | history: Vec::new(), |
| 1108 | redo: Vec::new(), |
| 1109 | next_link, |
| 1110 | subtitles: Vec::new(), |
| 1111 | limiter: Limiter::default(), |
| 1112 | tone: crate::tonemap::Preset::default(), |
| 1113 | }) |
| 1114 | } |
| 1115 | |
| 1116 | /// The first video lane -- what an export renders and what a single-lane |
| 1117 | /// caller still means by "the clips". |
| 1118 | pub fn clips(&self) -> &[Clip] { |
| 1119 | self.lane(Lane::V1) |
| 1120 | } |
| 1121 | |
| 1122 | /// The clips of `lane`, or nothing at all for a lane that is not there. |
| 1123 | pub fn lane(&self, lane: Lane) -> &[Clip] { |
| 1124 | self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips) |
| 1125 | } |
| 1126 | |
| 1127 | /// Every lane's handle, in display order -- what a walk over "all lanes" |
| 1128 | /// iterates, and what a front-end lays out top to bottom. |
| 1129 | pub fn lanes(&self) -> Vec<Lane> { |
| 1130 | handles(&self.lanes) |
| 1131 | } |
| 1132 | |
| 1133 | /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane |
| 1134 | /// for every `ord` below it, and none at or above it. |
| 1135 | pub fn lane_count(&self, kind: LaneKind) -> usize { |
| 1136 | self.lanes.iter().filter(|l| l.kind == kind).count() |
| 1137 | } |
| 1138 | |
| 1139 | /// Appends an empty lane of `kind` and hands back its handle. One undo |
| 1140 | /// step, because the lane list is state a front-end shows: an added lane |
| 1141 | /// that could not be taken back would be the one edit with no way out. |
| 1142 | /// Nothing plays differently until something is placed on it. |
| 1143 | /// |
| 1144 | /// An empty lane is a lane like any other -- so is a whole project of them |
| 1145 | /// ([`Project::from_parts`]); nothing plays until something is placed. |
| 1146 | pub fn add_lane(&mut self, kind: LaneKind) -> Lane { |
| 1147 | self.snapshot(); |
| 1148 | self.lanes.push(LaneData::new(kind, Vec::new())); |
| 1149 | Lane::new(kind, self.lane_count(kind) - 1) |
| 1150 | } |
| 1151 | |
| 1152 | /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and |
| 1153 | /// one undo step like it, which restores the lane where it stood. |
| 1154 | /// |
| 1155 | /// Refused, changing nothing, while the lane holds anything: the refusal |
| 1156 | /// names the clips (file and first frame), because a track removal that |
| 1157 | /// deleted takes with it would be the one edit nobody sees coming. Refused |
| 1158 | /// too for the last lane of its kind, which is `V1` or `A1`: those two are |
| 1159 | /// where an import and a paste land ([`Project::paste`] takes lane 0 of each |
| 1160 | /// kind and *skips* a kind that is not there), so a project without one |
| 1161 | /// would swallow half of every file dropped on it, silently. |
| 1162 | /// |
| 1163 | /// The lanes below it move up one `ord`, so a handle a caller was holding |
| 1164 | /// (a selection, an open card) names the lane after it from here on -- the |
| 1165 | /// one thing a front-end owes this call. |
| 1166 | pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> { |
| 1167 | let Some(i) = self.index(lane) else { |
| 1168 | return Err(format!("there is no {} to remove", lane.label()).into()); |
| 1169 | }; |
| 1170 | // A subtitle lane is not in that rule: nothing lands on one by itself |
| 1171 | // -- a project starts without any and one is added when a caption is -- |
| 1172 | // so the last of them comes off like any other empty track. |
| 1173 | if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle { |
| 1174 | return Err(format!( |
| 1175 | "{} is the only {} track: every import lands on it", |
| 1176 | lane.label(), |
| 1177 | match lane.kind { |
| 1178 | LaneKind::Video => "video", |
| 1179 | LaneKind::Audio => "audio", |
| 1180 | // Unreachable while the guard above lets the last subtitle |
| 1181 | // lane go, and its own word here so the sentence stays true |
| 1182 | // if that rule is ever relaxed. |
| 1183 | LaneKind::Subtitle => "subtitle", |
| 1184 | } |
| 1185 | ) |
| 1186 | .into()); |
| 1187 | } |
| 1188 | if !self.lanes[i].subs.is_empty() { |
| 1189 | // Three names and a count, exactly as the clips below get: the way |
| 1190 | // out of the refusal is the drag, so the words say so. |
| 1191 | let named: Vec<String> = self.lanes[i] |
| 1192 | .subs |
| 1193 | .iter() |
| 1194 | .take(3) |
| 1195 | .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start)) |
| 1196 | .collect(); |
| 1197 | let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) { |
| 1198 | 0 => String::new(), |
| 1199 | n => format!(" and {n} more"), |
| 1200 | }; |
| 1201 | return Err(format!( |
| 1202 | "{} still holds {}{rest}: delete those captions (or drag them to \ |
| 1203 | another track) first", |
| 1204 | lane.label(), |
| 1205 | named.join(", ") |
| 1206 | ) |
| 1207 | .into()); |
| 1208 | } |
| 1209 | let clips = &self.lanes[i].clips; |
| 1210 | if !clips.is_empty() { |
| 1211 | // Three names and a count: a lane can hold forty clips and a |
| 1212 | // refusal nobody reads to the end says nothing at all. |
| 1213 | let named: Vec<String> = clips |
| 1214 | .iter() |
| 1215 | .take(3) |
| 1216 | .map(|c| { |
| 1217 | let name = self.sources.get(c.source).map_or_else( |
| 1218 | || format!("source {}", c.source), |
| 1219 | |s| s.path.display().to_string(), |
| 1220 | ); |
| 1221 | format!("{name} at frame {}", c.start) |
| 1222 | }) |
| 1223 | .collect(); |
| 1224 | let rest = match clips.len().saturating_sub(named.len()) { |
| 1225 | 0 => String::new(), |
| 1226 | n => format!(" and {n} more"), |
| 1227 | }; |
| 1228 | return Err(format!( |
| 1229 | "{} still holds {}{rest}: delete those clips (or drag them to \ |
| 1230 | another track) first", |
| 1231 | lane.label(), |
| 1232 | named.join(", ") |
| 1233 | ) |
| 1234 | .into()); |
| 1235 | } |
| 1236 | self.snapshot(); |
| 1237 | self.lanes.remove(i); |
| 1238 | Ok(()) |
| 1239 | } |
| 1240 | |
| 1241 | /// Moves `lane` to display position `to` -- an index into |
| 1242 | /// [`Project::lanes`], the slot the lane there gives up -- and hands back |
| 1243 | /// the handle it answers to from now on. `None`, changing nothing and |
| 1244 | /// snapshotting nothing, for a lane that is not there, a position that is |
| 1245 | /// not, and a lane already standing in it. |
| 1246 | /// |
| 1247 | /// The whole track travels: its clips, its gain, its kind. Nothing is |
| 1248 | /// remapped, so no take changes lane and no group is broken -- this is the |
| 1249 | /// *order* of the lanes and nothing else, which is why one call is one undo |
| 1250 | /// step like an add or a removal. |
| 1251 | /// |
| 1252 | /// Display order **is** the stack: [`Project::composite_span_at`] shows the |
| 1253 | /// last video lane covering a frame, so moving one video lane past another |
| 1254 | /// changes which picture wins, in the preview and in an export alike. The |
| 1255 | /// audio lanes are summed and their sum does not care about order, so an |
| 1256 | /// audio track moved among the video ones is a rearrangement of the screen |
| 1257 | /// alone. |
| 1258 | /// |
| 1259 | /// A label is a *position* ([`Lane::label`] reads `ord`, which is the |
| 1260 | /// position among the lanes of that kind), so a lane that crosses one of |
| 1261 | /// its own kind swaps names with it -- `V2` dragged above `V1` becomes |
| 1262 | /// `V1`, clips and all -- while one that crosses only lanes of the other |
| 1263 | /// kind keeps its name. That is the returned handle: unchanged means every |
| 1264 | /// handle a caller holds still names the track it named before. |
| 1265 | pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> { |
| 1266 | let i = self.index(lane)?; |
| 1267 | if to >= self.lanes.len() || to == i { |
| 1268 | return None; |
| 1269 | } |
| 1270 | self.snapshot(); |
| 1271 | let data = self.lanes.remove(i); |
| 1272 | self.lanes.insert(to, data); |
| 1273 | Some(handles(&self.lanes)[to]) |
| 1274 | } |
| 1275 | |
| 1276 | /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is |
| 1277 | /// not there. The one place a handle becomes a position. |
| 1278 | fn index(&self, lane: Lane) -> Option<usize> { |
| 1279 | self.lanes |
| 1280 | .iter() |
| 1281 | .enumerate() |
| 1282 | .filter(|(_, l)| l.kind == lane.kind) |
| 1283 | .map(|(i, _)| i) |
| 1284 | .nth(lane.ord) |
| 1285 | } |
| 1286 | |
| 1287 | fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> { |
| 1288 | let i = self.index(lane)?; |
| 1289 | Some(&mut self.lanes[i].clips) |
| 1290 | } |
| 1291 | |
| 1292 | /// The files the clips index into, in import order; index 0 is the file the |
| 1293 | /// project was opened with. |
| 1294 | pub fn sources(&self) -> &[Source] { |
| 1295 | &self.sources |
| 1296 | } |
| 1297 | |
| 1298 | /// The same list in the `(path, stream)` shape the audio engine indexes |
| 1299 | /// into -- [`crate::AudioSession::open_multi_streams`] and |
| 1300 | /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip |
| 1301 | /// was placed with is the stream that plays *and* the stream that exports. |
| 1302 | pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> { |
| 1303 | self.sources |
| 1304 | .iter() |
| 1305 | .map(|s| (s.path.clone(), s.audio_stream)) |
| 1306 | .collect() |
| 1307 | } |
| 1308 | |
| 1309 | /// Index for `path` played on `audio_stream`, appending it if it is new. |
| 1310 | /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached |
| 1311 | /// by two paths imports once and two streams of one file are two sources. |
| 1312 | /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes |
| 1313 | /// no history: a source entry alone changes nothing playable. |
| 1314 | pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize { |
| 1315 | let source = Source::new(path, audio_stream); |
| 1316 | match self.sources.iter().position(|s| *s == source) { |
| 1317 | Some(idx) => idx, |
| 1318 | None => { |
| 1319 | self.sources.push(source); |
| 1320 | self.sources.len() - 1 |
| 1321 | } |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | /// Append a whole-file clip of `source` to the end of every *media* lane, |
| 1326 | /// grouped -- an import lands as one take. Subtitle lanes are skipped: they |
| 1327 | /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles |
| 1328 | /// come in through [`Project::add_subtitles`], which is the palette. |
| 1329 | /// |
| 1330 | /// One history snapshot, so an import is one undo step, and undoing it |
| 1331 | /// leaves the (harmless) source entry behind, because indexes are forever. |
| 1332 | /// Refused for an unknown source index. |
| 1333 | pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool { |
| 1334 | if source >= self.sources.len() { |
| 1335 | return false; |
| 1336 | } |
| 1337 | self.snapshot(); |
| 1338 | let start = self.timeline_frames(); |
| 1339 | let clip = Clip { |
| 1340 | fade_in: 0, |
| 1341 | fade_out: 0, |
| 1342 | transition_out: 0, |
| 1343 | start, |
| 1344 | in_frame: 0, |
| 1345 | out_frame: frame_count.max(1), |
| 1346 | source, |
| 1347 | link: Some(self.new_link()), |
| 1348 | eq: None, |
| 1349 | color: None, |
| 1350 | transform: None, |
| 1351 | fit: FitPolicy::default(), |
| 1352 | speed: Speed::NORMAL, |
| 1353 | }; |
| 1354 | for data in self |
| 1355 | .lanes |
| 1356 | .iter_mut() |
| 1357 | .filter(|l| l.kind != LaneKind::Subtitle) |
| 1358 | { |
| 1359 | data.clips.push(clip); |
| 1360 | } |
| 1361 | true |
| 1362 | } |
| 1363 | |
| 1364 | /// Drops a source entry -- the file a library row *is* -- and renumbers |
| 1365 | /// every clip that indexed past it, which is why this is more than a |
| 1366 | /// `Vec::remove`. |
| 1367 | /// |
| 1368 | /// Refused, changing nothing, while any clip still plays from it: the |
| 1369 | /// refusal names the lanes and how many clips each holds, so a caller can |
| 1370 | /// say what has to be deleted first. The *last* entry goes like any other |
| 1371 | /// -- a project may name no file at all, which is an empty library over an |
| 1372 | /// empty timeline (nothing can play, since a clip would have refused the |
| 1373 | /// removal). What a front-end does with that is its own decision: `edith`'s |
| 1374 | /// window goes back to the empty state it launches in, and |
| 1375 | /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project) |
| 1376 | /// refuses to write a project that names nothing, because no such file |
| 1377 | /// could be opened again. |
| 1378 | /// |
| 1379 | /// Every index past `idx` moves down by one, so a caller holding a *raw* |
| 1380 | /// source index of its own -- a clipboard, which is the one thing outside |
| 1381 | /// this type that does -- has to fix it up or drop it, or a paste plays a |
| 1382 | /// different file. [`PlaybackSession::remove_source`] hands back the index |
| 1383 | /// that went for exactly that. |
| 1384 | /// |
| 1385 | /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a |
| 1386 | /// snapshot older than the removal can name the very source being removed |
| 1387 | /// (delete a file's clips, then remove the file) and restoring it would |
| 1388 | /// point a clip at an entry that is gone. The upgrade path is snapshotting |
| 1389 | /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the |
| 1390 | /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and |
| 1391 | /// the reason [`without_orphan_sources`](Project::without_orphan_sources) |
| 1392 | /// exists) currently rules out. |
| 1393 | pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> { |
| 1394 | let Some(source) = self.sources.get(idx) else { |
| 1395 | return Err(format!("there is no source {idx} to remove").into()); |
| 1396 | }; |
| 1397 | let name = source.path.display().to_string(); |
| 1398 | let used: Vec<String> = handles(&self.lanes) |
| 1399 | .into_iter() |
| 1400 | .zip(&self.lanes) |
| 1401 | .filter_map( |
| 1402 | |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() { |
| 1403 | 0 => None, |
| 1404 | 1 => Some(format!("{} (1 clip)", lane.label())), |
| 1405 | n => Some(format!("{} ({n} clips)", lane.label())), |
| 1406 | }, |
| 1407 | ) |
| 1408 | .collect(); |
| 1409 | if !used.is_empty() { |
| 1410 | return Err(format!("{name} still plays on {}", used.join(", ")).into()); |
| 1411 | } |
| 1412 | self.sources.remove(idx); |
| 1413 | for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) { |
| 1414 | if c.source > idx { |
| 1415 | c.source -= 1; |
| 1416 | } |
| 1417 | } |
| 1418 | self.history.clear(); |
| 1419 | Ok(()) |
| 1420 | } |
| 1421 | |
| 1422 | /// The sources a clip actually names, with the clips reindexed onto them |
| 1423 | /// -- what a save writes. Indexes are forever *inside* a session (see |
| 1424 | /// [`Project::append_clip`]), so an undone import leaves an orphan source |
| 1425 | /// entry behind; writing that orphan to a project file would let a file |
| 1426 | /// nothing plays refuse a future load. New indexes are assigned in order of |
| 1427 | /// first use -- lane by lane, in display order -- so the same project always |
| 1428 | /// emits the same bytes. |
| 1429 | /// |
| 1430 | /// Every lane comes out, in display order and with its kind: that is what a |
| 1431 | /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`] |
| 1432 | /// takes back. |
| 1433 | /// |
| 1434 | /// The equalizer and colour tables are pruned the same way and for the same |
| 1435 | /// reason: an undone [`set_eq`](Project::set_eq) or |
| 1436 | /// [`set_color`](Project::set_color) leaves settings nothing plays behind, |
| 1437 | /// and this is the one moment they can go -- the indexes that survive it are |
| 1438 | /// only the ones a clip names. |
| 1439 | /// |
| 1440 | /// One exception, and it is the emptied timeline's: a project no clip plays |
| 1441 | /// from still keeps its first source, if it has one. A file is what a |
| 1442 | /// reopened project scaffolds itself from -- the frame rate is written |
| 1443 | /// nowhere else -- so a save that pruned the last of them would write a |
| 1444 | /// project that cannot be loaded back at all. |
| 1445 | /// |
| 1446 | /// What comes out is *not* ordered by anything a reader may assume: first |
| 1447 | /// use, lane by lane, means the entry at index 0 can be a still or a song |
| 1448 | /// whatever the session was scaffolded from. `PlaybackSession::open_project` |
| 1449 | /// picks its rate and its audio reference by what a source *is*, never by |
| 1450 | /// where it sits. |
| 1451 | pub fn without_orphan_sources(&self) -> Parts { |
| 1452 | let mut moved = vec![None; self.sources.len()]; |
| 1453 | let mut sources = Vec::new(); |
| 1454 | let mut moved_eq = vec![None; self.eq.len()]; |
| 1455 | let mut eq = Vec::new(); |
| 1456 | let mut moved_color = vec![None; self.color.len()]; |
| 1457 | let mut color = Vec::new(); |
| 1458 | let mut moved_transform = vec![None; self.transform.len()]; |
| 1459 | let mut transform = Vec::new(); |
| 1460 | let mut lanes = self.lanes.clone(); |
| 1461 | for c in lanes.iter_mut().flat_map(|l| &mut l.clips) { |
| 1462 | let old = c.source; |
| 1463 | c.source = match moved[old] { |
| 1464 | Some(new) => new, |
| 1465 | None => { |
| 1466 | sources.push(self.sources[old].clone()); |
| 1467 | moved[old] = Some(sources.len() - 1); |
| 1468 | sources.len() - 1 |
| 1469 | } |
| 1470 | }; |
| 1471 | if let Some(old) = c.eq.map(usize::from) { |
| 1472 | c.eq = Some(match moved_eq[old] { |
| 1473 | Some(new) => new, |
| 1474 | None => { |
| 1475 | eq.push(self.eq[old].clone()); |
| 1476 | let new = (eq.len() - 1) as u16; |
| 1477 | moved_eq[old] = Some(new); |
| 1478 | new |
| 1479 | } |
| 1480 | }); |
| 1481 | } |
| 1482 | if let Some(old) = c.color.map(usize::from) { |
| 1483 | c.color = Some(match moved_color[old] { |
| 1484 | Some(new) => new, |
| 1485 | None => { |
| 1486 | color.push(self.color[old]); |
| 1487 | let new = (color.len() - 1) as u16; |
| 1488 | moved_color[old] = Some(new); |
| 1489 | new |
| 1490 | } |
| 1491 | }); |
| 1492 | } |
| 1493 | if let Some(old) = c.transform.map(usize::from) { |
| 1494 | c.transform = Some(match moved_transform[old] { |
| 1495 | Some(new) => new, |
| 1496 | None => { |
| 1497 | transform.push(self.transform[old]); |
| 1498 | let new = (transform.len() - 1) as u16; |
| 1499 | moved_transform[old] = Some(new); |
| 1500 | new |
| 1501 | } |
| 1502 | }); |
| 1503 | } |
| 1504 | } |
| 1505 | if sources.is_empty() { |
| 1506 | sources.extend(self.sources.first().cloned()); |
| 1507 | } |
| 1508 | ( |
| 1509 | sources, |
| 1510 | // Every lane, subtitle ones included: they hold no [`Clip`], so what |
| 1511 | // comes out for one is an empty list, and its *place* in the display |
| 1512 | // order is what a save writes it for. What is on it travels beside |
| 1513 | // this, in [`lane_subs`](Project::lane_subs), as the gains do. |
| 1514 | lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), |
| 1515 | eq, |
| 1516 | color, |
| 1517 | transform, |
| 1518 | ) |
| 1519 | } |
| 1520 | |
| 1521 | /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for |
| 1522 | /// a lane that is not there. Whole-lane and whole-band -- every clip on the |
| 1523 | /// track moves by it, which is what makes it a different control from a |
| 1524 | /// clip's equalizer (one frequency range of one take) and from the master |
| 1525 | /// volume (what this machine monitors at, which no file carries). |
| 1526 | pub fn lane_gain_db(&self, lane: Lane) -> f32 { |
| 1527 | self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db) |
| 1528 | } |
| 1529 | |
| 1530 | /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`]. |
| 1531 | /// One undo step like every other edit -- it is in the lane list, so an |
| 1532 | /// undo restores it with the rest. `false`, and no history, for a lane that |
| 1533 | /// is not there, for a value that is not finite, and for one already set. |
| 1534 | /// |
| 1535 | /// `false` too for a subtitle lane, and that one is a *refusal* rather than |
| 1536 | /// a value nobody reads: words have no loudness, so a slider that appeared |
| 1537 | /// to move one would be a control with no effect. (A video lane's gain is |
| 1538 | /// meaningless in the same way but is kept settable: it is the pair `A1` |
| 1539 | /// carries for a take, and mixing reads it off the audio lane alone.) |
| 1540 | pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { |
| 1541 | let Some(i) = self.index(lane) else { |
| 1542 | return false; |
| 1543 | }; |
| 1544 | if !db.is_finite() || lane.kind == LaneKind::Subtitle { |
| 1545 | return false; |
| 1546 | } |
| 1547 | let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); |
| 1548 | if self.lanes[i].gain_db == db { |
| 1549 | return false; |
| 1550 | } |
| 1551 | self.snapshot(); |
| 1552 | self.lanes[i].gain_db = db; |
| 1553 | true |
| 1554 | } |
| 1555 | |
| 1556 | /// Every lane's volume in dB, in display order -- what a save writes, |
| 1557 | /// beside the lanes [`Project::without_orphan_sources`] hands back. |
| 1558 | /// |
| 1559 | /// The *same* lanes as that call, subtitle ones included at the `0.0` they |
| 1560 | /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses |
| 1561 | /// one): a save zips the two lists, so a lane that is in one and not the |
| 1562 | /// other would hand every track below it the volume of the track above. |
| 1563 | pub fn lane_gains(&self) -> Vec<f32> { |
| 1564 | self.lanes.iter().map(|l| l.gain_db).collect() |
| 1565 | } |
| 1566 | |
| 1567 | /// What is placed on every lane, in display order and in step with |
| 1568 | /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as |
| 1569 | /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub` |
| 1570 | /// lines. Empty for every video and audio lane, which hold no [`SubClip`]. |
| 1571 | /// |
| 1572 | /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette* |
| 1573 | /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a |
| 1574 | /// clip's source there is no orphan to prune and no index to move. |
| 1575 | pub fn lane_subs(&self) -> Vec<Vec<SubClip>> { |
| 1576 | self.lanes.iter().map(|l| l.subs.clone()).collect() |
| 1577 | } |
| 1578 | |
| 1579 | /// The placements a *load* puts back, one list per lane in display order -- |
| 1580 | /// the door [`with_mix`](Project::with_mix) is, and no undo step for the |
| 1581 | /// same reason. Called *after* |
| 1582 | /// [`with_subtitles`](Project::with_subtitles), whose palette a placement |
| 1583 | /// names. |
| 1584 | /// |
| 1585 | /// The subtitle half of [`from_parts`](Project::from_parts) and checked |
| 1586 | /// like it, by name and in release, because it is the same untrusted file: |
| 1587 | /// a placement on a lane that is not a subtitle lane, an empty span or an |
| 1588 | /// empty window, a track the palette does not have, a span running past the |
| 1589 | /// last frame there is, and a lane that is out of order or overlaps itself |
| 1590 | /// ([`place_sub`] refuses every one of those on the live timeline). |
| 1591 | /// |
| 1592 | /// [`place_sub`]: Project::place_sub |
| 1593 | pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> { |
| 1594 | let names = handles(&self.lanes); |
| 1595 | let palette = self.subtitles.len(); |
| 1596 | for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) { |
| 1597 | let name = lane.label(); |
| 1598 | if list.is_empty() { |
| 1599 | continue; |
| 1600 | } |
| 1601 | if data.kind != LaneKind::Subtitle { |
| 1602 | return Err(format!( |
| 1603 | "{name} is not a subtitle track and holds {} caption(s): words go on a \ |
| 1604 | subtitle track", |
| 1605 | list.len() |
| 1606 | ) |
| 1607 | .into()); |
| 1608 | } |
| 1609 | for s in &list { |
| 1610 | if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 { |
| 1611 | return Err(format!( |
| 1612 | "{name} caption at {} is empty: {} frames of [{}, {})", |
| 1613 | s.start, s.frames, s.in_us, s.out_us |
| 1614 | ) |
| 1615 | .into()); |
| 1616 | } |
| 1617 | if s.track >= palette { |
| 1618 | return Err(format!( |
| 1619 | "{name} caption at {} names subtitle track {} of {palette}", |
| 1620 | s.start, s.track |
| 1621 | ) |
| 1622 | .into()); |
| 1623 | } |
| 1624 | if s.start.checked_add(s.frames).is_none() { |
| 1625 | return Err(format!( |
| 1626 | "{name} caption at {} runs past the last frame there is", |
| 1627 | s.start |
| 1628 | ) |
| 1629 | .into()); |
| 1630 | } |
| 1631 | } |
| 1632 | if !subs_sorted_disjoint(&list) { |
| 1633 | return Err(format!("the {name} lane is out of order or overlaps itself").into()); |
| 1634 | } |
| 1635 | data.subs = list; |
| 1636 | // The counter also has to clear the ids these captions carry: this |
| 1637 | // is the door a load's placements come through, *after* |
| 1638 | // [`from_parts`](Project::from_parts) seeded it from the clips, and |
| 1639 | // a hand-grouped caption may carry the highest id in the file. |
| 1640 | self.next_link = self.next_link.max( |
| 1641 | data.subs |
| 1642 | .iter() |
| 1643 | .filter_map(|s| s.link) |
| 1644 | .max() |
| 1645 | .map_or(0, |m| m.saturating_add(1)), |
| 1646 | ); |
| 1647 | } |
| 1648 | Ok(self) |
| 1649 | } |
| 1650 | |
| 1651 | /// The mix settings a *load* puts back: lane volumes in display order (a |
| 1652 | /// short list leaves the rest at unity) and the master limiter, both |
| 1653 | /// clamped as their setters clamp them. |
| 1654 | /// |
| 1655 | /// The load's own door, beside [`from_parts`](Project::from_parts): the |
| 1656 | /// setters push an undo step, and a project that arrives one undo away from |
| 1657 | /// a state it was never in is a project whose first ctrl+z is a surprise. |
| 1658 | pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self { |
| 1659 | for (data, &db) in self.lanes.iter_mut().zip(gains) { |
| 1660 | if db.is_finite() { |
| 1661 | data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); |
| 1662 | } |
| 1663 | } |
| 1664 | self.limiter = limiter.with_ceiling(limiter.ceiling_db); |
| 1665 | self |
| 1666 | } |
| 1667 | |
| 1668 | /// The HDR rendition a *load* puts back -- the same door |
| 1669 | /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason. |
| 1670 | pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self { |
| 1671 | self.tone = preset; |
| 1672 | self |
| 1673 | } |
| 1674 | |
| 1675 | /// Which HDR-to-SDR rendition this project is watched and exported in. A |
| 1676 | /// project setting, not a clip's: one picture, one look |
| 1677 | /// ([`crate::tonemap::Preset`]). |
| 1678 | pub fn tone(&self) -> crate::tonemap::Preset { |
| 1679 | self.tone |
| 1680 | } |
| 1681 | |
| 1682 | /// Sets it. `false` for the one already in force, which is what keeps a |
| 1683 | /// re-pick of the current rendition from costing a reseek. |
| 1684 | /// |
| 1685 | /// corner-cut: not an undo step, for the reason the limiter and the project |
| 1686 | /// resolution are not -- it is not in the lane list the history snapshots. |
| 1687 | /// Upgrade path is the same one: a history entry holding the project's own |
| 1688 | /// settings beside the lanes. |
| 1689 | pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool { |
| 1690 | if self.tone == preset { |
| 1691 | return false; |
| 1692 | } |
| 1693 | self.tone = preset; |
| 1694 | true |
| 1695 | } |
| 1696 | |
| 1697 | /// The subtitle tracks a *load* puts back, in the order they were saved -- |
| 1698 | /// the same door [`with_mix`](Project::with_mix) is, and no undo step for |
| 1699 | /// the same reason. |
| 1700 | pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self { |
| 1701 | self.subtitles = tracks; |
| 1702 | self |
| 1703 | } |
| 1704 | |
| 1705 | /// What this timeline shows over the picture, in the order they were added: |
| 1706 | /// what a front-end lists and what a save writes. |
| 1707 | pub fn subtitles(&self) -> &[SubtitleTrack] { |
| 1708 | &self.subtitles |
| 1709 | } |
| 1710 | |
| 1711 | /// Adds a track, unless the very same one -- same file, same track number |
| 1712 | /// inside it -- is already on the list. `false` for that repeat: importing |
| 1713 | /// the same `.srt` twice is one subtitle track, not two identical ones. |
| 1714 | pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool { |
| 1715 | if self |
| 1716 | .subtitles |
| 1717 | .iter() |
| 1718 | .any(|t| t.path == track.path && t.track == track.track) |
| 1719 | { |
| 1720 | return false; |
| 1721 | } |
| 1722 | self.subtitles.push(track.clone()); |
| 1723 | true |
| 1724 | } |
| 1725 | |
| 1726 | /// Takes the track at `idx` off the list -- what a row's own remove goes |
| 1727 | /// through, so whatever an import added can be taken back out. Refused by |
| 1728 | /// name for a row this project does not have, rather than a silent no-op: |
| 1729 | /// a front-end holding a stale index has picked the wrong row and needs to |
| 1730 | /// hear it. |
| 1731 | /// |
| 1732 | /// Every index past `idx` moves down by one, as [`remove_source`]( |
| 1733 | /// Project::remove_source)'s do: a caller holding a picked row (an export's |
| 1734 | /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop |
| 1735 | /// it, or it names a different track afterwards. The placements on the |
| 1736 | /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by |
| 1737 | /// index into this very list, so every one past `idx` is walked down with |
| 1738 | /// it here -- the reindex [`remove_source`](Project::remove_source) does |
| 1739 | /// for its clips, for its reason. |
| 1740 | /// |
| 1741 | /// Refused, changing nothing, while anything placed on a subtitle lane |
| 1742 | /// plays *this* row: the placement would have to be deleted or retargeted, |
| 1743 | /// and either one is an edit nobody asked for. The refusal names the lane |
| 1744 | /// and the frame it is at, up to three of them -- |
| 1745 | /// [`remove_source`](Project::remove_source) refuses the same way for the |
| 1746 | /// same silent corruption. |
| 1747 | /// |
| 1748 | /// corner-cut: not an undo step, for the reason the limiter is not -- the |
| 1749 | /// history snapshots hold the lane list and subtitles are not on it |
| 1750 | /// ([`Project::subtitles`]). The inverse is putting the file's tracks back |
| 1751 | /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own |
| 1752 | /// door, which reads the subtitles of a file and nothing else -- and not a |
| 1753 | /// ctrl+z; the upgrade path is the same one the limiter has: a history |
| 1754 | /// entry holding the project's own settings beside the lanes. The history |
| 1755 | /// is *cleared* rather than kept, as a source removal clears it: the |
| 1756 | /// snapshots hold the indexes as they were before the reindex, so an undo |
| 1757 | /// into one would put every placement past `idx` on the wrong track. |
| 1758 | pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> { |
| 1759 | if idx >= self.subtitles.len() { |
| 1760 | return Err(format!("there is no subtitle track {idx} to remove").into()); |
| 1761 | } |
| 1762 | let placed: Vec<String> = handles(&self.lanes) |
| 1763 | .into_iter() |
| 1764 | .zip(&self.lanes) |
| 1765 | .flat_map(|(lane, data)| { |
| 1766 | data.subs |
| 1767 | .iter() |
| 1768 | .filter(move |s| s.track == idx) |
| 1769 | .map(move |s| format!("{} at frame {}", lane.label(), s.start)) |
| 1770 | }) |
| 1771 | .take(3) |
| 1772 | .collect(); |
| 1773 | if !placed.is_empty() { |
| 1774 | return Err(format!( |
| 1775 | "{} is on the timeline ({}): delete those clips first", |
| 1776 | self.track_name(idx), |
| 1777 | placed.join(", ") |
| 1778 | ) |
| 1779 | .into()); |
| 1780 | } |
| 1781 | self.subtitles.remove(idx); |
| 1782 | for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) { |
| 1783 | if s.track > idx { |
| 1784 | s.track -= 1; |
| 1785 | } |
| 1786 | } |
| 1787 | self.history.clear(); |
| 1788 | Ok(()) |
| 1789 | } |
| 1790 | |
| 1791 | /// What a refusal calls a palette row: the name the panel shows, and the |
| 1792 | /// index alone for a row that is not there. |
| 1793 | fn track_name(&self, track: usize) -> String { |
| 1794 | self.subtitles |
| 1795 | .get(track) |
| 1796 | .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone()) |
| 1797 | } |
| 1798 | |
| 1799 | /// The subtitle lanes in display order -- what a front-end lays out and |
| 1800 | /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of |
| 1801 | /// [`audio_lanes`](Project::audio_lanes). |
| 1802 | pub fn subtitle_lanes(&self) -> Vec<Lane> { |
| 1803 | self.lanes() |
| 1804 | .into_iter() |
| 1805 | .filter(|l| l.kind == LaneKind::Subtitle) |
| 1806 | .collect() |
| 1807 | } |
| 1808 | |
| 1809 | /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin |
| 1810 | /// for a subtitle track, and empty for every other lane and for one that is |
| 1811 | /// not there. |
| 1812 | pub fn sub_lane(&self, lane: Lane) -> &[SubClip] { |
| 1813 | self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs) |
| 1814 | } |
| 1815 | |
| 1816 | /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s |
| 1817 | /// twin, with one deliberate difference: it **refuses** an overlap instead |
| 1818 | /// of overwriting what it lands on. |
| 1819 | /// |
| 1820 | /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored, |
| 1821 | /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag |
| 1822 | /// carries is a *window of a track* and where the hand let go, and the |
| 1823 | /// second of those is the argument. So a caller builds the placement once |
| 1824 | /// (from the palette row it dragged) and drops it at as many frames as it |
| 1825 | /// likes without rewriting the field each time. |
| 1826 | /// |
| 1827 | /// A picture placed over a picture hides it and the hidden one is still |
| 1828 | /// there to drag back out; two captions in one frame are two lines nobody |
| 1829 | /// asked to stack, and the words that lost are gone from the screen with |
| 1830 | /// nothing to show for it. So the refusal names the placement in the way, |
| 1831 | /// and the caller picks another frame or another lane -- which is what a |
| 1832 | /// second subtitle lane is for. |
| 1833 | /// |
| 1834 | /// One undo step on success, and none on any refusal: an empty window or an |
| 1835 | /// empty span, a track the palette does not have |
| 1836 | /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a |
| 1837 | /// subtitle lane, a span that would run past the last frame there is, and |
| 1838 | /// the overlap above. |
| 1839 | pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> { |
| 1840 | if lane.kind != LaneKind::Subtitle { |
| 1841 | return Err(format!( |
| 1842 | "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \ |
| 1843 | the others", |
| 1844 | lane.label() |
| 1845 | ) |
| 1846 | .into()); |
| 1847 | } |
| 1848 | let Some(i) = self.index(lane) else { |
| 1849 | return Err(format!("there is no {} to place on", lane.label()).into()); |
| 1850 | }; |
| 1851 | if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 { |
| 1852 | return Err(format!( |
| 1853 | "that placement is empty: {} frames of [{}, {})", |
| 1854 | sub.frames, sub.in_us, sub.out_us |
| 1855 | ) |
| 1856 | .into()); |
| 1857 | } |
| 1858 | if sub.track >= self.subtitles.len() { |
| 1859 | return Err(format!( |
| 1860 | "it names subtitle track {} of {}", |
| 1861 | sub.track, |
| 1862 | self.subtitles.len() |
| 1863 | ) |
| 1864 | .into()); |
| 1865 | } |
| 1866 | // The placement belongs to no group, for [`place`]'s reason: a caption |
| 1867 | // dragged out of the palette arrives alone, and grouping it with what |
| 1868 | // is under it is a hand's decision ([`Project::group_all`]). |
| 1869 | let sub = SubClip { |
| 1870 | start: at, |
| 1871 | link: None, |
| 1872 | ..sub |
| 1873 | }; |
| 1874 | if at.checked_add(sub.frames).is_none() { |
| 1875 | return Err(format!("a placement at frame {at} runs past the last frame there is").into()); |
| 1876 | } |
| 1877 | if let Some(other) = self.lanes[i] |
| 1878 | .subs |
| 1879 | .iter() |
| 1880 | .find(|o| o.end() > sub.start && o.start < sub.end()) |
| 1881 | { |
| 1882 | return Err(format!( |
| 1883 | "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \ |
| 1884 | on another subtitle track", |
| 1885 | lane.label(), |
| 1886 | other.start, |
| 1887 | other.start, |
| 1888 | other.end() |
| 1889 | ) |
| 1890 | .into()); |
| 1891 | } |
| 1892 | self.snapshot(); |
| 1893 | let subs = &mut self.lanes[i].subs; |
| 1894 | let idx = subs.partition_point(|o| o.start < sub.start); |
| 1895 | subs.insert(idx, sub); |
| 1896 | debug_assert!(subs_sorted_disjoint(subs)); |
| 1897 | Ok(()) |
| 1898 | } |
| 1899 | |
| 1900 | /// Move the subtitle at `idx` of `from` onto `to` with its head at `start` |
| 1901 | /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is |
| 1902 | /// refused an overlap where that one clamps to it, for |
| 1903 | /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it |
| 1904 | /// still and no picture under it that a landing would hide, so "as far as |
| 1905 | /// it goes" would silently be a frame nobody named. |
| 1906 | /// |
| 1907 | /// A caption *in* a group drags the group: one delta for every member -- |
| 1908 | /// its clips and its other captions -- clamped to the room each of them |
| 1909 | /// has, exactly as a clip's drag always has. That is the point of putting |
| 1910 | /// a caption in a group: the words go where the picture goes. |
| 1911 | /// |
| 1912 | /// The window travels untouched: a caption dragged later says the same |
| 1913 | /// words later, exactly as a clip dragged later plays the same pictures |
| 1914 | /// later. |
| 1915 | /// |
| 1916 | /// One undo step on success; nothing changed and no step on a refusal -- |
| 1917 | /// an index that is not there, a lane that is not a subtitle lane or is not |
| 1918 | /// there, and (for a caption in no group) an overlap. A drop that changes |
| 1919 | /// neither lane nor frame is `Ok` and no step: a hand that picked a caption |
| 1920 | /// up and put it back has done nothing wrong, and a front-end showing every |
| 1921 | /// `Err` would say so. |
| 1922 | pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> { |
| 1923 | let Some(sub) = self.sub_lane(from).get(idx).copied() else { |
| 1924 | return Err(format!("there is no subtitle {idx} on {}", from.label()).into()); |
| 1925 | }; |
| 1926 | if to.kind != LaneKind::Subtitle { |
| 1927 | return Err(format!( |
| 1928 | "{} is not a subtitle track: a caption cannot play on it", |
| 1929 | to.label() |
| 1930 | ) |
| 1931 | .into()); |
| 1932 | } |
| 1933 | let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else { |
| 1934 | return Err(format!("there is no {} to move onto", to.label()).into()); |
| 1935 | }; |
| 1936 | if (here, start) == (dest, sub.start) { |
| 1937 | // A pick-up-put-back: the drag ended where it began, which is not a |
| 1938 | // mistake to name -- `Ok`, and no undo step, because nothing |
| 1939 | // changed. A refusal here would toast a hand that did nothing. |
| 1940 | return Ok(()); |
| 1941 | } |
| 1942 | if start.checked_add(sub.frames).is_none() { |
| 1943 | return Err( |
| 1944 | format!("a placement at frame {start} runs past the last frame there is").into(), |
| 1945 | ); |
| 1946 | } |
| 1947 | // A grouped caption carries its group, clamped to the room the whole |
| 1948 | // group has rather than refused ([`Project::move_room]) -- one drag, one |
| 1949 | // delta, one undo step. |
| 1950 | let members = self.group_of(from, idx).expect("the subtitle was found"); |
| 1951 | if !members.alone() { |
| 1952 | if members |
| 1953 | .subs |
| 1954 | .iter() |
| 1955 | .any(|&(l, i)| l == dest && (l, i) != (here, idx)) |
| 1956 | { |
| 1957 | return Err(format!( |
| 1958 | "a group is one caption per track: {} already carries this group", |
| 1959 | to.label() |
| 1960 | ) |
| 1961 | .into()); |
| 1962 | } |
| 1963 | let want = i64::from(start) - i64::from(sub.start); |
| 1964 | let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else { |
| 1965 | return Err(format!( |
| 1966 | "another placement already covers those frames on {}", |
| 1967 | to.label() |
| 1968 | ) |
| 1969 | .into()); |
| 1970 | }; |
| 1971 | let delta = want.clamp(lo, hi); |
| 1972 | self.snapshot(); |
| 1973 | for &(l, i) in &members.clips { |
| 1974 | let c = &mut self.lanes[l].clips[i]; |
| 1975 | c.start = (i64::from(c.start) + delta) as u32; |
| 1976 | } |
| 1977 | for &(l, i) in &members.subs { |
| 1978 | let s = &mut self.lanes[l].subs[i]; |
| 1979 | s.start = (i64::from(s.start) + delta) as u32; |
| 1980 | } |
| 1981 | let moved = self.lanes[here].subs.remove(idx); |
| 1982 | let subs = &mut self.lanes[dest].subs; |
| 1983 | let at = subs.partition_point(|o| o.start < moved.start); |
| 1984 | subs.insert(at, moved); |
| 1985 | debug_assert!(subs_sorted_disjoint(subs)); |
| 1986 | debug_assert!(members |
| 1987 | .clips |
| 1988 | .iter() |
| 1989 | .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips))); |
| 1990 | return Ok(()); |
| 1991 | } |
| 1992 | let moved = SubClip { start, ..sub }; |
| 1993 | if let Some(other) = self.lanes[dest] |
| 1994 | .subs |
| 1995 | .iter() |
| 1996 | .enumerate() |
| 1997 | .find(|&(j, o)| { |
| 1998 | !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end() |
| 1999 | }) |
| 2000 | .map(|(_, o)| *o) |
| 2001 | { |
| 2002 | return Err(format!( |
| 2003 | "the {} subtitle at frame {} already covers [{}, {})", |
| 2004 | to.label(), |
| 2005 | other.start, |
| 2006 | other.start, |
| 2007 | other.end() |
| 2008 | ) |
| 2009 | .into()); |
| 2010 | } |
| 2011 | self.snapshot(); |
| 2012 | self.lanes[here].subs.remove(idx); |
| 2013 | let subs = &mut self.lanes[dest].subs; |
| 2014 | let at = subs.partition_point(|o| o.start < moved.start); |
| 2015 | subs.insert(at, moved); |
| 2016 | debug_assert!(subs_sorted_disjoint(subs)); |
| 2017 | debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs)); |
| 2018 | Ok(()) |
| 2019 | } |
| 2020 | |
| 2021 | /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame |
| 2022 | /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand |
| 2023 | /// pulling an edge past what is legal means "as far as it goes". |
| 2024 | /// |
| 2025 | /// The window follows the edge, in the seconds the frames are worth at |
| 2026 | /// `fps`: a head pulled in starts the caption later *in its track* (the |
| 2027 | /// cues that were skipped stay skipped, exactly as a trimmed clip's frames |
| 2028 | /// stay behind), and a tail pulled out shows more of it. `fps` is the one |
| 2029 | /// thing a [`Project`] does not know -- it is the caller's timeline rate, |
| 2030 | /// the same one [`crate::export::timeline_cues`] is asked with -- and it is |
| 2031 | /// needed here and nowhere else in this file, because a trim is the only |
| 2032 | /// edit that changes a *duration*. |
| 2033 | /// |
| 2034 | /// The walls: one frame always survives, an edge never crosses the |
| 2035 | /// neighbouring subtitle on its own lane, a head never walks back past the |
| 2036 | /// track's own start (`in_us` of 0), and a tail never runs past the last |
| 2037 | /// cue the track has -- which is the source length a media trim needs a |
| 2038 | /// caller's table for, and which this one can simply read. |
| 2039 | /// |
| 2040 | /// `Err`, with nothing changed and no undo step, for an index that is not |
| 2041 | /// there and an unusable `fps`. An edge that ends up where it already was |
| 2042 | /// -- the hand did not move it, or the clamp stopped it at a wall it stood |
| 2043 | /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s |
| 2044 | /// reason: a drag that stops at a wall is not a mistake to report. |
| 2045 | pub fn trim_sub( |
| 2046 | &mut self, |
| 2047 | lane: Lane, |
| 2048 | idx: usize, |
| 2049 | edge: Edge, |
| 2050 | to: u32, |
| 2051 | fps: f64, |
| 2052 | ) -> crate::Result<()> { |
| 2053 | if !(fps.is_finite() && fps > 0.0) { |
| 2054 | return Err(format!("{fps} is not a frame rate to trim against").into()); |
| 2055 | } |
| 2056 | let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else { |
| 2057 | return Err(format!("there is no subtitle {idx} on {}", lane.label()).into()); |
| 2058 | }; |
| 2059 | let Some(sub) = self.sub_lane(lane).get(idx).copied() else { |
| 2060 | return Err(format!("there is no subtitle {idx} on {}", lane.label()).into()); |
| 2061 | }; |
| 2062 | let to = to.clamp(lo, hi); |
| 2063 | let at = match edge { |
| 2064 | Edge::Start => sub.start, |
| 2065 | Edge::End => sub.end(), |
| 2066 | }; |
| 2067 | if to == at { |
| 2068 | // The edge is where it was asked to go -- either the hand did not |
| 2069 | // move it, or the clamp above stopped it at a wall it was already |
| 2070 | // standing against. Both are a drag that changed nothing: `Ok`, no |
| 2071 | // undo step, and no toast for a box that simply stopped moving. |
| 2072 | return Ok(()); |
| 2073 | } |
| 2074 | self.snapshot(); |
| 2075 | let members = self.group_of(lane, idx).expect("the subtitle was found"); |
| 2076 | let i = self.index(lane).expect("the subtitle was found on it"); |
| 2077 | let s = &mut self.lanes[i].subs[idx]; |
| 2078 | match edge { |
| 2079 | // The words that stay are the words that were there, so the window |
| 2080 | // moves with the head -- a trim, not a slip. |
| 2081 | Edge::Start => { |
| 2082 | // Clamped to a window that is still a window: the walls above |
| 2083 | // are frames and the rounding between the two clocks is not |
| 2084 | // exact, and neither is a caller's hand-built placement. |
| 2085 | s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps)) |
| 2086 | .clamp(0, s.out_us - 1); |
| 2087 | s.frames = s.end() - to; |
| 2088 | s.start = to; |
| 2089 | } |
| 2090 | Edge::End => { |
| 2091 | s.out_us = |
| 2092 | (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1); |
| 2093 | s.frames = to - s.start; |
| 2094 | } |
| 2095 | } |
| 2096 | debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0); |
| 2097 | debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs)); |
| 2098 | // A caption in a group drags its group's edge with it, exactly as a |
| 2099 | // clip's trim does: one delta, each member clamped to its own room. |
| 2100 | // No source table to grow by, which only tightens how far a member may |
| 2101 | // follow -- never whether it may. |
| 2102 | self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]); |
| 2103 | Ok(()) |
| 2104 | } |
| 2105 | |
| 2106 | /// How far that edge may travel, `(first, last)` timeline frame inclusive |
| 2107 | /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end |
| 2108 | /// drawing the box during a drag asks. `None` for an index that is not |
| 2109 | /// there. |
| 2110 | pub fn trim_sub_room( |
| 2111 | &self, |
| 2112 | lane: Lane, |
| 2113 | idx: usize, |
| 2114 | edge: Edge, |
| 2115 | fps: f64, |
| 2116 | ) -> Option<(u32, u32)> { |
| 2117 | let subs = self.sub_lane(lane); |
| 2118 | let s = *subs.get(idx)?; |
| 2119 | // How many timeline frames a stretch of the track is worth, which is |
| 2120 | // what turns its two walls -- its own start, and its last cue -- into |
| 2121 | // frames. A rate that is not a rate leaves the window where it is. |
| 2122 | let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 { |
| 2123 | true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32, |
| 2124 | false => 0, |
| 2125 | }; |
| 2126 | Some(match edge { |
| 2127 | Edge::Start => ( |
| 2128 | s.start |
| 2129 | .saturating_sub(frames_of(s.in_us)) |
| 2130 | .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())), |
| 2131 | s.end() - 1, |
| 2132 | ), |
| 2133 | Edge::End => { |
| 2134 | // Out to the end of the track it reads, and never over the |
| 2135 | // subtitle behind it. A track the palette no longer has (or one |
| 2136 | // with no cues at all) may not grow, exactly as a source with no |
| 2137 | // entry in a media trim's table may not. |
| 2138 | let track_end = self |
| 2139 | .subtitles |
| 2140 | .get(s.track) |
| 2141 | .and_then(|t| t.cues.iter().map(|c| c.end_us).max()) |
| 2142 | .unwrap_or(s.out_us); |
| 2143 | ( |
| 2144 | s.start + 1, |
| 2145 | s.start |
| 2146 | .saturating_add(frames_of(track_end - s.in_us).max(1)) |
| 2147 | .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)), |
| 2148 | ) |
| 2149 | } |
| 2150 | }) |
| 2151 | } |
| 2152 | |
| 2153 | /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing |
| 2154 | /// else -- [`lift`](Project::lift)'s twin, and one undo step like it. |
| 2155 | /// `false` for an index that is not there (which a lane that is not a |
| 2156 | /// subtitle lane always is). |
| 2157 | pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool { |
| 2158 | let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else { |
| 2159 | return false; |
| 2160 | }; |
| 2161 | self.snapshot(); |
| 2162 | self.lanes[i].subs.remove(idx); |
| 2163 | true |
| 2164 | } |
| 2165 | |
| 2166 | /// What `lane` shows, as cues on the **timeline's** clock: every placement's |
| 2167 | /// window of its track, clipped to that window and shifted to where the |
| 2168 | /// placement sits. The map [`crate::export::timeline_cues`] is for a track |
| 2169 | /// carried through the picture's spans -- this is its twin for a track that |
| 2170 | /// is placed on a lane of its own, and it is what a preview draws and what |
| 2171 | /// an export of the lane would write. |
| 2172 | /// |
| 2173 | /// Cut, not stretched: a cue half inside the window keeps the half that is |
| 2174 | /// inside, and a cue wholly outside it is gone -- the same rule the media |
| 2175 | /// spans follow. `fps` is the timeline's rate, needed here because a |
| 2176 | /// placement's *position* is in frames while its words are in microseconds. |
| 2177 | /// |
| 2178 | /// Pure and cheap enough to ask per repaint (a walk of the placements and |
| 2179 | /// of their cues, no file opened), which is how a front-end asks it. |
| 2180 | pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> { |
| 2181 | if !(fps.is_finite() && fps > 0.0) { |
| 2182 | return Vec::new(); |
| 2183 | } |
| 2184 | let mut out = Vec::new(); |
| 2185 | for s in self.sub_lane(lane) { |
| 2186 | let Some(track) = self.subtitles.get(s.track) else { |
| 2187 | // A placement whose track was taken off the palette |
| 2188 | // ([`Project::remove_subtitles`]) shows nothing rather than |
| 2189 | // showing another track's words. |
| 2190 | continue; |
| 2191 | }; |
| 2192 | // Where the placement's own first microsecond lands on the |
| 2193 | // timeline, and how many microseconds of timeline one microsecond |
| 2194 | // of the window is worth: the placement's own proportion, which a |
| 2195 | // group's re-rate changes (the frames compress, the window does |
| 2196 | // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and |
| 2197 | // every cue lands where it always did; at 2x the words cross the |
| 2198 | // screen in half the time, cue for cue. |
| 2199 | let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64); |
| 2200 | let onto = |t: i64| { |
| 2201 | (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64 |
| 2202 | }; |
| 2203 | for cue in &track.cues { |
| 2204 | let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us)); |
| 2205 | if b <= a { |
| 2206 | continue; // wholly outside the window this placement keeps |
| 2207 | } |
| 2208 | out.push(SubtitleCue { |
| 2209 | start_us: onto(a), |
| 2210 | end_us: onto(b), |
| 2211 | text: cue.text.clone(), |
| 2212 | image: cue.image.clone(), |
| 2213 | }); |
| 2214 | } |
| 2215 | } |
| 2216 | // The placements come in timeline order, but two lanes' worth (or a |
| 2217 | // track whose cues a window reordered) do not. |
| 2218 | out.sort_by_key(|cue| cue.start_us); |
| 2219 | out |
| 2220 | } |
| 2221 | |
| 2222 | /// What each of [`audio_segments_from`](Project::audio_segments_from)'s |
| 2223 | /// lanes is multiplied by on its way into the mix: the same lanes in the |
| 2224 | /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` |
| 2225 | /// for a lane nobody has turned, which is a multiply f32 leaves alone -- |
| 2226 | /// the bit-exact path. |
| 2227 | pub fn audio_gains(&self) -> Vec<f32> { |
| 2228 | self.audio_lanes() |
| 2229 | .into_iter() |
| 2230 | .map(|lane| db_to_linear(self.lane_gain_db(lane))) |
| 2231 | .collect() |
| 2232 | } |
| 2233 | |
| 2234 | /// The master limiter the mix is summed through. A project setting, not a |
| 2235 | /// clip's and not a lane's: there is one mix. |
| 2236 | pub fn limiter(&self) -> Limiter { |
| 2237 | self.limiter |
| 2238 | } |
| 2239 | |
| 2240 | /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false` |
| 2241 | /// for a setting already in force. |
| 2242 | /// |
| 2243 | /// corner-cut: not an undo step, for the reason the project resolution is not |
| 2244 | /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the |
| 2245 | /// lane list the history snapshots. Upgrade path is a history entry that |
| 2246 | /// holds the mix settings beside the lanes. |
| 2247 | pub fn set_limiter(&mut self, limiter: Limiter) -> bool { |
| 2248 | let limiter = limiter.with_ceiling(limiter.ceiling_db); |
| 2249 | if self.limiter == limiter { |
| 2250 | return false; |
| 2251 | } |
| 2252 | self.limiter = limiter; |
| 2253 | true |
| 2254 | } |
| 2255 | |
| 2256 | /// What the clip at `idx` of `lane` plays through, or `None` for one that |
| 2257 | /// plays flat (and for an index that is not there) -- what a feeder and an |
| 2258 | /// export ask before they build an [`crate::eq::EqState`]. |
| 2259 | pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { |
| 2260 | self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?)) |
| 2261 | } |
| 2262 | |
| 2263 | /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to |
| 2264 | /// take them off. One undo step, like every other edit. `false` -- and no |
| 2265 | /// history -- for an index that is not there and for params holding a value |
| 2266 | /// that is not finite, which is the one thing the file format could not |
| 2267 | /// write and read back. |
| 2268 | /// |
| 2269 | /// Settings equal to ones already in the table share their entry, so a |
| 2270 | /// project that puts the same curve on twenty clips writes it once. |
| 2271 | pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool { |
| 2272 | if idx >= self.lane(lane).len() { |
| 2273 | return false; |
| 2274 | } |
| 2275 | let slot = match params { |
| 2276 | None => None, |
| 2277 | Some(params) => { |
| 2278 | if !finite(¶ms) { |
| 2279 | return false; |
| 2280 | } |
| 2281 | Some(match self.eq.iter().position(|p| *p == params) { |
| 2282 | Some(at) => at as u16, |
| 2283 | // corner-cut: the table is append-only within a session (see |
| 2284 | // the module docs) and `Clip::eq` is a u16, so the 65535th |
| 2285 | // *distinct* setting of one session is refused rather than |
| 2286 | // silently aliased. Upgrade path if a UI ever drags a slider |
| 2287 | // that far: widen `Clip::eq` to u32 (Clip has the room) or |
| 2288 | // snapshot the table into the history and compact it here. |
| 2289 | None if self.eq.len() >= usize::from(u16::MAX) => return false, |
| 2290 | None => { |
| 2291 | self.eq.push(params); |
| 2292 | (self.eq.len() - 1) as u16 |
| 2293 | } |
| 2294 | }) |
| 2295 | } |
| 2296 | }; |
| 2297 | self.snapshot(); |
| 2298 | self.lane_mut(lane).expect("checked above")[idx].eq = slot; |
| 2299 | true |
| 2300 | } |
| 2301 | |
| 2302 | /// How the clip at `idx` of `lane` is graded, or `None` for one that plays |
| 2303 | /// ungraded (and for an index that is not there) -- what the renderer and |
| 2304 | /// the export ask before they call [`crate::color::apply_yuv`]. |
| 2305 | pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> { |
| 2306 | self.color |
| 2307 | .get(usize::from(self.lane(lane).get(idx)?.color?)) |
| 2308 | } |
| 2309 | |
| 2310 | /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it |
| 2311 | /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false` |
| 2312 | /// (and no history) for an index that is not there or a value that is not |
| 2313 | /// finite, and equal settings share a table entry. |
| 2314 | pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { |
| 2315 | self.write_color(lane, idx, params, true) |
| 2316 | } |
| 2317 | |
| 2318 | /// [`set_color`](Self::set_color) without the undo step: the samples *inside* |
| 2319 | /// one pointer drag, whose first write (a plain `set_color`) already took the |
| 2320 | /// snapshot the gesture rolls back to. A drag across a slider is one undo, |
| 2321 | /// not one per pixel -- and undoing it lands where the hand picked it up. |
| 2322 | pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { |
| 2323 | self.write_color(lane, idx, params, false) |
| 2324 | } |
| 2325 | |
| 2326 | fn write_color( |
| 2327 | &mut self, |
| 2328 | lane: Lane, |
| 2329 | idx: usize, |
| 2330 | params: Option<ColorParams>, |
| 2331 | snapshot: bool, |
| 2332 | ) -> bool { |
| 2333 | if idx >= self.lane(lane).len() { |
| 2334 | return false; |
| 2335 | } |
| 2336 | let slot = match params { |
| 2337 | None => None, |
| 2338 | Some(params) => { |
| 2339 | if !color_finite(¶ms) { |
| 2340 | return false; |
| 2341 | } |
| 2342 | Some(match self.color.iter().position(|p| *p == params) { |
| 2343 | Some(at) => at as u16, |
| 2344 | // corner-cut: the 65535th *distinct* grade of one session is |
| 2345 | // refused rather than silently aliased, exactly as `set_eq` |
| 2346 | // refuses the 65535th curve; same upgrade path. |
| 2347 | None if self.color.len() >= usize::from(u16::MAX) => return false, |
| 2348 | None => { |
| 2349 | self.color.push(params); |
| 2350 | (self.color.len() - 1) as u16 |
| 2351 | } |
| 2352 | }) |
| 2353 | } |
| 2354 | }; |
| 2355 | if snapshot { |
| 2356 | self.snapshot(); |
| 2357 | } |
| 2358 | self.lane_mut(lane).expect("checked above")[idx].color = slot; |
| 2359 | true |
| 2360 | } |
| 2361 | |
| 2362 | /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit |
| 2363 | /// policy's own placement (and for an index that is not there) -- what the |
| 2364 | /// renderer and the export ask before they place its picture. |
| 2365 | pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> { |
| 2366 | self.transform |
| 2367 | .get(usize::from(self.lane(lane).get(idx)?.transform?)) |
| 2368 | } |
| 2369 | |
| 2370 | /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo |
| 2371 | /// step, `false` (and no history) for an index that is not there or a |
| 2372 | /// value that is not finite, and equal settings share a table entry. |
| 2373 | pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool { |
| 2374 | self.write_transform(lane, idx, params, true) |
| 2375 | } |
| 2376 | |
| 2377 | /// [`set_transform`](Self::set_transform) without the undo step, for |
| 2378 | /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside |
| 2379 | /// one drag on a position/scale/rotate/crop control are one undo, not one |
| 2380 | /// per pixel. |
| 2381 | pub fn set_transform_live( |
| 2382 | &mut self, |
| 2383 | lane: Lane, |
| 2384 | idx: usize, |
| 2385 | params: Option<TransformParams>, |
| 2386 | ) -> bool { |
| 2387 | self.write_transform(lane, idx, params, false) |
| 2388 | } |
| 2389 | |
| 2390 | fn write_transform( |
| 2391 | &mut self, |
| 2392 | lane: Lane, |
| 2393 | idx: usize, |
| 2394 | params: Option<TransformParams>, |
| 2395 | snapshot: bool, |
| 2396 | ) -> bool { |
| 2397 | if idx >= self.lane(lane).len() { |
| 2398 | return false; |
| 2399 | } |
| 2400 | let slot = match params { |
| 2401 | None => None, |
| 2402 | Some(params) => { |
| 2403 | if !transform_finite(¶ms) { |
| 2404 | return false; |
| 2405 | } |
| 2406 | Some(match self.transform.iter().position(|p| *p == params) { |
| 2407 | Some(at) => at as u16, |
| 2408 | // corner-cut: the 65535th *distinct* transform of one |
| 2409 | // session is refused rather than silently aliased, |
| 2410 | // exactly as `write_color` refuses the 65535th grade; |
| 2411 | // same upgrade path. |
| 2412 | None if self.transform.len() >= usize::from(u16::MAX) => return false, |
| 2413 | None => { |
| 2414 | self.transform.push(params); |
| 2415 | (self.transform.len() - 1) as u16 |
| 2416 | } |
| 2417 | }) |
| 2418 | } |
| 2419 | }; |
| 2420 | if snapshot { |
| 2421 | self.snapshot(); |
| 2422 | } |
| 2423 | self.lane_mut(lane).expect("checked above")[idx].transform = slot; |
| 2424 | true |
| 2425 | } |
| 2426 | |
| 2427 | /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an |
| 2428 | /// index that is not there, which is what every clip starts at anyway. |
| 2429 | pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed { |
| 2430 | self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed) |
| 2431 | } |
| 2432 | |
| 2433 | /// Sets it, for the clip **and its whole group**: a link is one span on |
| 2434 | /// however many lanes ([`links_are_consistent`]), so a picture sped up away |
| 2435 | /// from its sound would be a group no save could load. One snapshot, so the |
| 2436 | /// group's change is one [`Project::undo`]. |
| 2437 | /// |
| 2438 | /// The source range is untouched -- a speed says how many timeline frames |
| 2439 | /// that range is spread over ([`Clip::frames`]), which is why a trim and a |
| 2440 | /// split still address the file afterwards. |
| 2441 | /// |
| 2442 | /// Refused, changing nothing and costing no undo step, when the clip would |
| 2443 | /// grow into the one after it on its own lane: slowing a clip down makes it |
| 2444 | /// wider, and a lane may not overlap itself. The refusal *names* the clip in |
| 2445 | /// the way -- by lane and timeline frame -- because "it did not fit" is not |
| 2446 | /// something a user can go and fix. Also for an index that is not there. |
| 2447 | pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { |
| 2448 | self.write_speed(lane, idx, speed, true) |
| 2449 | } |
| 2450 | |
| 2451 | /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside* |
| 2452 | /// one pointer drag, whose first write (a plain `set_speed`) already took the |
| 2453 | /// snapshot the gesture rolls back to. A drag across the bar is one undo, |
| 2454 | /// not one per rate it passed through -- exactly as |
| 2455 | /// [`set_color_live`](Self::set_color_live) is for a slider. |
| 2456 | pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { |
| 2457 | self.write_speed(lane, idx, speed, false) |
| 2458 | } |
| 2459 | |
| 2460 | fn write_speed( |
| 2461 | &mut self, |
| 2462 | lane: Lane, |
| 2463 | idx: usize, |
| 2464 | speed: Speed, |
| 2465 | snapshot: bool, |
| 2466 | ) -> crate::Result<()> { |
| 2467 | let Some(members) = self.group_of(lane, idx) else { |
| 2468 | return Err(format!("there is no clip {idx} on {}", lane.label()).into()); |
| 2469 | }; |
| 2470 | let labels = handles(&self.lanes); |
| 2471 | // The clip the hand is holding is the group's clock: everything else |
| 2472 | // in the group, caption members included, re-times by the ratio its new |
| 2473 | // rate gives its own frames. The clips take the rate itself; a caption |
| 2474 | // has none, so it takes the *ratio* -- its span on the timeline |
| 2475 | // compresses or stretches about the held clip's head, while the words |
| 2476 | // it reads keep their own timing ([`write_sub_edge`]'s law: the |
| 2477 | // timeline moves, the track does not). |
| 2478 | let Some(held) = self.lane(lane).get(idx).copied() else { |
| 2479 | return Err(format!("there is no clip {idx} on {}", lane.label()).into()); |
| 2480 | }; |
| 2481 | // The same per-member piece `speeded_playhead` builds for this op, |
| 2482 | // asked here instead of read there -- a caption's length comes from |
| 2483 | // the map's own ends (`end - start`), never `round(len * ratio)` |
| 2484 | // separately, which is what let the two answers drift apart by a |
| 2485 | // frame. |
| 2486 | let (held_old, new) = (held.speed.as_f64(), speed.as_f64()); |
| 2487 | let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f); |
| 2488 | let retimed = |s: SubClip| { |
| 2489 | let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))); |
| 2490 | let start = map.apply(s.start); |
| 2491 | let end = map.apply(s.end()).max(start.saturating_add(1)); |
| 2492 | SubClip { start, frames: end - start, ..s } |
| 2493 | }; |
| 2494 | for &(l, i) in &members.clips { |
| 2495 | let clips = &self.lanes[l].clips; |
| 2496 | let mut moved = clips[i]; |
| 2497 | moved.speed = speed; |
| 2498 | if let Some(next) = clips.get(i + 1) |
| 2499 | && moved.end() > next.start |
| 2500 | { |
| 2501 | let name = labels[l].label(); |
| 2502 | return Err(format!( |
| 2503 | "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \ |
| 2504 | move it along, or trim this one first", |
| 2505 | moved.end(), |
| 2506 | next.start |
| 2507 | ) |
| 2508 | .into()); |
| 2509 | } |
| 2510 | } |
| 2511 | // ...and the captions, against their own lanes' captions: a stretch |
| 2512 | // that runs one into its neighbour is refused for the clip arm's |
| 2513 | // reason -- a lane may not overlap itself -- and by name like it. |
| 2514 | let subs: Vec<(usize, usize, SubClip)> = members |
| 2515 | .subs |
| 2516 | .iter() |
| 2517 | .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i]))) |
| 2518 | .collect(); |
| 2519 | for &(l, i, moved) in &subs { |
| 2520 | for (j, other) in self.lanes[l].subs.iter().enumerate() { |
| 2521 | if j != i && moved.start < other.end() && other.start < moved.end() { |
| 2522 | return Err(format!( |
| 2523 | "at {speed} the {} caption at frame {} would run to frame {} and the next \ |
| 2524 | starts at {}: move it along, or trim this one first", |
| 2525 | labels[l].label(), |
| 2526 | self.lanes[l].subs[i].start, |
| 2527 | moved.end(), |
| 2528 | other.start |
| 2529 | ) |
| 2530 | .into()); |
| 2531 | } |
| 2532 | } |
| 2533 | } |
| 2534 | if snapshot { |
| 2535 | self.snapshot(); |
| 2536 | } |
| 2537 | for (l, i) in members.clips { |
| 2538 | self.lanes[l].clips[i].speed = speed; |
| 2539 | debug_assert!(sorted_disjoint(&self.lanes[l].clips)); |
| 2540 | } |
| 2541 | for (l, i, moved) in subs { |
| 2542 | self.lanes[l].subs[i] = moved; |
| 2543 | debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs)); |
| 2544 | } |
| 2545 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 2546 | Ok(()) |
| 2547 | } |
| 2548 | |
| 2549 | /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a |
| 2550 | /// playhead standing at `at` -- read off the geometry **before** the |
| 2551 | /// write, because the old ends are gone after it. The question a card |
| 2552 | /// asks as its bar moves: the picture under the cursor has to stay the |
| 2553 | /// picture under the cursor, or the scene changes with the rate. |
| 2554 | /// |
| 2555 | /// The answer is piecewise, exactly as [`write_speed`] re-times, and it |
| 2556 | /// is asked of the same [`TimelineMap`] the write itself is a shape of: |
| 2557 | /// a clip member keeps its own start and re-fits its length at the new |
| 2558 | /// rate -- its **old** rate against the new one, which is what the bar's |
| 2559 | /// live samples ask about as much as a first press does; a caption |
| 2560 | /// member scales about the held clip's start by the held clip's own |
| 2561 | /// proportion; and a playhead outside every member's old extent stays |
| 2562 | /// exactly where it was -- nothing ripples, so the gap a shrink leaves |
| 2563 | /// (or the room a stretch takes) absorbs the difference, not the |
| 2564 | /// playhead. `None` for an index that is not there. |
| 2565 | pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> { |
| 2566 | let members = self.group_of(lane, idx)?; |
| 2567 | let held = self.lane(lane).get(idx).copied()?; |
| 2568 | let (held_old, new) = (held.speed.as_f64(), speed.as_f64()); |
| 2569 | for &(l, i) in members.clips.iter().chain(&members.subs) { |
| 2570 | let (span, map) = match self |
| 2571 | .lanes[l] |
| 2572 | .clips |
| 2573 | .get(i) |
| 2574 | .filter(|_| members.clips.contains(&(l, i))) |
| 2575 | { |
| 2576 | // The clip's own span, re-fitted at its own old rate: one |
| 2577 | // piece of the map, anchored where the clip itself is. The |
| 2578 | // new length is the same *source* frames at the new rate -- |
| 2579 | // len divided by it, never multiplied. |
| 2580 | Some(c) => ( |
| 2581 | (c.start, c.start + c.frames()), |
| 2582 | TimelineMap::piece( |
| 2583 | (c.start, c.start + c.frames()), |
| 2584 | ( |
| 2585 | c.start, |
| 2586 | c.start + (c.len() as f64 / new).round() as u32, |
| 2587 | ), |
| 2588 | ), |
| 2589 | ), |
| 2590 | // The caption's span, scaled about the held clip's head by |
| 2591 | // the held clip's proportion -- the offset the group keeps. |
| 2592 | None => { |
| 2593 | let s = self.lanes[l].subs.get(i)?; |
| 2594 | let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f); |
| 2595 | ( |
| 2596 | (s.start, s.end()), |
| 2597 | TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))), |
| 2598 | ) |
| 2599 | } |
| 2600 | }; |
| 2601 | // The piece owns only its own old span: outside it the playhead |
| 2602 | // is another member's question, or nobody's. |
| 2603 | if (span.0..span.1).contains(&at) { |
| 2604 | return Some(map.apply(at)); |
| 2605 | } |
| 2606 | } |
| 2607 | Some(at) |
| 2608 | } |
| 2609 | |
| 2610 | /// How the clip at `idx` of `lane` meets a project canvas of another shape. |
| 2611 | /// [`FitPolicy::Fit`] for an index that is not there, which is the default |
| 2612 | /// every clip starts at anyway. |
| 2613 | pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy { |
| 2614 | self.lane(lane) |
| 2615 | .get(idx) |
| 2616 | .map_or(FitPolicy::default(), |c| c.fit) |
| 2617 | } |
| 2618 | |
| 2619 | /// Sets it. One undo step like every other edit, and `false` (with no |
| 2620 | /// history) for an index that is not there. Unlike an eq or a grade there is |
| 2621 | /// no "off": every clip has a policy, and `Fit` is what "off" would mean. |
| 2622 | pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool { |
| 2623 | if idx >= self.lane(lane).len() { |
| 2624 | return false; |
| 2625 | } |
| 2626 | self.snapshot(); |
| 2627 | self.lane_mut(lane).expect("checked above")[idx].fit = fit; |
| 2628 | true |
| 2629 | } |
| 2630 | |
| 2631 | /// Timeline frames of ramp-up from silence at the start of the clip at |
| 2632 | /// `idx` of `lane`. `0` for an index that is not there, same as a clip |
| 2633 | /// that has none. |
| 2634 | pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 { |
| 2635 | self.lane(lane).get(idx).map_or(0, |c| c.fade_in) |
| 2636 | } |
| 2637 | |
| 2638 | /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade |
| 2639 | /// can shrink a clip's audible middle to nothing but never ask for more |
| 2640 | /// ramp than the clip has frames. One undo step like [`Project::set_fit`], |
| 2641 | /// and `false` (no history) for an index that is not there. |
| 2642 | pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 2643 | if idx >= self.lane(lane).len() { |
| 2644 | return false; |
| 2645 | } |
| 2646 | self.snapshot(); |
| 2647 | let clip = &mut self.lane_mut(lane).expect("checked above")[idx]; |
| 2648 | clip.fade_in = frames.min(clip.frames()); |
| 2649 | true |
| 2650 | } |
| 2651 | |
| 2652 | /// Timeline frames of ramp-down to silence at the end of the clip at |
| 2653 | /// `idx` of `lane`. Same promise as [`Project::fade_in_of`]. |
| 2654 | pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 { |
| 2655 | self.lane(lane).get(idx).map_or(0, |c| c.fade_out) |
| 2656 | } |
| 2657 | |
| 2658 | /// Sets it. Same promises as [`Project::set_fade_in`]. |
| 2659 | pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 2660 | if idx >= self.lane(lane).len() { |
| 2661 | return false; |
| 2662 | } |
| 2663 | self.snapshot(); |
| 2664 | let clip = &mut self.lane_mut(lane).expect("checked above")[idx]; |
| 2665 | clip.fade_out = frames.min(clip.frames()); |
| 2666 | true |
| 2667 | } |
| 2668 | |
| 2669 | /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays |
| 2670 | /// into its successor, at its own end. `0` for an index that is not |
| 2671 | /// there, same as a clip that has none. |
| 2672 | pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 { |
| 2673 | self.lane(lane).get(idx).map_or(0, |c| c.transition_out) |
| 2674 | } |
| 2675 | |
| 2676 | /// Sets it, clamped to the clip's own length and to how many frames its |
| 2677 | /// successor on `lane` actually offers -- a dissolve can shrink a clip's |
| 2678 | /// visible middle to nothing but never ask for more than the two clips |
| 2679 | /// between them have. `false` -- no history -- unless `lane` is video, |
| 2680 | /// `idx + 1` is in bounds, and the two clips are adjacent: the second's |
| 2681 | /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between |
| 2682 | /// them. One undo step like [`Project::set_fade_out`]. |
| 2683 | pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 2684 | if lane.kind != LaneKind::Video { |
| 2685 | return false; |
| 2686 | } |
| 2687 | let clips = self.lane(lane); |
| 2688 | let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else { |
| 2689 | return false; |
| 2690 | }; |
| 2691 | if a.end() != b.start { |
| 2692 | return false; |
| 2693 | } |
| 2694 | let cap = a.frames().min(b.frames()); |
| 2695 | self.snapshot(); |
| 2696 | self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap); |
| 2697 | true |
| 2698 | } |
| 2699 | |
| 2700 | /// Crossfades the audio clip at `idx` of `lane` into the one immediately |
| 2701 | /// after it, over `frames` timeline frames: sets `idx`'s |
| 2702 | /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`, |
| 2703 | /// each clamped to its own clip's length. `false` -- no history -- unless |
| 2704 | /// `lane` is audio, `idx + 1` is in bounds, and the two clips are |
| 2705 | /// adjacent: the second's [`Clip::start`] is exactly the first's |
| 2706 | /// [`Clip::end`], no gap between them. |
| 2707 | /// |
| 2708 | /// This is the whole mechanism, not a stand-in for one: a *real* |
| 2709 | /// cross-fade -- both takes heard at once, blending -- is what two clips |
| 2710 | /// **overlapping** on separate lanes already get for free from the |
| 2711 | /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]). |
| 2712 | /// This call only shapes the edges of two clips already sitting |
| 2713 | /// end-to-end on *one* lane, so the join between them fades like one did. |
| 2714 | pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 2715 | if lane.kind != LaneKind::Audio { |
| 2716 | return false; |
| 2717 | } |
| 2718 | let clips = self.lane(lane); |
| 2719 | let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else { |
| 2720 | return false; |
| 2721 | }; |
| 2722 | if a.end() != b.start { |
| 2723 | return false; |
| 2724 | } |
| 2725 | self.snapshot(); |
| 2726 | let clips = self.lane_mut(lane).expect("checked above"); |
| 2727 | clips[idx].fade_out = frames.min(clips[idx].frames()); |
| 2728 | clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames()); |
| 2729 | true |
| 2730 | } |
| 2731 | |
| 2732 | /// Every frame number on every lane rewritten onto a timeline counted at |
| 2733 | /// another rate: `k` is old timeline frames per new one, `counts` is how |
| 2734 | /// long each source is on the *new* timeline (indexed as |
| 2735 | /// [`Project::sources`] is), and the edit survives as the same seconds of |
| 2736 | /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to |
| 2737 | /// the edit list, and the only thing that touches the frame numbers without |
| 2738 | /// being an edit anyone made. |
| 2739 | /// |
| 2740 | /// Every position -- a clip's start and its end alike -- goes through the |
| 2741 | /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap |
| 2742 | /// stays a gap, and a take's picture and its sound land on the same frame on |
| 2743 | /// their two lanes: no lane can drift against another. A clip is then only |
| 2744 | /// ever made to *fit* the room its own start and end mapped to, never to |
| 2745 | /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor |
| 2746 | /// below is the backstop for the one case that could: a slow clip so short |
| 2747 | /// that no source range fits its new room at all). |
| 2748 | /// |
| 2749 | /// corner-cut: not exact both ways. Each rate change re-rounds every boundary |
| 2750 | /// onto the new grid, so a rate picked, unpicked and picked again is within |
| 2751 | /// a frame of where it started rather than back at it. Upgrade path is |
| 2752 | /// keeping the edit list at one reference rate and conforming on the way |
| 2753 | /// out, which every frame number in this module would then be measured in. |
| 2754 | pub fn retime(&mut self, k: Rate, counts: &[u32]) { |
| 2755 | for lane in &mut self.lanes { |
| 2756 | let mut cursor = 0; |
| 2757 | for clip in &mut lane.clips { |
| 2758 | let start = k.timeline_at(clip.start).max(cursor); |
| 2759 | // The room its own end mapped to -- never zero, since a clip is |
| 2760 | // never empty even on a grid too coarse to hold it. |
| 2761 | let room = k.timeline_at(clip.end()).saturating_sub(start).max(1); |
| 2762 | let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1); |
| 2763 | // Its footage, held inside the file's new length: a clip whose |
| 2764 | // out-point was the last frame of its source must not come out |
| 2765 | // of this naming a frame past the end -- that is a project that |
| 2766 | // would not open again ([`crate::PlaybackSession::open_project`] |
| 2767 | // refuses one by name). |
| 2768 | let in_frame = k.timeline_at(clip.in_frame).min(count - 1); |
| 2769 | let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame); |
| 2770 | clip.start = start; |
| 2771 | clip.in_frame = in_frame; |
| 2772 | clip.out_frame = in_frame + len; |
| 2773 | cursor = clip.end(); |
| 2774 | } |
| 2775 | // A subtitle's *window* is in microseconds and a rate change moves |
| 2776 | // no seconds, so only where it sits is remapped -- through the same |
| 2777 | // [`Rate::timeline_at`] every clip boundary goes through, so a |
| 2778 | // caption still starts on the frame its picture does. |
| 2779 | let mut cursor = 0; |
| 2780 | for sub in &mut lane.subs { |
| 2781 | let start = k.timeline_at(sub.start).max(cursor); |
| 2782 | sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1); |
| 2783 | sub.start = start; |
| 2784 | cursor = sub.end(); |
| 2785 | } |
| 2786 | } |
| 2787 | } |
| 2788 | |
| 2789 | /// Length of the timeline in frames: where the *last* lane runs out. A lane |
| 2790 | /// that ends early is a trailing gap in that lane, not a shorter timeline. |
| 2791 | /// |
| 2792 | /// A subtitle lane counts like any other: a caption placed past the last |
| 2793 | /// picture holds the timeline open under it, exactly as an `A2` running |
| 2794 | /// past `V1` does, rather than being silently clipped away by the length |
| 2795 | /// ([`crate::export::timeline_cues`] clips cues to this). |
| 2796 | pub fn timeline_frames(&self) -> u32 { |
| 2797 | self.lanes |
| 2798 | .iter() |
| 2799 | .filter_map(|l| match l.kind { |
| 2800 | LaneKind::Subtitle => l.subs.last().map(SubClip::end), |
| 2801 | _ => l.clips.last().map(Clip::end), |
| 2802 | }) |
| 2803 | .max() |
| 2804 | .unwrap_or(0) |
| 2805 | } |
| 2806 | |
| 2807 | /// The same, counting the *media* alone: where the last picture or sound |
| 2808 | /// runs out, with the captions over them ignored. |
| 2809 | /// |
| 2810 | /// What an export actually writes ends here -- the picture loop walks the |
| 2811 | /// composite spans and the file stops with them -- so this is the length a |
| 2812 | /// cue has to be inside of to be written at all (what |
| 2813 | /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to |
| 2814 | /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last |
| 2815 | /// thing is a picture or a sound, which is every timeline that has no |
| 2816 | /// caption hanging past the end of both. |
| 2817 | pub fn media_frames(&self) -> u32 { |
| 2818 | self.lanes |
| 2819 | .iter() |
| 2820 | .filter(|l| l.kind != LaneKind::Subtitle) |
| 2821 | .filter_map(|l| l.clips.last().map(Clip::end)) |
| 2822 | .max() |
| 2823 | .unwrap_or(0) |
| 2824 | } |
| 2825 | |
| 2826 | /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs |
| 2827 | /// to lay clips out. Gaps show up as the holes between consecutive entries. |
| 2828 | pub fn clip_spans(&self) -> Vec<(u32, u32)> { |
| 2829 | self.lane_spans(Lane::V1) |
| 2830 | } |
| 2831 | |
| 2832 | pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> { |
| 2833 | // Timeline frames, not source ones: a box on a lane is as wide as the |
| 2834 | // clip is long *there*, which a speed halves or quadruples. |
| 2835 | self.lane(lane) |
| 2836 | .iter() |
| 2837 | .map(|c| (c.start, c.frames())) |
| 2838 | .collect() |
| 2839 | } |
| 2840 | |
| 2841 | /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap |
| 2842 | /// and past the end -- [`Project::span_at`] is the version that tells those |
| 2843 | /// two apart. |
| 2844 | pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> { |
| 2845 | let clips = self.lane(lane); |
| 2846 | let idx = at(clips, timeline_frame)?; |
| 2847 | Some((idx, source_frame(&clips[idx], timeline_frame))) |
| 2848 | } |
| 2849 | |
| 2850 | /// [`map`](Project::map) on `V1` -- the mapping a decoder follows. |
| 2851 | pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> { |
| 2852 | self.map(Lane::V1, timeline_frame) |
| 2853 | } |
| 2854 | |
| 2855 | /// What `lane` holds from `timeline_frame` on: the rest of the clip covering |
| 2856 | /// it, or the gap running to the next clip (or to the end of the timeline, |
| 2857 | /// which is where a lane shorter than its neighbour keeps showing black). |
| 2858 | /// `None` at or past the end of the timeline, which is the only "nothing |
| 2859 | /// left" there is. |
| 2860 | pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> { |
| 2861 | let total = self.timeline_frames(); |
| 2862 | if timeline_frame >= total { |
| 2863 | return None; |
| 2864 | } |
| 2865 | let clips = self.lane(lane); |
| 2866 | Some(match at(clips, timeline_frame) { |
| 2867 | Some(idx) => Span { |
| 2868 | start: timeline_frame, |
| 2869 | len: clips[idx].end() - timeline_frame, |
| 2870 | from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))), |
| 2871 | speed: clips[idx].speed, |
| 2872 | }, |
| 2873 | None => Span { |
| 2874 | start: timeline_frame, |
| 2875 | speed: Speed::NORMAL, |
| 2876 | // The next placement, or the end of the timeline: a gap is |
| 2877 | // bounded by what comes after it, never by its own bookkeeping. |
| 2878 | len: clips |
| 2879 | .iter() |
| 2880 | .find(|c| c.start > timeline_frame) |
| 2881 | .map_or(total, |c| c.start) |
| 2882 | - timeline_frame, |
| 2883 | from: None, |
| 2884 | }, |
| 2885 | }) |
| 2886 | } |
| 2887 | |
| 2888 | /// Every span of `lane` from `timeline_frame` to the end of the timeline, |
| 2889 | /// gaps included -- the whole play list, which is what an export walks. |
| 2890 | pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> { |
| 2891 | let mut out = Vec::new(); |
| 2892 | let mut t = timeline_frame; |
| 2893 | while let Some(span) = self.span_at(lane, t) { |
| 2894 | t = span.end(); |
| 2895 | out.push(span); |
| 2896 | } |
| 2897 | out |
| 2898 | } |
| 2899 | |
| 2900 | /// What the *composite* shows from `timeline_frame` on -- the answer |
| 2901 | /// [`span_at`](Project::span_at) gives for one lane, resolved across every |
| 2902 | /// video lane by one rule: **the topmost lane with a clip there wins**, and |
| 2903 | /// topmost is the *last* video lane in display order, so `V2` covers `V1` |
| 2904 | /// (the usual overlay convention). A frame no video lane covers is a gap, |
| 2905 | /// which is black however many lanes are above or below it. |
| 2906 | /// |
| 2907 | /// No blending, so exactly one lane is visible at a time and the composite |
| 2908 | /// is itself a span list -- which is why one decoder plays it, the same one |
| 2909 | /// a single-lane timeline uses, rather than N running at once. |
| 2910 | /// |
| 2911 | /// The span is cut short wherever a *higher* lane's clip starts, because |
| 2912 | /// from that frame on a different lane wins; that is what makes walking |
| 2913 | /// [`composite_spans_from`](Project::composite_spans_from) correct. |
| 2914 | /// |
| 2915 | /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two |
| 2916 | /// lanes would then be visible in one frame and the caller needs a decoder |
| 2917 | /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame |
| 2918 | /// (this same walk, per lane) feeding N decoders. |
| 2919 | pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> { |
| 2920 | let total = self.timeline_frames(); |
| 2921 | if timeline_frame >= total { |
| 2922 | return None; |
| 2923 | } |
| 2924 | let video = self.video_lanes(); |
| 2925 | // The last covering lane is the winner; only the lanes above it can |
| 2926 | // interrupt what it shows. |
| 2927 | let winner = video |
| 2928 | .iter() |
| 2929 | .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some()); |
| 2930 | let (from, speed, until) = match winner { |
| 2931 | Some(i) => { |
| 2932 | let clips = self.lane(video[i]); |
| 2933 | let idx = at(clips, timeline_frame).expect("just found above"); |
| 2934 | ( |
| 2935 | Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))), |
| 2936 | clips[idx].speed, |
| 2937 | clips[idx].end(), |
| 2938 | ) |
| 2939 | } |
| 2940 | // Nothing covers it: black until something above the floor starts. |
| 2941 | None => (None, Speed::NORMAL, total), |
| 2942 | }; |
| 2943 | let takeover = video[winner.map_or(0, |i| i + 1)..] |
| 2944 | .iter() |
| 2945 | .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame)) |
| 2946 | .map(|c| c.start) |
| 2947 | .min(); |
| 2948 | Some(Span { |
| 2949 | start: timeline_frame, |
| 2950 | len: takeover.map_or(until, |t| t.min(until)) - timeline_frame, |
| 2951 | from, |
| 2952 | speed, |
| 2953 | }) |
| 2954 | } |
| 2955 | |
| 2956 | /// The video lanes in display order, topmost last -- the order the composite |
| 2957 | /// rule counts in. |
| 2958 | fn video_lanes(&self) -> Vec<Lane> { |
| 2959 | self.lanes() |
| 2960 | .into_iter() |
| 2961 | .filter(|l| l.kind == LaneKind::Video) |
| 2962 | .collect() |
| 2963 | } |
| 2964 | |
| 2965 | /// *Which* clip the composite shows at `timeline_frame`, named: the winner |
| 2966 | /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its |
| 2967 | /// index on that lane. `None` over a gap and past the end. What a front-end |
| 2968 | /// asks to act on "the clip on screen" without re-deriving the rule. |
| 2969 | pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> { |
| 2970 | let video = self.video_lanes(); |
| 2971 | let winner = video |
| 2972 | .iter() |
| 2973 | .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?; |
| 2974 | Some((video[winner], at(self.lane(video[winner]), timeline_frame)?)) |
| 2975 | } |
| 2976 | |
| 2977 | /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap |
| 2978 | /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at) |
| 2979 | /// answers "the clip on screen"; this answers it per lane, which is what |
| 2980 | /// walking the lanes for something to select needs. |
| 2981 | pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> { |
| 2982 | at(self.lane(lane), timeline_frame) |
| 2983 | } |
| 2984 | |
| 2985 | /// How the composite is graded at `timeline_frame`, so the picture playback |
| 2986 | /// converts and the one an export encodes are graded from one answer. |
| 2987 | /// `None` over a gap (black is black) and for a clip nobody has graded, |
| 2988 | /// which is the byte-identical path everywhere. |
| 2989 | pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> { |
| 2990 | let (lane, idx) = self.composite_clip_at(timeline_frame)?; |
| 2991 | self.color_of(lane, idx) |
| 2992 | } |
| 2993 | |
| 2994 | /// [`composite_color_at`](Self::composite_color_at)'s twin for |
| 2995 | /// [`Clip::transform`]: `None` over a gap and for a clip at its fit |
| 2996 | /// policy's own placement. |
| 2997 | pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> { |
| 2998 | let (lane, idx) = self.composite_clip_at(timeline_frame)?; |
| 2999 | self.transform_of(lane, idx) |
| 3000 | } |
| 3001 | |
| 3002 | /// How the composite meets the project canvas at `timeline_frame`, so the |
| 3003 | /// picture playback composes and the one an export encodes are placed from |
| 3004 | /// one answer. `Fit` over a gap, where black is already the canvas. |
| 3005 | pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy { |
| 3006 | self.composite_clip_at(timeline_frame) |
| 3007 | .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx)) |
| 3008 | } |
| 3009 | |
| 3010 | /// [`spans_from`](Project::spans_from) over the composite: every stretch the |
| 3011 | /// viewer sees from `timeline_frame` to the end, in order. What an export |
| 3012 | /// encodes and what playback walks at a clip boundary. |
| 3013 | pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> { |
| 3014 | let mut out = Vec::new(); |
| 3015 | let mut t = timeline_frame; |
| 3016 | while let Some(span) = self.composite_span_at(t) { |
| 3017 | t = span.end(); |
| 3018 | out.push(span); |
| 3019 | } |
| 3020 | out |
| 3021 | } |
| 3022 | |
| 3023 | /// Split every lane at `timeline_frame`, so that frame becomes the first |
| 3024 | /// frame of a new clip, and hand the two sides two fresh group ids. Refused |
| 3025 | /// (`false`, no change) when no lane has a clip to split there -- at a |
| 3026 | /// placement's own start, in a gap, and past the end -- all of which would |
| 3027 | /// produce an empty clip or nothing at all. |
| 3028 | /// |
| 3029 | /// Lanes' halves share an id only where they are the *same* span: the lanes |
| 3030 | /// are edited apart, so the clip being cut here may start (or end) |
| 3031 | /// somewhere else on another lane, and a group id whose clips disagree |
| 3032 | /// about their span is not one take (see [`links_are_consistent`], which |
| 3033 | /// refuses to load one). |
| 3034 | /// |
| 3035 | /// Metadata only: no mapping changes, in any lane. |
| 3036 | pub fn split(&mut self, timeline_frame: u32) -> bool { |
| 3037 | self.write_split(timeline_frame, true, &all_lanes(&self.lanes)) |
| 3038 | } |
| 3039 | |
| 3040 | /// [`split`](Project::split), with the snapshot optional and the lanes |
| 3041 | /// named: a batch that has already taken a snapshot |
| 3042 | /// ([`speed_regions`](Project::speed_regions)) splits at two frames per |
| 3043 | /// region and must still be one undo press, and a *scoped* batch must not |
| 3044 | /// cut a lane it was told to leave alone. |
| 3045 | fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool { |
| 3046 | let cut: Vec<Option<Clip>> = self |
| 3047 | .lanes |
| 3048 | .iter() |
| 3049 | .enumerate() |
| 3050 | .map(|(i, l)| { |
| 3051 | on.contains(&i) |
| 3052 | .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx])) |
| 3053 | .flatten() |
| 3054 | }) |
| 3055 | .collect(); |
| 3056 | // The same question on the subtitle lanes, in their own arithmetic: a |
| 3057 | // razor cuts the captions with the picture, and a frame where only a |
| 3058 | // caption can be cut is still a cut. |
| 3059 | let cut_subs: Vec<bool> = self |
| 3060 | .lanes |
| 3061 | .iter() |
| 3062 | .enumerate() |
| 3063 | .map(|(i, l)| { |
| 3064 | on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end()) |
| 3065 | }) |
| 3066 | .collect(); |
| 3067 | // The links the captions carry, read before the room is opened below |
| 3068 | // -- `sub_open_room` takes the id off both halves, exactly as |
| 3069 | // `open_room` does for a clip, and the split hands the halves theirs |
| 3070 | // back afterwards. |
| 3071 | let sub_orig: Vec<Option<u32>> = self |
| 3072 | .lanes |
| 3073 | .iter() |
| 3074 | .zip(&cut_subs) |
| 3075 | .map(|(l, &cut)| { |
| 3076 | cut.then(|| { |
| 3077 | l.subs |
| 3078 | .iter() |
| 3079 | .find(|s| s.start < timeline_frame && timeline_frame < s.end()) |
| 3080 | .and_then(|s| s.link) |
| 3081 | }) |
| 3082 | .flatten() |
| 3083 | }) |
| 3084 | .collect(); |
| 3085 | if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) { |
| 3086 | return false; |
| 3087 | } |
| 3088 | if snapshot { |
| 3089 | self.snapshot(); |
| 3090 | } |
| 3091 | for (data, _) in self |
| 3092 | .lanes |
| 3093 | .iter_mut() |
| 3094 | .zip(&cut_subs) |
| 3095 | .filter(|&(_, &cut)| cut) |
| 3096 | { |
| 3097 | // A split is room of no width: the halves keep their windows by |
| 3098 | // proportion and nothing moves. |
| 3099 | sub_open_room(&mut data.subs, timeline_frame, 0); |
| 3100 | debug_assert!(subs_sorted_disjoint(&data.subs)); |
| 3101 | } |
| 3102 | // Each side is its own question, and the answer is the group the clip |
| 3103 | // already carried: the left half *keeps* its take's id -- the take the |
| 3104 | // frames before the cut still are -- and the right halves of one take |
| 3105 | // share one fresh id of their own, clips and captions alike. A lane |
| 3106 | // holding no group (a `place`ment, a caption nobody grouped) comes out |
| 3107 | // of the cut holding none, which is what it went in with. The captions' |
| 3108 | // own links were drawn above, before the room opened. |
| 3109 | let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect(); |
| 3110 | let mut distinct: Vec<u32> = Vec::new(); |
| 3111 | for id in orig.iter().chain(&sub_orig).flatten() { |
| 3112 | if !distinct.contains(id) { |
| 3113 | distinct.push(*id); |
| 3114 | } |
| 3115 | } |
| 3116 | let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect(); |
| 3117 | let right_of = |
| 3118 | |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]); |
| 3119 | for (l, data) in self.lanes.iter_mut().enumerate() { |
| 3120 | if !cut_subs[l] { |
| 3121 | continue; |
| 3122 | } |
| 3123 | // The pair the razor just made: they touch at the frame it cut. |
| 3124 | if let Some(idx) = data |
| 3125 | .subs |
| 3126 | .iter() |
| 3127 | .position(|s| s.end() == timeline_frame) |
| 3128 | .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame)) |
| 3129 | { |
| 3130 | data.subs[idx].link = sub_orig[l]; |
| 3131 | data.subs[idx + 1].link = right_of(sub_orig[l]); |
| 3132 | } |
| 3133 | } |
| 3134 | for (data_i, data) in self.lanes.iter_mut().enumerate() { |
| 3135 | // The lanes this call was not scoped to are not cut, whatever their |
| 3136 | // own clips would allow. |
| 3137 | let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else { |
| 3138 | continue; |
| 3139 | }; |
| 3140 | let mut tail = data.clips[idx]; |
| 3141 | // Where the cut lands *in the file*, which is the clip's own rate |
| 3142 | // away from where it lands on the timeline. Both halves keep the |
| 3143 | // speed, and `splittable` has already refused any frame at which |
| 3144 | // the two would not add up to the one being cut. |
| 3145 | tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so"); |
| 3146 | tail.start = timeline_frame; |
| 3147 | tail.link = right_of(orig[data_i]); |
| 3148 | // A split makes a new edge for each half, and a fade is a promise |
| 3149 | // about an edge: only the half that *kept* the original edge |
| 3150 | // keeps that fade, re-clamped to its own now-shorter length (a |
| 3151 | // cut inside the ramp shortens it, never leaves it pointing past |
| 3152 | // the clip it is on); the edge the cut itself made starts, or |
| 3153 | // ends, flat -- there was no silence there to ramp out of. |
| 3154 | tail.fade_in = 0; |
| 3155 | tail.fade_out = tail.fade_out.min(tail.frames()); |
| 3156 | // A dissolve is a promise about the *end* edge, same as |
| 3157 | // `fade_out`: only the half that kept the clip's original end |
| 3158 | // (the tail) keeps it, re-clamped to its own now-shorter length; |
| 3159 | // the head's new end is the cut the razor just made, which starts |
| 3160 | // flat -- there was no successor to dissolve into there. |
| 3161 | tail.transition_out = tail.transition_out.min(tail.frames()); |
| 3162 | data.clips[idx].out_frame = tail.in_frame; |
| 3163 | data.clips[idx].link = orig[data_i]; |
| 3164 | data.clips[idx].fade_out = 0; |
| 3165 | data.clips[idx].transition_out = 0; |
| 3166 | data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames()); |
| 3167 | data.clips.insert(idx + 1, tail); |
| 3168 | } |
| 3169 | true |
| 3170 | } |
| 3171 | |
| 3172 | /// The inverse of [`split`](Project::split): rejoin the placements that meet |
| 3173 | /// at `timeline_frame` in every lane and put the result back in one group. |
| 3174 | /// Only what a split could have produced is rejoined -- the two sides must |
| 3175 | /// touch on the timeline *and* be consecutive frames of the same source -- |
| 3176 | /// so the clip list comes back exactly as it was and traversal with it. |
| 3177 | /// `false` when no lane has such a pair. The rejoined placement keeps the |
| 3178 | /// **left** half's id, which is the take the split left on it: rejoining a |
| 3179 | /// cut take puts the take back, id and all. |
| 3180 | pub fn regroup(&mut self, timeline_frame: u32) -> bool { |
| 3181 | // What each lane would end up covering, if it joins here at all. |
| 3182 | let joined: Vec<Option<(u32, u32)>> = self |
| 3183 | .lanes |
| 3184 | .iter() |
| 3185 | .map(|l| { |
| 3186 | joinable(&l.clips, timeline_frame) |
| 3187 | .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end())) |
| 3188 | }) |
| 3189 | .collect(); |
| 3190 | // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule. |
| 3191 | let join_subs: Vec<Option<usize>> = self |
| 3192 | .lanes |
| 3193 | .iter() |
| 3194 | .map(|l| sub_joinable(&l.subs, timeline_frame)) |
| 3195 | .collect(); |
| 3196 | if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) { |
| 3197 | return false; |
| 3198 | } |
| 3199 | self.snapshot(); |
| 3200 | for (data, sub) in self.lanes.iter_mut().zip(join_subs) { |
| 3201 | if let Some(idx) = sub { |
| 3202 | data.subs[idx].frames += data.subs[idx + 1].frames; |
| 3203 | data.subs[idx].out_us = data.subs[idx + 1].out_us; |
| 3204 | data.subs.remove(idx + 1); |
| 3205 | debug_assert!(subs_sorted_disjoint(&data.subs)); |
| 3206 | } |
| 3207 | let Some(idx) = joinable(&data.clips, timeline_frame) else { |
| 3208 | continue; |
| 3209 | }; |
| 3210 | data.clips[idx].out_frame = data.clips[idx + 1].out_frame; |
| 3211 | data.clips.remove(idx + 1); |
| 3212 | } |
| 3213 | true |
| 3214 | } |
| 3215 | |
| 3216 | /// Take the placement at `idx` of `lane` out of its group: every clip and |
| 3217 | /// every caption carrying its id -- on however many lanes -- is handed an |
| 3218 | /// id of its own, so from here on each half moves, trims and is deleted |
| 3219 | /// alone. The music video whose sound is to be cut against its picture |
| 3220 | /// starts here, and so does the caption that has to come off the picture it |
| 3221 | /// was pinned to. |
| 3222 | /// |
| 3223 | /// An id of its own rather than none at all: a half no other lane is grouped |
| 3224 | /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal |
| 3225 | /// (see [`links_are_consistent`]), and it is what a front-end already draws |
| 3226 | /// as detached. `None` would instead say "was never part of a take", which |
| 3227 | /// is what a one-lane [`place`](Project::place) means. |
| 3228 | /// |
| 3229 | /// Metadata only, like a [`split`](Project::split): no mapping changes, so |
| 3230 | /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts |
| 3231 | /// the group back. Refused (`false`, nothing changed) for an index that is |
| 3232 | /// not there, a placement in no group at all, and one whose group has no |
| 3233 | /// other half -- that one is already detached, and a refusal must not cost |
| 3234 | /// an undo step. |
| 3235 | pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool { |
| 3236 | let Some(members) = self.group_of(lane, idx) else { |
| 3237 | return false; |
| 3238 | }; |
| 3239 | if members.alone() { |
| 3240 | return false; |
| 3241 | } |
| 3242 | let Some(id) = self |
| 3243 | .lane(lane) |
| 3244 | .get(idx) |
| 3245 | .and_then(|c| c.link) |
| 3246 | .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link)) |
| 3247 | else { |
| 3248 | return false; |
| 3249 | }; |
| 3250 | self.snapshot(); |
| 3251 | // Drawn before the walk: `new_link` takes the whole project, and the |
| 3252 | // walk holds the lanes. |
| 3253 | let count = members.clips.len() + members.subs.len(); |
| 3254 | let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>(); |
| 3255 | for data in &mut self.lanes { |
| 3256 | for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) { |
| 3257 | c.link = fresh.pop(); |
| 3258 | } |
| 3259 | for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) { |
| 3260 | s.link = fresh.pop(); |
| 3261 | } |
| 3262 | } |
| 3263 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 3264 | true |
| 3265 | } |
| 3266 | |
| 3267 | /// Put two clips on two lanes into one group, so what moves one moves the |
| 3268 | /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and |
| 3269 | /// how a picture is regrouped with sound it was never opened with. Whatever |
| 3270 | /// either of them was grouped with comes along: those clips cover this same |
| 3271 | /// span already, so the result is one group and not two overlapping ones. |
| 3272 | /// |
| 3273 | /// Same frames or nothing: a group id names **one span** on however many |
| 3274 | /// lanes ([`links_are_consistent`] refuses to load anything else), so two |
| 3275 | /// clips that do not cover the same frames cannot be one take, and the |
| 3276 | /// refusal says which bounds to trim to. Kinds are *not* checked: a take may |
| 3277 | /// run on `V1` and `V2` at once, and picture-with-sound is the case people |
| 3278 | /// mean, not the rule. |
| 3279 | /// |
| 3280 | /// Metadata only, one snapshot. The error says what is wrong, because |
| 3281 | /// `false` would not: a bad index, one lane twice (a group is at most one |
| 3282 | /// clip per lane), spans that disagree, and a pair that is already one take |
| 3283 | /// -- nothing changes, and none of them costs an undo step. |
| 3284 | pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> { |
| 3285 | if a == b { |
| 3286 | return Err(format!( |
| 3287 | "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}", |
| 3288 | a.label() |
| 3289 | ) |
| 3290 | .into()); |
| 3291 | } |
| 3292 | let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> { |
| 3293 | p.lane(lane) |
| 3294 | .get(idx) |
| 3295 | .copied() |
| 3296 | .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into()) |
| 3297 | }; |
| 3298 | let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?); |
| 3299 | if (x.start, x.end()) != (y.start, y.end()) { |
| 3300 | return Err(format!( |
| 3301 | "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first", |
| 3302 | a.label(), |
| 3303 | x.start, |
| 3304 | x.end(), |
| 3305 | b.label(), |
| 3306 | y.start, |
| 3307 | y.end() |
| 3308 | ) |
| 3309 | .into()); |
| 3310 | } |
| 3311 | if x.link.is_some() && x.link == y.link { |
| 3312 | return Err("those two are one take already".into()); |
| 3313 | } |
| 3314 | self.snapshot(); |
| 3315 | let id = self.new_link(); |
| 3316 | // Every clip either of them was grouped with, by the same rule: all of |
| 3317 | // them cover this span, so one id over the lot stays consistent. |
| 3318 | let old = [x.link, y.link]; |
| 3319 | for data in &mut self.lanes { |
| 3320 | for c in data.clips.iter_mut().filter(|c| c.link.is_some()) { |
| 3321 | if old.contains(&c.link) { |
| 3322 | c.link = Some(id); |
| 3323 | } |
| 3324 | } |
| 3325 | } |
| 3326 | // And the two themselves, which a `place` may have left in no group. |
| 3327 | self.lane_mut(a).expect("read above")[a_idx].link = Some(id); |
| 3328 | self.lane_mut(b).expect("read above")[b_idx].link = Some(id); |
| 3329 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 3330 | Ok(()) |
| 3331 | } |
| 3332 | |
| 3333 | /// Put every placement the picks name into one group -- the group a hand |
| 3334 | /// builds with ctrl-click and a menu: the picture, its sound and the |
| 3335 | /// caption over it, on as many lanes as the picks name. What any of them |
| 3336 | /// was already grouped with rides along (one group, not two sharing a |
| 3337 | /// member), and the members keep their own spans: a group is one id over |
| 3338 | /// one placement per lane, and the offsets between them are what the group |
| 3339 | /// preserves -- a drag, a trim and a delete all move the members *by the |
| 3340 | /// same distance*, not to the same frames. |
| 3341 | /// |
| 3342 | /// No two picks may name one lane -- that is the one clip-per-lane rule, |
| 3343 | /// and the refusal says which lane -- and a pick that names nothing is |
| 3344 | /// refused with its own words. At least two picks, or there is nothing to |
| 3345 | /// group. |
| 3346 | /// |
| 3347 | /// Metadata only, one snapshot, so one [`Project::undo`] takes the group |
| 3348 | /// apart again. None of the refusals changes anything or costs an undo |
| 3349 | /// step. |
| 3350 | pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> { |
| 3351 | if picks.len() < 2 { |
| 3352 | return Err("a group is two placements or more: pick another one first".into()); |
| 3353 | } |
| 3354 | let mut seen: Vec<Lane> = Vec::with_capacity(picks.len()); |
| 3355 | for &(lane, idx) in picks { |
| 3356 | if seen.contains(&lane) { |
| 3357 | return Err(format!( |
| 3358 | "a group is one placement per lane: {} is picked twice -- keep one clip per \ |
| 3359 | track", |
| 3360 | lane.label() |
| 3361 | ) |
| 3362 | .into()); |
| 3363 | } |
| 3364 | seen.push(lane); |
| 3365 | let there = if lane.kind == LaneKind::Subtitle { |
| 3366 | idx < self.sub_lane(lane).len() |
| 3367 | } else { |
| 3368 | idx < self.lane(lane).len() |
| 3369 | }; |
| 3370 | if !there { |
| 3371 | let what = if lane.kind == LaneKind::Subtitle { |
| 3372 | "subtitle" |
| 3373 | } else { |
| 3374 | "clip" |
| 3375 | }; |
| 3376 | return Err( |
| 3377 | format!("there is no {what} {idx} on {}", lane.label()).into() |
| 3378 | ); |
| 3379 | } |
| 3380 | } |
| 3381 | let links: Vec<Option<u32>> = picks |
| 3382 | .iter() |
| 3383 | .map(|&(lane, idx)| { |
| 3384 | if lane.kind == LaneKind::Subtitle { |
| 3385 | self.sub_lane(lane)[idx].link |
| 3386 | } else { |
| 3387 | self.lane(lane)[idx].link |
| 3388 | } |
| 3389 | }) |
| 3390 | .collect(); |
| 3391 | // The picks are already one per lane (`seen`, above), but a pick's |
| 3392 | // *existing* group can carry a second member onto a lane another |
| 3393 | // pick (or another existing group in the merge) already occupies -- |
| 3394 | // two captions on one sub lane, say, each grouped with a different |
| 3395 | // clip before this call. Merging both in would leave that lane with |
| 3396 | // two members of one id, which `links_are_consistent` may never see: |
| 3397 | // refused by name, before anything moves, rather than a group closed |
| 3398 | // broken. |
| 3399 | let labels = handles(&self.lanes); |
| 3400 | let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new(); |
| 3401 | for (li, data) in self.lanes.iter().enumerate() { |
| 3402 | let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count() |
| 3403 | + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count(); |
| 3404 | if n > 0 { |
| 3405 | per_lane.insert(li, n as u32); |
| 3406 | } |
| 3407 | } |
| 3408 | // A pick that carries no link of its own is invisible to the scan |
| 3409 | // above (there is no `Some` to match): it still claims its lane. |
| 3410 | for &(lane, _) in picks { |
| 3411 | let li = self.index(lane).expect("checked above"); |
| 3412 | per_lane.entry(li).or_insert(0); |
| 3413 | if !self.lanes[li] |
| 3414 | .clips |
| 3415 | .iter() |
| 3416 | .any(|c| c.link.is_some() && links.contains(&c.link)) |
| 3417 | && !self.lanes[li] |
| 3418 | .subs |
| 3419 | .iter() |
| 3420 | .any(|s| s.link.is_some() && links.contains(&s.link)) |
| 3421 | { |
| 3422 | *per_lane.get_mut(&li).expect("just inserted") += 1; |
| 3423 | } |
| 3424 | } |
| 3425 | if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) { |
| 3426 | return Err(format!( |
| 3427 | "a group is one placement per lane: merging these groups would put two on {}", |
| 3428 | labels[li].label() |
| 3429 | ) |
| 3430 | .into()); |
| 3431 | } |
| 3432 | self.snapshot(); |
| 3433 | let id = self.new_link(); |
| 3434 | // Whatever any pick was grouped with comes along, for [`group`]'s |
| 3435 | // reason -- one id over the lot, not two groups sharing a member. |
| 3436 | for data in &mut self.lanes { |
| 3437 | for c in data.clips.iter_mut() { |
| 3438 | if c.link.is_some() && links.contains(&c.link) { |
| 3439 | c.link = Some(id); |
| 3440 | } |
| 3441 | } |
| 3442 | for s in data.subs.iter_mut() { |
| 3443 | if s.link.is_some() && links.contains(&s.link) { |
| 3444 | s.link = Some(id); |
| 3445 | } |
| 3446 | } |
| 3447 | } |
| 3448 | // And the picks themselves, which a `place` may have left in no group. |
| 3449 | // The lane seats are read before the walk, which holds the lanes. |
| 3450 | let seats: Vec<(usize, bool)> = picks |
| 3451 | .iter() |
| 3452 | .map(|&(lane, _)| { |
| 3453 | ( |
| 3454 | self.index(lane).expect("checked above"), |
| 3455 | lane.kind == LaneKind::Subtitle, |
| 3456 | ) |
| 3457 | }) |
| 3458 | .collect(); |
| 3459 | for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) { |
| 3460 | let _ = lane; |
| 3461 | if sub { |
| 3462 | self.lanes[at].subs[idx].link = Some(id); |
| 3463 | } else { |
| 3464 | self.lanes[at].clips[idx].link = Some(id); |
| 3465 | } |
| 3466 | } |
| 3467 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 3468 | Ok(()) |
| 3469 | } |
| 3470 | |
| 3471 | /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it |
| 3472 | /// lands on and leaving every other clip exactly where it is -- the |
| 3473 | /// per-lane paste. Anything already there is trimmed away (and split in two |
| 3474 | /// if `clip` lands inside it), which is what keeps the lane sorted and |
| 3475 | /// disjoint; nothing ripples, so a gap before the placement simply stays a |
| 3476 | /// gap. Refused only for an empty `clip`. |
| 3477 | /// |
| 3478 | /// The placement belongs to no group: a clipboard clip carries the link id |
| 3479 | /// of the take it was copied from, and placing it twice -- or placing a copy |
| 3480 | /// back over the clip it came from -- would put that id on two clips of one |
| 3481 | /// lane, which is what a link may never mean (see [`links_are_consistent`]). |
| 3482 | /// `None` rather than a fresh id because a one-lane placement has nothing on |
| 3483 | /// another lane to be grouped *with*; [`Project::regroup`] is how clips |
| 3484 | /// become a group again. |
| 3485 | /// |
| 3486 | /// Refused for an empty `clip`, for a lane that is not there, and for a |
| 3487 | /// subtitle lane, which carries no picture and no sound |
| 3488 | /// ([`Project::place_sub`] is its door). |
| 3489 | pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool { |
| 3490 | if clip.out_frame <= clip.in_frame |
| 3491 | || lane.kind == LaneKind::Subtitle |
| 3492 | || self.index(lane).is_none() |
| 3493 | { |
| 3494 | return false; |
| 3495 | } |
| 3496 | self.snapshot(); |
| 3497 | let clip = Clip { |
| 3498 | fade_in: 0, |
| 3499 | fade_out: 0, |
| 3500 | transition_out: 0, |
| 3501 | start: timeline_frame, |
| 3502 | link: None, |
| 3503 | ..clip |
| 3504 | }; |
| 3505 | self.insert_over(lane, clip); |
| 3506 | true |
| 3507 | } |
| 3508 | |
| 3509 | /// Place `clip` on `lane` **and its sound on that lane's own audio row** as |
| 3510 | /// one grouped take -- what a picture let go over a further video track |
| 3511 | /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added |
| 3512 | /// if it is not there yet (the `+ V` button adds a video row alone). Without |
| 3513 | /// this half a file with sound landed on a layer silent, and the only way to |
| 3514 | /// hear it was to drop it a second time on an audio lane. |
| 3515 | /// |
| 3516 | /// Both halves overwrite what they land on and neither ripples, exactly as |
| 3517 | /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so |
| 3518 | /// nothing under it moves. One history snapshot for the pair, the added lane |
| 3519 | /// included, so one [`Project::undo`] takes the whole placement back. The two |
| 3520 | /// carry one link, which is what makes them one take to a drag, a trim and a |
| 3521 | /// save. |
| 3522 | /// |
| 3523 | /// Refused, changing nothing, for an empty `clip` and for a lane that is not |
| 3524 | /// there or is not a video lane: sound placed alone is |
| 3525 | /// [`place`](Project::place)'s door, and a still has no sound to pair. |
| 3526 | pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool { |
| 3527 | if clip.out_frame <= clip.in_frame |
| 3528 | || lane.kind != LaneKind::Video |
| 3529 | || self.index(lane).is_none() |
| 3530 | { |
| 3531 | return false; |
| 3532 | } |
| 3533 | self.snapshot(); |
| 3534 | // `A2` for `V2` -- and the rows between it and the last audio lane, since |
| 3535 | // an ord names a lane only while every ord below it does. |
| 3536 | while self.lane_count(LaneKind::Audio) <= lane.ord { |
| 3537 | self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new())); |
| 3538 | } |
| 3539 | let clip = Clip { |
| 3540 | fade_in: 0, |
| 3541 | fade_out: 0, |
| 3542 | transition_out: 0, |
| 3543 | start: timeline_frame, |
| 3544 | link: Some(self.new_link()), |
| 3545 | ..clip |
| 3546 | }; |
| 3547 | for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] { |
| 3548 | self.insert_over(half, clip); |
| 3549 | } |
| 3550 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 3551 | true |
| 3552 | } |
| 3553 | |
| 3554 | /// `clip` into `lane` at its own start, over whatever it lands on: the |
| 3555 | /// insert both placement doors make, which is what keeps a lane sorted and |
| 3556 | /// disjoint. The caller has checked that the lane is there. |
| 3557 | fn insert_over(&mut self, lane: Lane, clip: Clip) { |
| 3558 | let clips = self.lane_mut(lane).expect("the caller checked the lane"); |
| 3559 | clear(clips, clip.start, clip.end()); |
| 3560 | let idx = clips.partition_point(|c| c.start < clip.start); |
| 3561 | clips.insert(idx, clip); |
| 3562 | debug_assert!(sorted_disjoint(clips)); |
| 3563 | } |
| 3564 | |
| 3565 | /// Move the clip at `idx` of `from` onto `to` with its head at timeline |
| 3566 | /// frame `start`: the drag that rearranges takes, along a track and across |
| 3567 | /// them alike. One snapshot, so one [`Project::undo`] puts it back where it |
| 3568 | /// was. `start` at the clip's own is the pure lane change. |
| 3569 | /// |
| 3570 | /// The whole group travels the same distance, each half on the lane it |
| 3571 | /// already sits on -- a link means "these cover one span on however many |
| 3572 | /// lanes" ([`links_are_consistent`]), so a picture that slid away from its |
| 3573 | /// sound would be a group no save could load. Only the dragged half changes |
| 3574 | /// lane, and that is not a desync: a link names no lane at all. |
| 3575 | /// |
| 3576 | /// `start` is **clamped**, never refused, to the room the group has: no |
| 3577 | /// member crosses a neighbour on the lane it lands on, exactly as |
| 3578 | /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand |
| 3579 | /// dragging past a neighbour means "as far as it goes", and butting up |
| 3580 | /// against the take next door is how clips are laid end to end. The |
| 3581 | /// tightest member's wall wins, so a sound half boxed in between two others |
| 3582 | /// holds its picture still. |
| 3583 | /// |
| 3584 | /// Refused, changing nothing and costing no undo step, for a lane that is |
| 3585 | /// not there, an index that is not there, a move across *kinds* (a picture |
| 3586 | /// cannot play on an audio lane, and the save it wrote would not open |
| 3587 | /// again), a head let go *inside* another clip or into a gap too narrow to |
| 3588 | /// hold this one -- a move that overwrote what it landed on would destroy a |
| 3589 | /// take the pointer never named, which is what [`place`](Project::place) |
| 3590 | /// may do and a drag may not -- a half let go onto the lane its own partner |
| 3591 | /// is on, and a drop that changes neither lane nor frame, which is a clip |
| 3592 | /// picked up and put back down, i.e. a click. |
| 3593 | pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { |
| 3594 | self.move_selection(&[(from, idx)], from, idx, to, start) |
| 3595 | } |
| 3596 | |
| 3597 | /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks` |
| 3598 | /// (each with its own link group, exactly as [`group_of`](Self::group_of) |
| 3599 | /// reads it) travels the same distance as the clip at `idx` of `from`, |
| 3600 | /// which alone changes lane, onto `to`. One clamp across the whole set |
| 3601 | /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a |
| 3602 | /// neighbour that boxes in *any* member narrows the delta every member |
| 3603 | /// moves by, and a member with no room at all (`lo > hi`) refuses the |
| 3604 | /// whole set rather than moving the rest and leaving that one behind. |
| 3605 | /// `move_clip` is this with a selection of one -- the dragged clip's own |
| 3606 | /// group and nothing else -- so a drag on a clip outside the selection is |
| 3607 | /// byte-identical to before this existed. |
| 3608 | pub fn move_selection( |
| 3609 | &mut self, |
| 3610 | picks: &[(Lane, usize)], |
| 3611 | from: Lane, |
| 3612 | idx: usize, |
| 3613 | to: Lane, |
| 3614 | start: u32, |
| 3615 | ) -> bool { |
| 3616 | let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else { |
| 3617 | return false; |
| 3618 | }; |
| 3619 | if from.kind != to.kind { |
| 3620 | return false; |
| 3621 | } |
| 3622 | let held = self.index(from).expect("the clip was found on it"); |
| 3623 | // Every pick's own group, unioned: the whole selection moves as one, |
| 3624 | // and a pick's link partners (not themselves picked) come along with |
| 3625 | // it exactly as a lone drag's do. |
| 3626 | let mut members = Members::default(); |
| 3627 | for &(lane, i) in picks { |
| 3628 | let Some(group) = self.group_of(lane, i) else { |
| 3629 | continue; |
| 3630 | }; |
| 3631 | for m in group.clips { |
| 3632 | if !members.clips.contains(&m) { |
| 3633 | members.clips.push(m); |
| 3634 | } |
| 3635 | } |
| 3636 | for m in group.subs { |
| 3637 | if !members.subs.contains(&m) { |
| 3638 | members.subs.push(m); |
| 3639 | } |
| 3640 | } |
| 3641 | } |
| 3642 | if !members.clips.contains(&(held, idx)) { |
| 3643 | members.clips.push((held, idx)); |
| 3644 | } |
| 3645 | // The two halves of *the dragged clip's own* group would land on one |
| 3646 | // span of one lane, which is the one thing a link may never mean -- |
| 3647 | // checked against that group alone, not the whole moving set: an |
| 3648 | // unlinked fellow pick already sitting on `dest` is no conflict at |
| 3649 | // all, since it travels by the same delta and `move_room` below |
| 3650 | // leaves it the room to. Refused rather than clamped: the partner |
| 3651 | // moves the same distance, so there is no room for it anywhere on |
| 3652 | // that lane. |
| 3653 | let own_group = self.group_of(from, idx).expect("the clip was found"); |
| 3654 | if dest != held |
| 3655 | && own_group |
| 3656 | .clips |
| 3657 | .iter() |
| 3658 | .chain(&own_group.subs) |
| 3659 | .any(|&(l, _)| l == dest) |
| 3660 | { |
| 3661 | return false; |
| 3662 | } |
| 3663 | let want = i64::from(start) - i64::from(clip.start); |
| 3664 | // How far the group may travel, in timeline frames and signed: every |
| 3665 | // member -- the clips and any caption grouped with them -- narrows it |
| 3666 | // to the gap it is landing in, and what is left is what the pointer is |
| 3667 | // clamped to. |
| 3668 | let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else { |
| 3669 | return false; |
| 3670 | }; |
| 3671 | if lo > hi { |
| 3672 | return false; |
| 3673 | } |
| 3674 | let delta = want.clamp(lo, hi); |
| 3675 | if delta == 0 && dest == held { |
| 3676 | return false; |
| 3677 | } |
| 3678 | self.snapshot(); |
| 3679 | for &(l, i) in &members.clips { |
| 3680 | let c = &mut self.lanes[l].clips[i]; |
| 3681 | // In range by the walls above, which are `u32` frames throughout. |
| 3682 | c.start = (i64::from(c.start) + delta) as u32; |
| 3683 | } |
| 3684 | for &(l, i) in &members.subs { |
| 3685 | let s = &mut self.lanes[l].subs[i]; |
| 3686 | s.start = (i64::from(s.start) + delta) as u32; |
| 3687 | } |
| 3688 | if dest != held { |
| 3689 | let clip = self.lanes[held].clips.remove(idx); |
| 3690 | let clips = &mut self.lanes[dest].clips; |
| 3691 | let at = clips.partition_point(|c| c.start < clip.start); |
| 3692 | clips.insert(at, clip); |
| 3693 | } |
| 3694 | debug_assert!(sorted_disjoint(&self.lanes[dest].clips)); |
| 3695 | debug_assert!(members |
| 3696 | .clips |
| 3697 | .iter() |
| 3698 | .chain(&members.subs) |
| 3699 | .all(|&(l, _)| { |
| 3700 | sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs) |
| 3701 | })); |
| 3702 | true |
| 3703 | } |
| 3704 | |
| 3705 | /// How far a group drag may travel, `(least, most)` in timeline frames and |
| 3706 | /// signed: every member narrows the range to the gap it is landing in -- |
| 3707 | /// the clips against their lanes' clips and the captions against their |
| 3708 | /// lanes' captions -- and what is left is what the pointer is clamped to. |
| 3709 | /// `travelling` names the one member that changes lane, if any: the clip a |
| 3710 | /// hand is carrying onto another track, whose walls are read on the lane it |
| 3711 | /// is let go over at the frame the pointer named. `None` when a member has |
| 3712 | /// no gap to land in at all. |
| 3713 | fn move_room( |
| 3714 | &self, |
| 3715 | members: &Members, |
| 3716 | travelling: Option<(usize, usize, usize, u32)>, |
| 3717 | ) -> Option<(i64, i64)> { |
| 3718 | let (mut lo, mut hi) = (i64::MIN, i64::MAX); |
| 3719 | for &(l, i) in members.clips.iter().chain(&members.subs) { |
| 3720 | let sub = members.subs.contains(&(l, i)); |
| 3721 | let (start, frames) = match self.lanes[l] |
| 3722 | .clips |
| 3723 | .get(i) |
| 3724 | .filter(|_| !sub) |
| 3725 | .map(|c| (c.start, c.frames())) |
| 3726 | { |
| 3727 | Some(pair) => pair, |
| 3728 | None => { |
| 3729 | let s = self.lanes[l].subs.get(i)?; |
| 3730 | (s.start, s.frames) |
| 3731 | } |
| 3732 | }; |
| 3733 | let land = travelling |
| 3734 | .filter(|&(fl, fi, ..)| (fl, fi) == (l, i)) |
| 3735 | .map_or(l, |(_, _, dest, _)| dest); |
| 3736 | // Which gap this member's walls are read off: its own place on the |
| 3737 | // lane it stays on, and the frame the pointer named on the lane it |
| 3738 | // is let go over. A clip's neighbours are the clips of the lane it |
| 3739 | // lands on and a caption's are its captions -- the two lists of one |
| 3740 | // lane never meet. |
| 3741 | let at = match travelling { |
| 3742 | Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked, |
| 3743 | _ => start, |
| 3744 | }; |
| 3745 | let (mut wall_lo, mut wall_hi) = (0, u32::MAX); |
| 3746 | let neighbours: Vec<(u32, u32)> = if sub { |
| 3747 | self.lanes[land] |
| 3748 | .subs |
| 3749 | .iter() |
| 3750 | .map(|s| (s.start, s.end())) |
| 3751 | .collect() |
| 3752 | } else { |
| 3753 | self.lanes[land] |
| 3754 | .clips |
| 3755 | .iter() |
| 3756 | .map(|c| (c.start, c.end())) |
| 3757 | .collect() |
| 3758 | }; |
| 3759 | for (j, (other_start, other_end)) in neighbours.iter().enumerate() { |
| 3760 | if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) { |
| 3761 | continue; |
| 3762 | } |
| 3763 | if *other_start <= at && at < *other_end { |
| 3764 | // A head let go inside another placement, which a clamp |
| 3765 | // has no answer for: the drop is refused. |
| 3766 | return None; |
| 3767 | } |
| 3768 | match other_end <= &at { |
| 3769 | true => wall_lo = wall_lo.max(*other_end), |
| 3770 | false => wall_hi = wall_hi.min(*other_start), |
| 3771 | } |
| 3772 | } |
| 3773 | if wall_hi - wall_lo < frames { |
| 3774 | return None; |
| 3775 | } |
| 3776 | lo = lo.max(i64::from(wall_lo) - i64::from(start)); |
| 3777 | hi = hi.min(i64::from(wall_hi - frames) - i64::from(start)); |
| 3778 | } |
| 3779 | Some((lo, hi)) |
| 3780 | } |
| 3781 | |
| 3782 | /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` -- |
| 3783 | /// the drag on a clip's end that makes it play more or less of its source. |
| 3784 | /// The rest of the lane stays exactly where it is (nothing ripples), so what |
| 3785 | /// a shortened clip leaves behind is a gap and what a lengthened one takes |
| 3786 | /// is room that was already empty. One snapshot, so a whole drag is one |
| 3787 | /// [`Project::undo`] -- commit once, at the release, rather than per pointer |
| 3788 | /// sample. Changes the timeline->source mapping: the caller must reseek. |
| 3789 | /// |
| 3790 | /// [`Edge::Start`] moves the in-point with it: the frames that stay play |
| 3791 | /// exactly what they played before, which is what makes this a trim and not |
| 3792 | /// a slip. |
| 3793 | /// |
| 3794 | /// `to` is **clamped**, never refused -- a hand pulling an edge past what is |
| 3795 | /// legal means "as far as it goes", and stopping the box there is the |
| 3796 | /// affordance. The walls are: one frame of clip always survives, an edge |
| 3797 | /// never crosses the neighbouring clip on its own lane, an in-point never |
| 3798 | /// walks back past the source's first frame, and an out-point never runs |
| 3799 | /// past `source_frames[clip.source]` -- the caller's table of how long each |
| 3800 | /// source actually is ([`Project`] does not know, and a clip ending past its |
| 3801 | /// file's last frame is a save that will not open again; see |
| 3802 | /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry |
| 3803 | /// there may not grow at all. |
| 3804 | /// |
| 3805 | /// Linked placements trim *together*, by one delta: every member's same |
| 3806 | /// edge moves the distance the dragged one did, clamped to the room its |
| 3807 | /// own walls leave -- offsets between the members of a hand-built group |
| 3808 | /// survive the trim, exactly as they survive a drag. |
| 3809 | /// |
| 3810 | /// `false`, changing nothing and costing no undo step, for an index that is |
| 3811 | /// not there and for an edge that is already where it was asked to go. |
| 3812 | pub fn trim( |
| 3813 | &mut self, |
| 3814 | lane: Lane, |
| 3815 | idx: usize, |
| 3816 | edge: Edge, |
| 3817 | to: u32, |
| 3818 | source_frames: &[u32], |
| 3819 | ) -> bool { |
| 3820 | let (Some((lo, hi)), Some(clip)) = ( |
| 3821 | self.trim_room(lane, idx, edge, source_frames), |
| 3822 | self.lane(lane).get(idx).copied(), |
| 3823 | ) else { |
| 3824 | return false; |
| 3825 | }; |
| 3826 | let to = to.clamp(lo, hi); |
| 3827 | let at = match edge { |
| 3828 | Edge::Start => clip.start, |
| 3829 | Edge::End => clip.end(), |
| 3830 | }; |
| 3831 | if to == at { |
| 3832 | return false; |
| 3833 | } |
| 3834 | // Worked out before anything moves: at a slow rate a room can be too |
| 3835 | // narrow to hold even one source frame ([`Speed::fit`]), and the |
| 3836 | // dragged clip refusing to fit must refuse the whole gesture rather |
| 3837 | // than be given a range wider than its room -- which is the overlap |
| 3838 | // the lane invariant exists to forbid. The walls below leave that room, |
| 3839 | // so this is the backstop for a project that came in through another |
| 3840 | // door. |
| 3841 | let room = match edge { |
| 3842 | // The frames that stay play what they played, so what survives is |
| 3843 | // measured from the *end*. |
| 3844 | Edge::Start => clip.end() - to, |
| 3845 | Edge::End => to - clip.start, |
| 3846 | }; |
| 3847 | let Some(keep) = clip.speed.fit(room) else { |
| 3848 | return false; |
| 3849 | }; |
| 3850 | let members = self.group_of(lane, idx).expect("checked above"); |
| 3851 | self.snapshot(); |
| 3852 | let still = self.is_still(&clip); |
| 3853 | let held = self.index(lane).expect("checked above"); |
| 3854 | let c = &mut self.lanes[held].clips[idx]; |
| 3855 | match edge { |
| 3856 | // A still has no earlier frame to walk an in-point back to -- |
| 3857 | // every frame of it is the same picture -- so its head grows |
| 3858 | // *forward*: the range it plays is however long the new room is, |
| 3859 | // anchored at the source's frame 0. Bounded by `lo`, which is where |
| 3860 | // the cap in `source_frames` is applied. |
| 3861 | Edge::Start if still => { |
| 3862 | c.in_frame = 0; |
| 3863 | c.out_frame = keep; |
| 3864 | c.start = to; |
| 3865 | } |
| 3866 | Edge::Start => { |
| 3867 | // Non-negative by `lo`, which is what keeps the in-point on the |
| 3868 | // source. |
| 3869 | c.in_frame = c.out_frame - keep.min(c.out_frame); |
| 3870 | c.start = to; |
| 3871 | } |
| 3872 | // Never wider than the room the edge was clamped to: see |
| 3873 | // [`Speed::fit`]. |
| 3874 | Edge::End => c.out_frame = c.in_frame + keep, |
| 3875 | } |
| 3876 | debug_assert!(sorted_disjoint(&self.lanes[held].clips)); |
| 3877 | self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames); |
| 3878 | true |
| 3879 | } |
| 3880 | |
| 3881 | /// The rest of a group after one member's `edge` has moved by `delta`: |
| 3882 | /// every other member's same edge moves the same distance, clamped to the |
| 3883 | /// room its own walls leave -- a clip's against its lane and its source, |
| 3884 | /// a caption's against its own lane, its window following by the |
| 3885 | /// placement's own proportion. The undo step is the caller's: this is the |
| 3886 | // second half of one edit, not an edit of its own. |
| 3887 | fn follow_group( |
| 3888 | &mut self, |
| 3889 | members: &Members, |
| 3890 | dragged: &(usize, usize), |
| 3891 | edge: Edge, |
| 3892 | delta: i64, |
| 3893 | source_frames: &[u32], |
| 3894 | ) { |
| 3895 | for &(l, i) in &members.clips { |
| 3896 | if (l, i) == *dragged { |
| 3897 | continue; |
| 3898 | } |
| 3899 | let c = self.lanes[l].clips[i]; |
| 3900 | let at = match edge { |
| 3901 | Edge::Start => c.start, |
| 3902 | Edge::End => c.end(), |
| 3903 | }; |
| 3904 | let (lo, hi) = self.clip_room(l, i, edge, source_frames); |
| 3905 | let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32; |
| 3906 | if to == at { |
| 3907 | continue; |
| 3908 | } |
| 3909 | let room = match edge { |
| 3910 | Edge::Start => c.end() - to, |
| 3911 | Edge::End => to - c.start, |
| 3912 | }; |
| 3913 | let Some(keep) = c.speed.fit(room) else { |
| 3914 | continue; |
| 3915 | }; |
| 3916 | let still = self.is_still(&self.lanes[l].clips[i]); |
| 3917 | let c = &mut self.lanes[l].clips[i]; |
| 3918 | match edge { |
| 3919 | Edge::Start if still => { |
| 3920 | c.in_frame = 0; |
| 3921 | c.out_frame = keep; |
| 3922 | c.start = to; |
| 3923 | } |
| 3924 | Edge::Start => { |
| 3925 | c.in_frame = c.out_frame - keep.min(c.out_frame); |
| 3926 | c.start = to; |
| 3927 | } |
| 3928 | Edge::End => c.out_frame = c.in_frame + keep, |
| 3929 | } |
| 3930 | debug_assert!(sorted_disjoint(&self.lanes[l].clips)); |
| 3931 | } |
| 3932 | for &(l, i) in &members.subs { |
| 3933 | if (l, i) == *dragged { |
| 3934 | continue; |
| 3935 | } |
| 3936 | let s = self.lanes[l].subs[i]; |
| 3937 | let at = match edge { |
| 3938 | Edge::Start => s.start, |
| 3939 | Edge::End => s.end(), |
| 3940 | }; |
| 3941 | let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge); |
| 3942 | let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32; |
| 3943 | if to == at { |
| 3944 | continue; |
| 3945 | } |
| 3946 | write_sub_edge(&mut self.lanes[l].subs[i], edge, to); |
| 3947 | debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs)); |
| 3948 | } |
| 3949 | } |
| 3950 | |
| 3951 | /// How far that edge may travel, `(first, last)` timeline frame inclusive -- |
| 3952 | /// the walls [`trim`](Project::trim) clamps to, without moving anything. |
| 3953 | /// What a front-end drawing the box *during* a drag asks, so the live width |
| 3954 | /// is the width the release will commit and an edge stops under the pointer |
| 3955 | /// rather than snapping back. The **clip's own** walls: the rest of its |
| 3956 | /// group follows by the same delta within their own ([`follow_group`]), so |
| 3957 | /// what is drawn for the dragged edge is what its own clip will commit. |
| 3958 | /// `None` for an index that is not there. |
| 3959 | pub fn trim_room( |
| 3960 | &self, |
| 3961 | lane: Lane, |
| 3962 | idx: usize, |
| 3963 | edge: Edge, |
| 3964 | source_frames: &[u32], |
| 3965 | ) -> Option<(u32, u32)> { |
| 3966 | let l = self.index(lane)?; |
| 3967 | (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames)) |
| 3968 | } |
| 3969 | |
| 3970 | /// [`trim_room`](Project::trim_room) for a clip the caller already holds by |
| 3971 | /// its lane's storage index: the one wall computation, asked for the clip |
| 3972 | /// itself and for each member a group trim carries. |
| 3973 | fn clip_room( |
| 3974 | &self, |
| 3975 | l: usize, |
| 3976 | i: usize, |
| 3977 | edge: Edge, |
| 3978 | source_frames: &[u32], |
| 3979 | ) -> (u32, u32) { |
| 3980 | let clips = &self.lanes[l].clips; |
| 3981 | let c = clips[i]; |
| 3982 | let (lo, hi) = match edge { |
| 3983 | Edge::Start => ( |
| 3984 | // Back to the source's own first frame -- as many *timeline* |
| 3985 | // frames as that head is worth at the clip's rate, which at |
| 3986 | // real time is the head itself -- and never over the clip in |
| 3987 | // front of it. Saturating because a clip may hold *more* |
| 3988 | // head than the timeline has room for -- a ripple delete |
| 3989 | // slides a clip back to frame 0 with its in-point wherever |
| 3990 | // the cut left it -- and frame 0 is the other wall. |
| 3991 | // |
| 3992 | // A still is measured from its *tail* instead: it has no |
| 3993 | // in-point worth the name (every frame the same picture), so |
| 3994 | // its head reaches exactly as far as its tail does -- out to |
| 3995 | // the length the caller's table gives it, whole. Measured |
| 3996 | // from the in-point it would have no head room at all, which |
| 3997 | // is a placed picture whose left edge cannot be dragged out. |
| 3998 | // No entry in the table means no growth, as it does at the |
| 3999 | // other end. |
| 4000 | if self.is_still(&c) { |
| 4001 | c.end().saturating_sub( |
| 4002 | c.speed |
| 4003 | .room(source_frames.get(c.source).copied().unwrap_or(c.len())), |
| 4004 | ) |
| 4005 | } else { |
| 4006 | c.start.saturating_sub(c.speed.room(c.in_frame)) |
| 4007 | } |
| 4008 | .max(i.checked_sub(1).map_or(0, |p| clips[p].end())), |
| 4009 | // One *frame of clip* always survives, and at a rate below |
| 4010 | // real time one frame of clip is several frames of timeline |
| 4011 | // ([`Speed::room`]): an edge dragged closer than that would |
| 4012 | // ask for a range no source frame fits in. At real time this |
| 4013 | // is `end - 1`, unchanged. |
| 4014 | c.end() - c.speed.room(1), |
| 4015 | ), |
| 4016 | Edge::End => ( |
| 4017 | // ...and the same wall from the other end: the shortest this |
| 4018 | // clip can be is the room one source frame of it takes. |
| 4019 | c.start + c.speed.room(1), |
| 4020 | // Out to whatever is left of the source -- again in timeline |
| 4021 | // frames, at this clip's rate -- and never over the clip |
| 4022 | // behind it. |
| 4023 | c.start |
| 4024 | .saturating_add( |
| 4025 | c.speed.room( |
| 4026 | source_frames |
| 4027 | .get(c.source) |
| 4028 | .copied() |
| 4029 | .unwrap_or(c.out_frame) |
| 4030 | .saturating_sub(c.in_frame), |
| 4031 | ), |
| 4032 | ) |
| 4033 | .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)), |
| 4034 | ), |
| 4035 | }; |
| 4036 | // `hi.max(lo)`: for a clip the invariants hold for, the range always |
| 4037 | // contains the edge's own place, and a caller's wrong `source_frames` |
| 4038 | // must not become an empty range (or a panicking `clamp`) here. |
| 4039 | (lo, hi.max(lo)) |
| 4040 | } |
| 4041 | |
| 4042 | /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose |
| 4043 | /// every frame is the same picture, so which frame of it a clip's in-point |
| 4044 | /// names is not a question -- what [`Project::trim`] lets grow at either |
| 4045 | /// end. `false` for a source that is not there. |
| 4046 | fn is_still(&self, clip: &Clip) -> bool { |
| 4047 | self.sources |
| 4048 | .get(clip.source) |
| 4049 | .is_some_and(|s| crate::is_image(&s.path)) |
| 4050 | } |
| 4051 | |
| 4052 | /// The placements that move as one with the one at `idx` of `lane` -- |
| 4053 | /// itself and whatever carries its link, on the media lanes and the |
| 4054 | /// subtitle ones alike. `None` for an index that is not there. |
| 4055 | fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> { |
| 4056 | let sub = lane.kind == LaneKind::Subtitle; |
| 4057 | let link = if sub { |
| 4058 | self.sub_lane(lane).get(idx)?.link |
| 4059 | } else { |
| 4060 | self.lane(lane).get(idx)?.link |
| 4061 | }; |
| 4062 | let mut members = Members::default(); |
| 4063 | match link { |
| 4064 | Some(link) => { |
| 4065 | for (l, data) in self.lanes.iter().enumerate() { |
| 4066 | if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) { |
| 4067 | members.clips.push((l, i)); |
| 4068 | } |
| 4069 | if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) { |
| 4070 | members.subs.push((l, i)); |
| 4071 | } |
| 4072 | } |
| 4073 | } |
| 4074 | None => { |
| 4075 | let l = self.index(lane).expect("the placement was found on it"); |
| 4076 | if sub { |
| 4077 | members.subs.push((l, idx)); |
| 4078 | } else { |
| 4079 | members.clips.push((l, idx)); |
| 4080 | } |
| 4081 | } |
| 4082 | } |
| 4083 | Some(members) |
| 4084 | } |
| 4085 | |
| 4086 | /// Insert `clip` into the first lane of each kind at `timeline_frame` as one |
| 4087 | /// new group, pushing everything from there on later by its length in |
| 4088 | /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip |
| 4089 | /// the clip it lands in is split around it; past the end of the timeline it |
| 4090 | /// goes down where it was asked for, with black in front of it -- which is |
| 4091 | /// what a library row let go on the open bed means, and what the ghost under |
| 4092 | /// the pointer promised. A clipboard means "put it here", not "here and |
| 4093 | /// black in front", and clamps to the end at its own door |
| 4094 | /// ([`crate::PlaybackSession::paste_at`]). |
| 4095 | /// Use [`place`](Project::place) to paste into one lane, or to make a gap. |
| 4096 | /// |
| 4097 | /// `V1` and `A1` and no other lane, because a take is one picture and one |
| 4098 | /// sound: copying it onto every lane there is would play the same audio |
| 4099 | /// twice over (and leave an mp4 export with two tracks to copy). A clip of a |
| 4100 | /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a |
| 4101 | /// video lane it is a clip that decodes to nothing, and a save carrying one |
| 4102 | /// does not open again -- and a still image ([`crate::is_image`]) reaches |
| 4103 | /// `V1` only, for the mirror of that reason. The room is still opened on |
| 4104 | /// every media lane, or the lanes it was not inserted into would slide out |
| 4105 | /// of step with the ones it was -- and the subtitle lanes are left alone: |
| 4106 | /// the words keep their own clock, and a caption that should travel with a |
| 4107 | /// clip is what a group is for. |
| 4108 | /// |
| 4109 | /// Exactly one history snapshot, so one [`Project::undo`] takes it back. |
| 4110 | /// Changes the timeline->source mapping: the caller must reseek. Refused for |
| 4111 | /// an empty `clip` and for one naming a source that is not there (both of |
| 4112 | /// which the public fields let a caller build), and for a paste whose ripple |
| 4113 | /// would push a clip past the last frame there is -- nothing is changed by |
| 4114 | /// any of them. |
| 4115 | pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool { |
| 4116 | let Some(source) = self.sources.get(clip.source) else { |
| 4117 | return false; |
| 4118 | }; |
| 4119 | if clip.out_frame <= clip.in_frame { |
| 4120 | return false; |
| 4121 | } |
| 4122 | let audio_only = crate::is_audio(&source.path); |
| 4123 | // ...and its mirror: a still is a picture and no sound, so a copy of one |
| 4124 | // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio |
| 4125 | // worker tries to demux -- which silences the *whole session*, not just |
| 4126 | // that clip -- and a save the engine's own `open_project` then refuses. |
| 4127 | let picture_only = crate::is_image(&source.path); |
| 4128 | // The frame it was asked for and no other: a row let go on the empty |
| 4129 | // bed past the last clip lands *there*, under the ghost that promised |
| 4130 | // it, with black in front. Clamping to the end here made every drop on |
| 4131 | // open bed an append -- the clipboard's rule, applied to a hand that |
| 4132 | // had named a place. |
| 4133 | let at = timeline_frame; |
| 4134 | // The room it takes on the timeline, which its speed decides -- not the |
| 4135 | // source range it reads. |
| 4136 | let len = clip.frames(); |
| 4137 | // Room for it: `open_room` adds `len` to every start from `at` on, and a |
| 4138 | // hand-written file may hold a clip that ends at the very last frame |
| 4139 | // (`edith::check` permits `start + len == u32::MAX`). Refused here |
| 4140 | // rather than wrapped there -- a wrapped start lands *behind* the clip |
| 4141 | // it belongs after, which is an overlap no save will read back. |
| 4142 | if at.checked_add(len).is_none() |
| 4143 | || self |
| 4144 | .lanes |
| 4145 | .iter() |
| 4146 | .flat_map(|l| &l.clips) |
| 4147 | .any(|c| c.end() > at && c.end().checked_add(len).is_none()) |
| 4148 | { |
| 4149 | return false; |
| 4150 | } |
| 4151 | // ...and room *to open*: the paste splits whatever it lands inside of, |
| 4152 | // and a speeded clip can only be cut where its own rate has a source |
| 4153 | // frame ([`Speed::split_at`]). Refused rather than pasted over the top |
| 4154 | // of one, which is the overlap a lane may never hold. At real time every |
| 4155 | // frame answers, so this cannot refuse an unspeeded paste. |
| 4156 | let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end()); |
| 4157 | if self |
| 4158 | .lanes |
| 4159 | .iter() |
| 4160 | .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none()) |
| 4161 | { |
| 4162 | return false; |
| 4163 | } |
| 4164 | self.snapshot(); |
| 4165 | let clip = Clip { |
| 4166 | fade_in: 0, |
| 4167 | fade_out: 0, |
| 4168 | transition_out: 0, |
| 4169 | start: at, |
| 4170 | link: Some(self.new_link()), |
| 4171 | ..clip |
| 4172 | }; |
| 4173 | // Only lanes that can play the source: a file with no picture belongs on |
| 4174 | // an audio lane and nowhere else, exactly as `place_stream_at` decides |
| 4175 | // it for an import. On a video lane it would decode to nothing, and the |
| 4176 | // save it wrote would not open again. |
| 4177 | let kinds: &[LaneKind] = match (audio_only, picture_only) { |
| 4178 | (true, _) => &[LaneKind::Audio], |
| 4179 | (_, true) => &[LaneKind::Video], |
| 4180 | _ => &[LaneKind::Video, LaneKind::Audio], |
| 4181 | }; |
| 4182 | let takes: Vec<usize> = kinds |
| 4183 | .iter() |
| 4184 | .filter_map(|&kind| self.index(Lane::new(kind, 0))) |
| 4185 | .collect(); |
| 4186 | for (i, data) in self.lanes.iter_mut().enumerate() { |
| 4187 | open_room(&mut data.clips, at, len); |
| 4188 | // The subtitle lanes are NOT touched: a paste inserts media, and |
| 4189 | // the words keep their own clock. Opening room here used to split |
| 4190 | // a caption the paste landed inside and slide the rest behind it |
| 4191 | // -- "a caption that stayed put while the picture moved on no |
| 4192 | // longer says the same thing" -- but a caption pinned to nothing |
| 4193 | // (and a video arriving on a timeline of words alone) has no |
| 4194 | // picture to follow, and the split did to the words what no hand |
| 4195 | // asked for. A caption that should travel with a clip is what a |
| 4196 | // group is for, and a group moves as one. |
| 4197 | if takes.contains(&i) { |
| 4198 | let idx = data.clips.partition_point(|c| c.start < at); |
| 4199 | data.clips.insert(idx, clip); |
| 4200 | } |
| 4201 | debug_assert!(sorted_disjoint(&data.clips)); |
| 4202 | debug_assert!(subs_sorted_disjoint(&data.subs)); |
| 4203 | } |
| 4204 | true |
| 4205 | } |
| 4206 | |
| 4207 | /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or |
| 4208 | /// silence, and nothing else moves. Refused only for an out-of-range index |
| 4209 | /// (which a lane that is not there always is) -- lifting the last placement |
| 4210 | /// there is leaves an *empty* timeline, which is a state the project holds |
| 4211 | /// like any other and an undo brings back. |
| 4212 | pub fn lift(&mut self, lane: Lane, idx: usize) -> bool { |
| 4213 | if idx >= self.lane(lane).len() { |
| 4214 | return false; |
| 4215 | } |
| 4216 | self.snapshot(); |
| 4217 | self.lane_mut(lane).expect("checked above").remove(idx); |
| 4218 | true |
| 4219 | } |
| 4220 | |
| 4221 | /// Cut the timeline frames `[at, at + len)` out of *every* lane and close |
| 4222 | /// the hole: everything after slides back by `len`. The rippling delete -- |
| 4223 | /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an |
| 4224 | /// empty range; a delete that leaves nothing behind empties the timeline, |
| 4225 | /// which is a state like any other and one undo away. |
| 4226 | pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool { |
| 4227 | if len == 0 { |
| 4228 | return false; |
| 4229 | } |
| 4230 | // Nothing reaches past `at`: there is nothing to cut and nothing to |
| 4231 | // slide back, and a delete that changes nothing must not cost an undo |
| 4232 | // step (see [`snapshot`](Project::snapshot)). |
| 4233 | if !self |
| 4234 | .lanes |
| 4235 | .iter() |
| 4236 | .flat_map(|l| &l.clips) |
| 4237 | .any(|c| c.end() > at) |
| 4238 | { |
| 4239 | return false; |
| 4240 | } |
| 4241 | self.snapshot(); |
| 4242 | let on = all_lanes(&self.lanes); |
| 4243 | ripple(&mut self.lanes, &on, at, len); |
| 4244 | true |
| 4245 | } |
| 4246 | |
| 4247 | /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what |
| 4248 | /// a right-click on empty bench space names before offering to close it. |
| 4249 | /// `None` when `frame` sits inside a placement, or past the last one: the |
| 4250 | /// open end of a lane is not a gap, since there is nothing after it to slide |
| 4251 | /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not |
| 4252 | /// the media [`Clip`] list they deliberately never hold. |
| 4253 | pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> { |
| 4254 | let data = self.index(lane).map(|i| &self.lanes[i])?; |
| 4255 | match data.kind { |
| 4256 | LaneKind::Subtitle => gap(&data.subs, frame), |
| 4257 | LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame), |
| 4258 | } |
| 4259 | } |
| 4260 | |
| 4261 | /// How many bounded holes `lane` holds. The open end after the last |
| 4262 | /// placement is not counted, like [`gap_at`](Self::gap_at), because closing |
| 4263 | /// it would move nothing. |
| 4264 | pub fn gap_count(&self, lane: Lane) -> usize { |
| 4265 | let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else { |
| 4266 | return 0; |
| 4267 | }; |
| 4268 | match data.kind { |
| 4269 | LaneKind::Subtitle => gaps(&data.subs).len(), |
| 4270 | LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(), |
| 4271 | } |
| 4272 | } |
| 4273 | |
| 4274 | /// The lanes closing the gap `(start, frames)` on `lane` must ripple |
| 4275 | /// together to keep sync -- what a right-click on empty bench space asks |
| 4276 | /// before the menu offers to close it, and what widens |
| 4277 | /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand |
| 4278 | /// named to the whole take the gap might be half of. |
| 4279 | /// |
| 4280 | /// A clip bordering the gap on `lane` -- the one ending where it starts, |
| 4281 | /// the one starting where it ends -- carries a link when it is one take |
| 4282 | /// with a clip on another lane. That lane joins the scope only when the |
| 4283 | /// *exact same* stretch is empty there too (same start, same length): the |
| 4284 | /// ripple then removes nothing but silence, on every lane it touches, and |
| 4285 | /// both halves stay the length they always were. A link whose partner |
| 4286 | /// lane is not empty there -- a gap of a different length, or none at all |
| 4287 | /// -- is named back to the caller rather than silently widened past |
| 4288 | /// (which would cut real media out of a lane nothing asked to touch) or |
| 4289 | /// silently left out (which is the defect this closes: a per-lane ripple |
| 4290 | /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole) |
| 4291 | /// to refuse it after the fact, on the very half this could have carried |
| 4292 | /// along). |
| 4293 | /// |
| 4294 | /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose |
| 4295 | /// partner clip sits on another lane -- the unlinked case, untouched. |
| 4296 | /// |
| 4297 | /// Subtitle lanes have no media take halves to inspect. A caption can be |
| 4298 | /// hand-grouped with clips, but it is not the imported A/V take this method |
| 4299 | /// widens for, so a subtitle gap stays scoped to its own lane; the later |
| 4300 | /// scoped cut still refuses an explicit group split. |
| 4301 | pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> { |
| 4302 | let Some(li) = self.index(lane) else { |
| 4303 | return Err("no track to work on".into()); |
| 4304 | }; |
| 4305 | let labels = handles(&self.lanes); |
| 4306 | let end = start + frames; |
| 4307 | let mut scope = vec![lane]; |
| 4308 | for c in self.lanes[li] |
| 4309 | .clips |
| 4310 | .iter() |
| 4311 | .filter(|c| c.end() == start || c.start == end) |
| 4312 | { |
| 4313 | let Some(id) = c.link else { continue }; |
| 4314 | for (j, data) in self.lanes.iter().enumerate() { |
| 4315 | if j == li { |
| 4316 | continue; |
| 4317 | } |
| 4318 | let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) else { |
| 4319 | continue; |
| 4320 | }; |
| 4321 | match gap(&data.clips, start) { |
| 4322 | Some((s, f)) if s == start && f == frames => { |
| 4323 | let other = labels[j]; |
| 4324 | if !scope.contains(&other) { |
| 4325 | scope.push(other); |
| 4326 | } |
| 4327 | } |
| 4328 | _ => { |
| 4329 | return Err(format!( |
| 4330 | "the {} clip at frame {} is one take with the {} clip at frame {}: \ |
| 4331 | closing this gap alone would pull the take out of sync -- close {}'s \ |
| 4332 | gap there too, or detach them first", |
| 4333 | labels[li].label(), |
| 4334 | c.start, |
| 4335 | labels[j].label(), |
| 4336 | half.start, |
| 4337 | labels[j].label() |
| 4338 | ) |
| 4339 | .into()); |
| 4340 | } |
| 4341 | } |
| 4342 | } |
| 4343 | } |
| 4344 | Ok(scope) |
| 4345 | } |
| 4346 | |
| 4347 | /// Close every bounded gap on `lane`, as one undo step, without making the |
| 4348 | /// lane's scope global. Media lanes use the same take-safety widening |
| 4349 | /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked |
| 4350 | /// halves ride along only when their matching lane is empty over that exact |
| 4351 | /// stretch; mismatches are skipped and reported. Subtitle lanes close their |
| 4352 | /// own [`SubClip`] list only: captions may be hand-grouped, but they are not |
| 4353 | /// halves of an imported A/V take, so the media take-widening rule has |
| 4354 | /// nothing to add there. |
| 4355 | /// |
| 4356 | /// The walk is back-to-front. Closing a gap shifts everything after it, so |
| 4357 | /// later holes must be consumed while their measured starts are still true; |
| 4358 | /// earlier starts are unchanged by cuts to their right. A snapshot is taken |
| 4359 | /// only before the first successful close, so an all-skipped sweep is not an |
| 4360 | /// undo step. |
| 4361 | pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> { |
| 4362 | let Some(i) = self.index(lane) else { |
| 4363 | return Err("no track to work on".into()); |
| 4364 | }; |
| 4365 | if self.lanes[i].kind == LaneKind::Subtitle { |
| 4366 | return Ok(self.close_all_subtitle_gaps_on_lane(i)); |
| 4367 | } |
| 4368 | let mut report = GapSweep::default(); |
| 4369 | let mut snapshot = false; |
| 4370 | for (start, frames) in gaps(self.lane(lane)).into_iter().rev() { |
| 4371 | match self |
| 4372 | .gap_take_scope(lane, start, frames) |
| 4373 | .and_then(|scope| { |
| 4374 | let on = self.scoped(&scope)?; |
| 4375 | self.scope_holds_takes_whole(&on, start)?; |
| 4376 | Ok(on) |
| 4377 | }) { |
| 4378 | Ok(on) => { |
| 4379 | if !snapshot { |
| 4380 | self.snapshot(); |
| 4381 | snapshot = true; |
| 4382 | } |
| 4383 | ripple(&mut self.lanes, &on, start, frames); |
| 4384 | report.closed += 1; |
| 4385 | } |
| 4386 | Err(e) => report.skipped.push(GapSkip { |
| 4387 | start, |
| 4388 | reason: e.to_string(), |
| 4389 | }), |
| 4390 | } |
| 4391 | } |
| 4392 | report.skipped.reverse(); |
| 4393 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 4394 | Ok(report) |
| 4395 | } |
| 4396 | |
| 4397 | /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no |
| 4398 | /// take-scope widening: a caption is not one half of an A/V take. Explicit |
| 4399 | /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole), |
| 4400 | /// so a grouped caption is refused rather than pulled away from its group. |
| 4401 | fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep { |
| 4402 | let mut report = GapSweep::default(); |
| 4403 | let mut snapshot = false; |
| 4404 | let on = [i]; |
| 4405 | for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() { |
| 4406 | match self.scope_holds_takes_whole(&on, start) { |
| 4407 | Ok(()) => { |
| 4408 | if !snapshot { |
| 4409 | self.snapshot(); |
| 4410 | snapshot = true; |
| 4411 | } |
| 4412 | ripple(&mut self.lanes, &on, start, frames); |
| 4413 | report.closed += 1; |
| 4414 | } |
| 4415 | Err(e) => report.skipped.push(GapSkip { |
| 4416 | start, |
| 4417 | reason: e.to_string(), |
| 4418 | }), |
| 4419 | } |
| 4420 | } |
| 4421 | report.skipped.reverse(); |
| 4422 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 4423 | report |
| 4424 | } |
| 4425 | |
| 4426 | /// Cut **every** one of `regions` -- `(start, len)` in timeline frames -- |
| 4427 | /// out of the lanes in `scope` and close each hole, as one edit: the |
| 4428 | /// jumpcut a silence scan asks for ([`crate::silence`]). |
| 4429 | /// |
| 4430 | /// A lane that is not in `scope` **does not move**, which is the whole |
| 4431 | /// point of the parameter: the silences of a podcast track come out |
| 4432 | /// without the music track under it sliding. `scope` is an arbitrary set of |
| 4433 | /// lanes and not a kind or a range, so a caller with its own idea of what |
| 4434 | /// is selected (a take, a track, everything) says it in lanes and nothing |
| 4435 | /// here has to learn about selection. |
| 4436 | /// |
| 4437 | /// One [`snapshot`](Project::snapshot) for the lot, which is the whole |
| 4438 | /// reason this exists rather than a caller's loop over |
| 4439 | /// [`ripple_delete`](Project::ripple_delete): forty silences must be one |
| 4440 | /// undo press, not forty. Cut back to front, so a region's frames still |
| 4441 | /// mean what the caller measured while the ones before it are cut. |
| 4442 | /// |
| 4443 | /// The list is sorted and overlapping entries are merged before anything is |
| 4444 | /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each |
| 4445 | /// other's frames. Refused, with no undo step, for an empty list, for a |
| 4446 | /// scope naming no lane that is there, and -- by name -- when the scope |
| 4447 | /// would take one half of a take with it |
| 4448 | /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)). |
| 4449 | pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> { |
| 4450 | let regions = tidy(regions); |
| 4451 | let on = self.scoped(scope)?; |
| 4452 | let Some(&(first, _)) = regions.first() else { |
| 4453 | return Err("nothing to cut".into()); |
| 4454 | }; |
| 4455 | self.scope_holds_takes_whole(&on, first)?; |
| 4456 | self.snapshot(); |
| 4457 | for &(at, len) in regions.iter().rev() { |
| 4458 | ripple(&mut self.lanes, &on, at, len); |
| 4459 | } |
| 4460 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 4461 | Ok(()) |
| 4462 | } |
| 4463 | |
| 4464 | /// The storage indices of `scope`, which is what every batch below walks. |
| 4465 | /// `Err` for a scope that names nothing there rather than a silent no-op: |
| 4466 | /// an edit asked for on a lane that is not there did not happen, and the |
| 4467 | /// caller has to hear so. |
| 4468 | fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> { |
| 4469 | let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect(); |
| 4470 | match on.is_empty() { |
| 4471 | true => Err("no track to work on".into()), |
| 4472 | false => Ok(on), |
| 4473 | } |
| 4474 | } |
| 4475 | |
| 4476 | /// The law a scoped ripple lives under: **a group travels as one**, so a |
| 4477 | /// batch that moves one half of a take and not the other would leave the |
| 4478 | /// halves disagreeing about where they stand -- an offset no hand asked |
| 4479 | /// for, and the reason the take's lanes have to be scoped together. |
| 4480 | /// |
| 4481 | /// Refused by name rather than widened silently. Widening would edit a |
| 4482 | /// track the user did not scope, which is exactly the surprise scoping |
| 4483 | /// exists to end; a front-end that wants the take is free to *say* the |
| 4484 | /// take's lanes, and to name them in what it tells the user afterwards. |
| 4485 | /// |
| 4486 | /// Only from `from` on: a take sitting entirely before the first cut does |
| 4487 | /// not move, so it is not this rule's business. |
| 4488 | fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> { |
| 4489 | let labels = handles(&self.lanes); |
| 4490 | // The halves of a group are on either of a lane's lists, and the |
| 4491 | // refusal names whichever sits outside the scope -- a clip like it |
| 4492 | // always has, and a caption now that a group may hold one. |
| 4493 | let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> { |
| 4494 | let Some(id) = link else { |
| 4495 | return Ok(()); |
| 4496 | }; |
| 4497 | for (j, data) in self.lanes.iter().enumerate() { |
| 4498 | if on.contains(&j) { |
| 4499 | continue; |
| 4500 | } |
| 4501 | let clip = data.clips.iter().find(|o| o.link == Some(id)); |
| 4502 | let sub = data.subs.iter().find(|s| s.link == Some(id)); |
| 4503 | if let Some(half) = clip { |
| 4504 | return Err(format!( |
| 4505 | "the {what} at frame {start} is one take with the {} clip at frame {}: \ |
| 4506 | moving one track of a take would pull it apart -- take the whole take, \ |
| 4507 | or detach them first", |
| 4508 | labels[j].label(), |
| 4509 | half.start |
| 4510 | ) |
| 4511 | .into()); |
| 4512 | } |
| 4513 | if let Some(half) = sub { |
| 4514 | return Err(format!( |
| 4515 | "the {what} at frame {start} is one take with the {} caption at frame {}: \ |
| 4516 | moving one track of a take would pull it apart -- take the whole take, \ |
| 4517 | or detach them first", |
| 4518 | labels[j].label(), |
| 4519 | half.start |
| 4520 | ) |
| 4521 | .into()); |
| 4522 | } |
| 4523 | } |
| 4524 | Ok(()) |
| 4525 | }; |
| 4526 | for &i in on { |
| 4527 | for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) { |
| 4528 | halves(c.start, c.link, &format!("{} clip", labels[i].label()))?; |
| 4529 | } |
| 4530 | // A caption before the first cut does not move, so it is not this |
| 4531 | // rule's business -- exactly the clip test's own line. |
| 4532 | for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) { |
| 4533 | halves(s.start, s.link, &format!("{} caption", labels[i].label()))?; |
| 4534 | } |
| 4535 | } |
| 4536 | Ok(()) |
| 4537 | } |
| 4538 | |
| 4539 | /// Play every one of `regions` at `speed` instead of cutting it: each is |
| 4540 | /// split out of whatever covers it, re-rated, and the room it no longer |
| 4541 | /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone |
| 4542 | /// does not ripple, and a hole where a silence shrank is the one thing this |
| 4543 | /// must not leave. One snapshot for the lot, like |
| 4544 | /// [`cut_regions`](Project::cut_regions). |
| 4545 | /// |
| 4546 | /// The rate is **absolute**, not a multiplier on what is there: running it |
| 4547 | /// twice over the same stretch leaves it at `speed`, not at `speed` |
| 4548 | /// squared, so a second pass over an already-cut timeline changes nothing. |
| 4549 | /// |
| 4550 | /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under |
| 4551 | /// the same take law: a lane outside `scope` is neither re-rated nor moved. |
| 4552 | /// |
| 4553 | /// Refused by name, with nothing changed and no undo step, when: |
| 4554 | /// |
| 4555 | /// * the scope would take one half of a take with it |
| 4556 | /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)); |
| 4557 | /// * a clip on a scoped lane covers only *part* of a region -- the lanes |
| 4558 | /// shrink by different amounts and the ripple would pull them apart, |
| 4559 | /// which is what cutting does not suffer and why delete mode has no such |
| 4560 | /// refusal; |
| 4561 | /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the |
| 4562 | /// piece could not be split out exactly; |
| 4563 | /// * two lanes' pieces would end up different lengths, which is a group |
| 4564 | /// whose halves disagree about their span (the refusal |
| 4565 | /// [`write_speed`](Project::write_speed) already makes, in its words); |
| 4566 | /// * the region would grow rather than shrink, i.e. it already plays faster |
| 4567 | /// than `speed`. |
| 4568 | pub fn speed_regions( |
| 4569 | &mut self, |
| 4570 | regions: &[(u32, u32)], |
| 4571 | speed: Speed, |
| 4572 | scope: &[Lane], |
| 4573 | ) -> crate::Result<()> { |
| 4574 | let regions = tidy(regions); |
| 4575 | let on = self.scoped(scope)?; |
| 4576 | let Some(&(first, _)) = regions.first() else { |
| 4577 | return Err("nothing to speed up".into()); |
| 4578 | }; |
| 4579 | self.scope_holds_takes_whole(&on, first)?; |
| 4580 | let labels = handles(&self.lanes); |
| 4581 | // Before anything is touched, because this is the refusal a person can |
| 4582 | // act on: a clip that laps over the edge of a silence has to be trimmed |
| 4583 | // (or the silences cut instead), and saying so after a rollback would |
| 4584 | // be saying it about a timeline that already looks different. |
| 4585 | for &(at, len) in ®ions { |
| 4586 | for &l in &on { |
| 4587 | for c in &self.lanes[l].clips { |
| 4588 | if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len) |
| 4589 | { |
| 4590 | return Err(format!( |
| 4591 | "the {} clip at frame {} covers only part of the silence at [{at}, {}): \ |
| 4592 | speeding it up would pull the lanes apart -- trim it first, or cut the \ |
| 4593 | silences out instead", |
| 4594 | labels[l].label(), |
| 4595 | c.start, |
| 4596 | at + len |
| 4597 | ) |
| 4598 | .into()); |
| 4599 | } |
| 4600 | } |
| 4601 | } |
| 4602 | } |
| 4603 | // The rest is checked as it is built: a split's own arithmetic is what |
| 4604 | // says whether a rate can address an edge. So the snapshot is taken |
| 4605 | // first and *rolled back* on a refusal -- one undo either way, and a |
| 4606 | // refusal still costs no step (`undo` pops the one just pushed). |
| 4607 | self.snapshot(); |
| 4608 | for &(at, len) in regions.iter().rev() { |
| 4609 | self.write_split(at, false, &on); |
| 4610 | self.write_split(at + len, false, &on); |
| 4611 | let mut room: Option<(Lane, u32)> = None; |
| 4612 | let mut refused = None; |
| 4613 | for &l in &on { |
| 4614 | let clips = &self.lanes[l].clips; |
| 4615 | for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) { |
| 4616 | if (c.start, c.end()) != (at, at + len) { |
| 4617 | // *Which* edge did not come off: a rate that cannot |
| 4618 | // address the end of the silence is not a rate that |
| 4619 | // cannot address its start, and naming the wrong frame |
| 4620 | // sends the user looking in the wrong place. |
| 4621 | let edge = match c.start == at { |
| 4622 | true => at + len, |
| 4623 | false => at, |
| 4624 | }; |
| 4625 | refused = Some(format!( |
| 4626 | "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \ |
| 4627 | detach it, or put it back to 1.00x first", |
| 4628 | labels[l].label(), |
| 4629 | c.start, |
| 4630 | c.speed |
| 4631 | )); |
| 4632 | continue; |
| 4633 | } |
| 4634 | let after = speed.frames(c.len()); |
| 4635 | match room { |
| 4636 | None => room = Some((labels[l], after)), |
| 4637 | Some((first, n)) if n != after => { |
| 4638 | refused = Some(format!( |
| 4639 | "at {speed} the {} half of the silence at frame {at} would cover \ |
| 4640 | {after} frames and the {} half {n}: they are one take and a take \ |
| 4641 | is one span -- detach them first", |
| 4642 | labels[l].label(), |
| 4643 | first.label() |
| 4644 | )); |
| 4645 | } |
| 4646 | Some(_) => {} |
| 4647 | } |
| 4648 | } |
| 4649 | } |
| 4650 | let shrunk = match (refused, room) { |
| 4651 | (Some(e), _) => { |
| 4652 | self.undo(); |
| 4653 | return Err(e.into()); |
| 4654 | } |
| 4655 | // A gap on every lane: nothing to re-rate, and nothing to close. |
| 4656 | (None, None) => continue, |
| 4657 | (None, Some((_, after))) => after, |
| 4658 | }; |
| 4659 | // The region's new length, on every scoped lane alike. |
| 4660 | let after = shrunk; |
| 4661 | let Some(delta) = len.checked_sub(shrunk) else { |
| 4662 | self.undo(); |
| 4663 | return Err(format!( |
| 4664 | "the silence at frame {at} already plays faster than {speed}: \ |
| 4665 | at that rate it would be {shrunk} frames instead of {len}" |
| 4666 | ) |
| 4667 | .into()); |
| 4668 | }; |
| 4669 | for &l in &on { |
| 4670 | for c in &mut self.lanes[l].clips { |
| 4671 | if c.start == at && c.end() == at + len { |
| 4672 | c.speed = speed; |
| 4673 | } else if c.start >= at + len { |
| 4674 | c.start -= delta; |
| 4675 | } |
| 4676 | } |
| 4677 | debug_assert!(sorted_disjoint(&self.lanes[l].clips)); |
| 4678 | // The captions on a scoped lane travel with the region's time: |
| 4679 | // a piece inside it plays in `after` frames instead of `len` |
| 4680 | // -- same words on less timeline, its window untouched, for |
| 4681 | // [`write_speed`]'s reason -- and everything behind the region |
| 4682 | // slides up by what the region gave back. |
| 4683 | // |
| 4684 | // The pieces inside re-time by their *boundaries*, not each |
| 4685 | // on its own: rounding one piece's start and its neighbour's |
| 4686 | // start apart can land both on the same frame (two one-frame |
| 4687 | // cues of a thirty-frame region at 2x both want frame 15), so |
| 4688 | // the mapped boundaries are walked in order and forced apart |
| 4689 | // -- each piece at least one frame, none past the region's own |
| 4690 | // new end, where the first follower lands exactly. A rounding |
| 4691 | // artifact is clamped, not refused: nothing about the words |
| 4692 | // asked for an overlap. |
| 4693 | let share = f64::from(after) / f64::from(len).max(1.); |
| 4694 | let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32; |
| 4695 | let mut prev = at; |
| 4696 | let subs = &mut self.lanes[l].subs; |
| 4697 | for i in 0..subs.len() { |
| 4698 | let s = subs[i]; |
| 4699 | if s.start >= at + len { |
| 4700 | subs[i].start = s.start - delta; |
| 4701 | } else if s.start >= at && s.end() <= at + len { |
| 4702 | let mut start = map(s.start).max(prev); |
| 4703 | let end = map(s.end()).max(start + 1).min(at + after); |
| 4704 | start = start.min(end - 1); |
| 4705 | subs[i].start = start; |
| 4706 | subs[i].frames = end - start; |
| 4707 | prev = end; |
| 4708 | } |
| 4709 | } |
| 4710 | debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs)); |
| 4711 | } |
| 4712 | } |
| 4713 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 4714 | Ok(()) |
| 4715 | } |
| 4716 | |
| 4717 | /// Remove the `V1` clip at `idx` and everything under it, closing the gap |
| 4718 | /// -- the whole-group delete a single-lane front-end means. `false` for a |
| 4719 | /// bad index. Changes the mapping: the caller must reseek. |
| 4720 | pub fn delete(&mut self, idx: usize) -> bool { |
| 4721 | self.delete_in(Lane::V1, idx) |
| 4722 | } |
| 4723 | |
| 4724 | /// [`delete`](Project::delete) for the lane the clip was picked on. A clip |
| 4725 | /// in no group (or a group of one, which is the same thing to a delete) is |
| 4726 | /// what it always was: its own span cut out of *every* lane, so the |
| 4727 | /// timeline closes up under it. A clip in a group takes the group with it, |
| 4728 | /// each member by its **own** span and on its **own** lane -- the members |
| 4729 | /// keep their offsets, so their spans may disagree, and the lanes may end |
| 4730 | /// up out of step with each other, which is inherent to a hand-built group |
| 4731 | /// and one undo away. Every member -- clips and captions alike -- goes by |
| 4732 | /// the same law: its own span out of its own lane, hole closed; a caption |
| 4733 | /// in no group keeps the lift that leaves a gap, which is its own door's |
| 4734 | /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the |
| 4735 | /// whole group, so one [`Project::undo`] puts it back. `false` for a bad |
| 4736 | /// index, and for a lane that is not there. Changes the mapping: the |
| 4737 | /// caller must reseek. |
| 4738 | pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool { |
| 4739 | let Some(members) = self.group_of(lane, idx) else { |
| 4740 | return false; |
| 4741 | }; |
| 4742 | if !members.alone() { |
| 4743 | return self.delete_members(&members); |
| 4744 | } |
| 4745 | let Some(clip) = self.lane(lane).get(idx).copied() else { |
| 4746 | return false; |
| 4747 | }; |
| 4748 | self.ripple_delete(clip.start, clip.frames()) |
| 4749 | } |
| 4750 | |
| 4751 | /// [`delete_in`](Project::delete_in) for the caption the pick named: a |
| 4752 | /// caption in no group lifts, exactly as its own key always made it |
| 4753 | /// ([`Project::lift_sub`]), and a caption in a group takes the group with |
| 4754 | /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own |
| 4755 | /// span out of its own lane, hole closed, captions and clips alike. |
| 4756 | /// `false` for a bad index. |
| 4757 | pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool { |
| 4758 | let Some(members) = self.group_of(lane, idx) else { |
| 4759 | return false; |
| 4760 | }; |
| 4761 | if !members.alone() { |
| 4762 | return self.delete_members(&members); |
| 4763 | } |
| 4764 | self.lift_sub(lane, idx) |
| 4765 | } |
| 4766 | |
| 4767 | /// The one whole-group delete both doors land in: every member's own span |
| 4768 | /// cut out of its own lane and the hole closed there -- clips and |
| 4769 | /// captions by the same law -- and nothing else on another lane moves, |
| 4770 | /// which is what keeps one member's ripple from dragging another |
| 4771 | /// member's lane out from under it. One snapshot, one undo step. |
| 4772 | fn delete_members(&mut self, members: &Members) -> bool { |
| 4773 | self.snapshot(); |
| 4774 | for &(l, i) in &members.clips { |
| 4775 | let c = self.lanes[l].clips[i]; |
| 4776 | ripple(&mut self.lanes, &[l], c.start, c.frames()); |
| 4777 | } |
| 4778 | // The captions go by the same law their clip siblings do -- the span |
| 4779 | // out of its own lane, the hole closed -- and not by the lift a |
| 4780 | // *lone* caption's delete is: deleted with its group, the words after |
| 4781 | // it slide up with everything else, or the lane the group emptied is |
| 4782 | // the one lane the delete left a hole in. `ripple` is the one |
| 4783 | // mechanism (it clears the span and shifts the rest, clips and |
| 4784 | // captions alike); a sub lane holds no clips, so its other list is |
| 4785 | // untouched. |
| 4786 | for &(l, i) in &members.subs { |
| 4787 | let s = self.lanes[l].subs[i]; |
| 4788 | ripple(&mut self.lanes, &[l], s.start, s.frames); |
| 4789 | } |
| 4790 | debug_assert!(links_are_consistent(&self.lanes).is_ok()); |
| 4791 | true |
| 4792 | } |
| 4793 | |
| 4794 | /// The clips a lane holds, for the sweep's order law: `lane`'s own list. |
| 4795 | #[cfg(test)] |
| 4796 | pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] { |
| 4797 | self.lane(lane) |
| 4798 | } |
| 4799 | |
| 4800 | /// How many undo steps are stacked: what the sweep asks so "one op, one |
| 4801 | /// snapshot" is a count and not a guess. |
| 4802 | #[cfg(test)] |
| 4803 | pub(crate) fn history_len(&self) -> usize { |
| 4804 | self.history.len() |
| 4805 | } |
| 4806 | |
| 4807 | /// How many redo steps are stacked: what the sweep asks to check `undo` |
| 4808 | /// left a branch behind, and that a fresh edit clears it. |
| 4809 | #[cfg(test)] |
| 4810 | pub(crate) fn redo_len(&self) -> usize { |
| 4811 | self.redo.len() |
| 4812 | } |
| 4813 | |
| 4814 | /// Every part of the project that an edit can change, as comparable |
| 4815 | /// values: what the sweep's undo round-trip asks "byte identical?" of. |
| 4816 | #[cfg(test)] |
| 4817 | pub(crate) fn parts(&self) -> SweepParts { |
| 4818 | SweepParts( |
| 4819 | self.sources.len(), |
| 4820 | self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(), |
| 4821 | self.lanes.iter().map(|l| l.subs.clone()).collect(), |
| 4822 | ) |
| 4823 | } |
| 4824 | |
| 4825 | /// Restore every lane from before the last successful edit -- the clips and |
| 4826 | /// the lane list both. `false` when there is nothing left to undo. Pushes |
| 4827 | /// the lanes just left onto the redo stack, so [`Project::redo`] can walk |
| 4828 | /// forward again. |
| 4829 | pub fn undo(&mut self) -> bool { |
| 4830 | match self.history.pop() { |
| 4831 | Some(prev) => { |
| 4832 | self.redo.push(std::mem::replace(&mut self.lanes, prev)); |
| 4833 | true |
| 4834 | } |
| 4835 | None => false, |
| 4836 | } |
| 4837 | } |
| 4838 | |
| 4839 | /// Restore every lane from before the last [`Project::undo`] -- the |
| 4840 | /// mirror of `undo`, walking the redo stack it fills. `false` when there |
| 4841 | /// is nothing left to redo, which is also true after any fresh edit: a |
| 4842 | /// new [`Project::snapshot`] clears the branch `undo` left behind. |
| 4843 | pub fn redo(&mut self) -> bool { |
| 4844 | match self.redo.pop() { |
| 4845 | Some(next) => { |
| 4846 | self.history.push(std::mem::replace(&mut self.lanes, next)); |
| 4847 | true |
| 4848 | } |
| 4849 | None => false, |
| 4850 | } |
| 4851 | } |
| 4852 | |
| 4853 | /// The project an export renders from: everything a render reads, with the |
| 4854 | /// undo history left behind. An export never walks the history back, and |
| 4855 | /// cloning it costs a copy of every lane list in the session -- this is |
| 4856 | /// taken on the UI thread, so it clones the lanes and the sources alone. |
| 4857 | pub fn export_snapshot(&self) -> Self { |
| 4858 | Self { |
| 4859 | sources: self.sources.clone(), |
| 4860 | lanes: self.lanes.clone(), |
| 4861 | eq: self.eq.clone(), |
| 4862 | color: self.color.clone(), |
| 4863 | transform: self.transform.clone(), |
| 4864 | history: Vec::new(), |
| 4865 | redo: Vec::new(), |
| 4866 | next_link: self.next_link, |
| 4867 | subtitles: self.subtitles.clone(), |
| 4868 | limiter: self.limiter, |
| 4869 | tone: self.tone, |
| 4870 | } |
| 4871 | } |
| 4872 | |
| 4873 | /// Half-open `(source, start, end)` segments in *source* seconds, from |
| 4874 | /// `timeline_frame` to the end of the timeline -- the play list for the |
| 4875 | /// audio worker, read off **`A1`**. A `None` source is a gap: the |
| 4876 | /// worker synthesises that many seconds of silence, which is what keeps the |
| 4877 | /// audio master clock counting across a hole instead of stalling on it. |
| 4878 | /// The first entry is partial when the position is mid-clip. Empty when the |
| 4879 | /// position is past the end or `fps` is not usable. |
| 4880 | pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> { |
| 4881 | self.lane_segments_from(Lane::A1, timeline_frame, fps) |
| 4882 | } |
| 4883 | |
| 4884 | /// [`segments_from`](Project::segments_from) for a named lane. |
| 4885 | pub fn lane_segments_from( |
| 4886 | &self, |
| 4887 | lane: Lane, |
| 4888 | timeline_frame: u32, |
| 4889 | fps: f64, |
| 4890 | ) -> Vec<(Option<usize>, f64, f64)> { |
| 4891 | if !(fps.is_finite() && fps > 0.0) { |
| 4892 | return Vec::new(); |
| 4893 | } |
| 4894 | self.spans_from(lane, timeline_frame) |
| 4895 | .iter() |
| 4896 | .map(|span| match span.from { |
| 4897 | // A clip's window is in *source* seconds: where in the file it |
| 4898 | // reads from, which a delete before it never shifts. How many |
| 4899 | // source frames that is, is the span's own arithmetic -- at a |
| 4900 | // speed it is not the timeline length ([`Span::source_len`]). |
| 4901 | Some((source, in_frame)) => ( |
| 4902 | Some(source), |
| 4903 | f64::from(in_frame) / fps, |
| 4904 | f64::from(in_frame + span.source_len()) / fps, |
| 4905 | ), |
| 4906 | // A gap has no file, so all it can say is how long it is. |
| 4907 | None => (None, 0.0, f64::from(span.len) / fps), |
| 4908 | }) |
| 4909 | .collect() |
| 4910 | } |
| 4911 | |
| 4912 | /// One play list per audio lane that *holds* something, in display order -- |
| 4913 | /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and |
| 4914 | /// what an export asks how many lanes it would have to mix. |
| 4915 | /// |
| 4916 | /// Never empty: a timeline whose audio lanes are all empty (or which has no |
| 4917 | /// audio lane at all) still yields one all-gap list, so it plays silence |
| 4918 | /// against a master clock exactly as it did before there were lanes to |
| 4919 | /// count. Lanes with nothing on them are left out rather than mixed in as |
| 4920 | /// silence: they would cost a decode thread each and add zero. |
| 4921 | pub fn audio_segments_from( |
| 4922 | &self, |
| 4923 | timeline_frame: u32, |
| 4924 | fps: f64, |
| 4925 | ) -> Vec<Vec<(Option<usize>, f64, f64)>> { |
| 4926 | self.audio_lanes() |
| 4927 | .into_iter() |
| 4928 | .map(|lane| self.lane_segments_from(lane, timeline_frame, fps)) |
| 4929 | .collect() |
| 4930 | } |
| 4931 | |
| 4932 | /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from) |
| 4933 | /// builds a play list for, in the same order. Public because everything |
| 4934 | /// asked per audio lane -- which clip a segment's equalizer belongs to, |
| 4935 | /// which lane an mp4 export would copy -- has to read the very list the |
| 4936 | /// sound comes off, or the two answers drift apart (which is exactly how an |
| 4937 | /// `A2`-only project once exported silently, ledger). |
| 4938 | pub fn audio_lanes(&self) -> Vec<Lane> { |
| 4939 | let lanes: Vec<Lane> = self |
| 4940 | .lanes() |
| 4941 | .into_iter() |
| 4942 | .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty()) |
| 4943 | .collect(); |
| 4944 | match lanes.is_empty() { |
| 4945 | // The all-gap fallback: `A1`'s own (empty) list, so a timeline with |
| 4946 | // no sound still plays silence against the master clock. |
| 4947 | true => vec![Lane::A1], |
| 4948 | false => lanes, |
| 4949 | } |
| 4950 | } |
| 4951 | |
| 4952 | /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s |
| 4953 | /// segments plays at, and how long the timeline gives it: the same lanes in |
| 4954 | /// the same order, one entry per segment, `None` for a segment at real time |
| 4955 | /// -- which is every segment of a project nobody has speeded, and the path |
| 4956 | /// the audio worker leaves bit-identical. |
| 4957 | /// |
| 4958 | /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason: |
| 4959 | /// the segment tuple is what every opener and a dozen tests speak, and a |
| 4960 | /// rate is not part of *which samples* a segment names. |
| 4961 | /// |
| 4962 | /// The seconds are what makes a resample exact: a segment's own window |
| 4963 | /// resolves to whole source frames, and dividing that by the rate would |
| 4964 | /// leave each clip a fraction of a frame short or long -- a drift that grows |
| 4965 | /// clip by clip. Told how much timeline it owes, the worker pads or trims |
| 4966 | /// the last few samples of each segment instead, so the sound stays locked |
| 4967 | /// to the picture however many speeded cuts it walks through. |
| 4968 | pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> { |
| 4969 | self.audio_lanes() |
| 4970 | .into_iter() |
| 4971 | .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps)) |
| 4972 | .collect() |
| 4973 | } |
| 4974 | |
| 4975 | /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching |
| 4976 | /// [`lane_segments_from`](Project::lane_segments_from) entry for entry -- |
| 4977 | /// same walk, same `fps` refusal. |
| 4978 | pub fn lane_speeds_from( |
| 4979 | &self, |
| 4980 | lane: Lane, |
| 4981 | timeline_frame: u32, |
| 4982 | fps: f64, |
| 4983 | ) -> Vec<Option<Stretch>> { |
| 4984 | if !(fps.is_finite() && fps > 0.0) { |
| 4985 | return Vec::new(); |
| 4986 | } |
| 4987 | self.spans_from(lane, timeline_frame) |
| 4988 | .iter() |
| 4989 | .map(|span| { |
| 4990 | (!span.speed.is_normal()).then(|| Stretch { |
| 4991 | step: span.speed.as_f64(), |
| 4992 | timeline_secs: f64::from(span.len) / fps, |
| 4993 | }) |
| 4994 | }) |
| 4995 | .collect() |
| 4996 | } |
| 4997 | |
| 4998 | /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s |
| 4999 | /// segments plays through: the same lanes in the same order, one entry per |
| 5000 | /// segment, `None` where the segment is a gap or its clip plays flat. |
| 5001 | /// |
| 5002 | /// A parallel list rather than a fourth element of the segment tuple: that |
| 5003 | /// tuple is what every opener, the packet-copy path and a dozen tests speak, |
| 5004 | /// and an effect is not part of *which samples* a segment names. A short |
| 5005 | /// list therefore means "flat from here on" rather than a length mismatch -- |
| 5006 | /// see [`crate::AudioSession::open_mixed_streams_eq`]. |
| 5007 | pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> { |
| 5008 | self.audio_lanes() |
| 5009 | .into_iter() |
| 5010 | .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps)) |
| 5011 | .collect() |
| 5012 | } |
| 5013 | |
| 5014 | /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching |
| 5015 | /// [`lane_segments_from`](Project::lane_segments_from) entry for entry -- |
| 5016 | /// same walk, same `fps` refusal, so the two lists cannot come out different |
| 5017 | /// lengths. |
| 5018 | pub fn lane_eqs_from( |
| 5019 | &self, |
| 5020 | lane: Lane, |
| 5021 | timeline_frame: u32, |
| 5022 | fps: f64, |
| 5023 | ) -> Vec<Option<EqParams>> { |
| 5024 | if !(fps.is_finite() && fps > 0.0) { |
| 5025 | return Vec::new(); |
| 5026 | } |
| 5027 | self.spans_from(lane, timeline_frame) |
| 5028 | .iter() |
| 5029 | // A span off a clip covers that clip's frames and no others, so its |
| 5030 | // own start names the clip -- the index a [`Span`] does not carry. |
| 5031 | .map(|span| { |
| 5032 | self.map(lane, span.start) |
| 5033 | .and_then(|(idx, _)| self.eq_of(lane, idx).cloned()) |
| 5034 | }) |
| 5035 | .collect() |
| 5036 | } |
| 5037 | |
| 5038 | /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s |
| 5039 | /// segments plays through: the same lanes in the same order, one entry per |
| 5040 | /// segment, `None` where the segment is a gap or its clip has neither a |
| 5041 | /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for |
| 5042 | /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason. |
| 5043 | pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> { |
| 5044 | self.audio_lanes() |
| 5045 | .into_iter() |
| 5046 | .map(|lane| self.lane_fades_from(lane, timeline_frame, fps)) |
| 5047 | .collect() |
| 5048 | } |
| 5049 | |
| 5050 | /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching |
| 5051 | /// [`lane_segments_from`](Project::lane_segments_from) entry for entry. |
| 5052 | pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> { |
| 5053 | if !(fps.is_finite() && fps > 0.0) { |
| 5054 | return Vec::new(); |
| 5055 | } |
| 5056 | self.spans_from(lane, timeline_frame) |
| 5057 | .iter() |
| 5058 | .map(|span| { |
| 5059 | let (idx, _) = self.map(lane, span.start)?; |
| 5060 | let clip = self.lane(lane).get(idx)?; |
| 5061 | (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade { |
| 5062 | // `span.len` is the clip's own remaining frames from |
| 5063 | // `span.start` on -- shorter than `clip.frames()` only |
| 5064 | // when this is the first span of a seek mid-clip. |
| 5065 | elapsed: clip.frames().saturating_sub(span.len), |
| 5066 | fade_in: clip.fade_in, |
| 5067 | fade_out: clip.fade_out, |
| 5068 | total: clip.frames(), |
| 5069 | }) |
| 5070 | }) |
| 5071 | .collect() |
| 5072 | } |
| 5073 | |
| 5074 | /// Pushes the undo snapshot. Every mutating method calls this once, *after* |
| 5075 | /// it has decided it will succeed -- a refusal must not cost an undo step. |
| 5076 | /// Clears the redo stack: a fresh edit branches off from here, so whatever |
| 5077 | /// `undo` had left to redo is no longer where this edit leads back to. |
| 5078 | fn snapshot(&mut self) { |
| 5079 | if self.history.len() == HISTORY_CAP { |
| 5080 | self.history.remove(0); |
| 5081 | } |
| 5082 | self.history.push(self.lanes.clone()); |
| 5083 | self.redo.clear(); |
| 5084 | } |
| 5085 | |
| 5086 | fn new_link(&mut self) -> u32 { |
| 5087 | let id = self.next_link; |
| 5088 | self.next_link = self.next_link.saturating_add(1); |
| 5089 | id |
| 5090 | } |
| 5091 | |
| 5092 | } |
| 5093 | |
| 5094 | /// The handle of every lane, in storage order -- the one definition of what |
| 5095 | /// [`Lane::ord`] counts. |
| 5096 | fn handles(lanes: &[LaneData]) -> Vec<Lane> { |
| 5097 | let (mut video, mut audio, mut subtitle) = (0, 0, 0); |
| 5098 | lanes |
| 5099 | .iter() |
| 5100 | .map(|l| match l.kind { |
| 5101 | LaneKind::Video => { |
| 5102 | video += 1; |
| 5103 | Lane::new(LaneKind::Video, video - 1) |
| 5104 | } |
| 5105 | LaneKind::Audio => { |
| 5106 | audio += 1; |
| 5107 | Lane::new(LaneKind::Audio, audio - 1) |
| 5108 | } |
| 5109 | LaneKind::Subtitle => { |
| 5110 | subtitle += 1; |
| 5111 | Lane::new(LaneKind::Subtitle, subtitle - 1) |
| 5112 | } |
| 5113 | }) |
| 5114 | .collect() |
| 5115 | } |
| 5116 | |
| 5117 | /// The one law a caption re-time scales by: frame `f` moves about the held |
| 5118 | /// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`] |
| 5119 | /// commits it, [`Project::speeded_playhead`] previews it -- both build their |
| 5120 | /// [`TimelineMap`] piece from this single answer so the two cannot drift |
| 5121 | /// apart by a frame the way they once did. |
| 5122 | fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 { |
| 5123 | (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new) |
| 5124 | .round() |
| 5125 | .clamp(0., f64::from(u32::MAX)) as u32 |
| 5126 | } |
| 5127 | |
| 5128 | /// Which source frame a clip plays at `timeline_frame`: its in-point plus the |
| 5129 | /// offset *at the clip's own rate*. The one place the two frame spaces meet, so |
| 5130 | /// a speed cannot be applied twice or forgotten in one of them. |
| 5131 | fn source_frame(c: &Clip, timeline_frame: u32) -> u32 { |
| 5132 | // Clamped inside the clip's own range: rounding at a slow rate can put the |
| 5133 | // last timeline frame of a clip a frame past its out-point, and a source |
| 5134 | // frame outside the range is one the next clip owns. |
| 5135 | (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1) |
| 5136 | } |
| 5137 | |
| 5138 | /// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap |
| 5139 | /// finder generic makes the subtitle path use the same bounded-hole rules as |
| 5140 | /// media lanes without teaching the media-specific take logic about captions. |
| 5141 | trait GapPlacement { |
| 5142 | fn start_frame(&self) -> u32; |
| 5143 | fn end_frame(&self) -> u32; |
| 5144 | } |
| 5145 | |
| 5146 | impl GapPlacement for Clip { |
| 5147 | fn start_frame(&self) -> u32 { |
| 5148 | self.start |
| 5149 | } |
| 5150 | |
| 5151 | fn end_frame(&self) -> u32 { |
| 5152 | self.end() |
| 5153 | } |
| 5154 | } |
| 5155 | |
| 5156 | impl GapPlacement for SubClip { |
| 5157 | fn start_frame(&self) -> u32 { |
| 5158 | self.start |
| 5159 | } |
| 5160 | |
| 5161 | fn end_frame(&self) -> u32 { |
| 5162 | self.end() |
| 5163 | } |
| 5164 | } |
| 5165 | |
| 5166 | /// Index of the placement covering `frame`, or `None` for a gap or past the |
| 5167 | /// end. Binary search: the sorted-disjoint invariant is what makes it legal. |
| 5168 | fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> { |
| 5169 | let idx = items.partition_point(|item| item.start_frame() <= frame).checked_sub(1)?; |
| 5170 | (frame < items[idx].end_frame()).then_some(idx) |
| 5171 | } |
| 5172 | |
| 5173 | /// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None` |
| 5174 | /// when `frame` is inside a placement, or past the last one. Sorted-disjoint |
| 5175 | /// invariant like [`at`]: the first placement whose start is past `frame` is |
| 5176 | /// the far wall, and the last one that ends at or before `frame` (or the |
| 5177 | /// timeline's own head, `0`, when there is none) is the near one. |
| 5178 | fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> { |
| 5179 | if at(items, frame).is_some() { |
| 5180 | return None; |
| 5181 | } |
| 5182 | let idx = items.partition_point(|item| item.start_frame() <= frame); |
| 5183 | let next = items.get(idx)?; |
| 5184 | let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame()); |
| 5185 | Some((start, next.start_frame() - start)) |
| 5186 | } |
| 5187 | |
| 5188 | /// Every bounded hole in `items`, left to right. The tail after the last |
| 5189 | /// placement is deliberately absent: there is no later placement for a ripple |
| 5190 | /// to bring back. |
| 5191 | fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> { |
| 5192 | let mut out = Vec::new(); |
| 5193 | let mut next = 0; |
| 5194 | for item in items { |
| 5195 | if item.start_frame() > next { |
| 5196 | out.push((next, item.start_frame() - next)); |
| 5197 | } |
| 5198 | next = item.end_frame(); |
| 5199 | } |
| 5200 | out |
| 5201 | } |
| 5202 | |
| 5203 | /// Index of the clip `frame` falls *strictly inside*, i.e. the one a split |
| 5204 | /// there would cut in two. A placement's own first frame is not inside it. |
| 5205 | fn splittable(clips: &[Clip], frame: u32) -> Option<usize> { |
| 5206 | let idx = at(clips, frame)?; |
| 5207 | // ...and, on a speeded clip, one its rate can actually address |
| 5208 | // ([`Speed::split_at`]): a cut between two showings of one source frame |
| 5209 | // would leave halves that no longer add up to the clip that was cut. |
| 5210 | (frame > clips[idx].start) |
| 5211 | .then_some(idx) |
| 5212 | .filter(|&idx| split_source(&clips[idx], frame).is_some()) |
| 5213 | } |
| 5214 | |
| 5215 | /// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's |
| 5216 | /// rate cannot address that frame. |
| 5217 | fn split_source(c: &Clip, frame: u32) -> Option<u32> { |
| 5218 | c.speed |
| 5219 | .split_at(c.len(), frame - c.start) |
| 5220 | .map(|src| c.in_frame + src) |
| 5221 | } |
| 5222 | |
| 5223 | /// Index of the first of the two clips a [`Project::regroup`] at `frame` would |
| 5224 | /// rejoin: they must touch there, and be consecutive frames of one source. |
| 5225 | fn joinable(clips: &[Clip], frame: u32) -> Option<usize> { |
| 5226 | let idx = clips.iter().position(|c| c.end() == frame)?; |
| 5227 | let next = clips.get(idx + 1)?; |
| 5228 | let joined = clips[idx].len() + next.len(); |
| 5229 | (next.start == frame |
| 5230 | && next.source == clips[idx].source |
| 5231 | && next.in_frame == clips[idx].out_frame |
| 5232 | // ...at one rate, and one that puts the rejoined clip back in exactly |
| 5233 | // the room the two took up: what a split could have produced, which is |
| 5234 | // all this undoes. |
| 5235 | && next.speed == clips[idx].speed |
| 5236 | && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames()) |
| 5237 | .then_some(idx) |
| 5238 | } |
| 5239 | |
| 5240 | /// The lane invariant: sorted by `start`, no two placements overlapping, no |
| 5241 | /// empty placement. Checked at every constructor and asserted after every |
| 5242 | /// mutation -- the offset model is only tractable while it holds. |
| 5243 | /// The one thing an equalizer setting may not be: a value the text format |
| 5244 | /// cannot write and read back as itself. Checked wherever params come in, so |
| 5245 | /// what an edit produces is always what a save writes and a load reads. |
| 5246 | fn finite(params: &EqParams) -> bool { |
| 5247 | params |
| 5248 | .bands |
| 5249 | .iter() |
| 5250 | .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite()) |
| 5251 | } |
| 5252 | |
| 5253 | /// The same for a colour grade: [`crate::color`] itself falls back to identity |
| 5254 | /// on a non-finite value, but a value that cannot be written and read back as |
| 5255 | /// itself has no business reaching the model. |
| 5256 | fn color_finite(p: &ColorParams) -> bool { |
| 5257 | p.brightness.is_finite() |
| 5258 | && p.contrast.is_finite() |
| 5259 | && p.saturation.is_finite() |
| 5260 | && p.tint.is_finite() |
| 5261 | } |
| 5262 | |
| 5263 | /// The same for a transform: [`crate::scale`] clamps a non-finite value to |
| 5264 | /// identity at read time, but a value that cannot round-trip has no business |
| 5265 | /// reaching the model. |
| 5266 | fn transform_finite(p: &TransformParams) -> bool { |
| 5267 | p.pos_x.is_finite() |
| 5268 | && p.pos_y.is_finite() |
| 5269 | && p.scale.is_finite() |
| 5270 | && p.rotate.is_finite() |
| 5271 | && p.crop_l.is_finite() |
| 5272 | && p.crop_r.is_finite() |
| 5273 | && p.crop_t.is_finite() |
| 5274 | && p.crop_b.is_finite() |
| 5275 | } |
| 5276 | |
| 5277 | fn sorted_disjoint(clips: &[Clip]) -> bool { |
| 5278 | clips.iter().all(|c| c.out_frame > c.in_frame) |
| 5279 | && clips.windows(2).all(|w| w[0].end() <= w[1].start) |
| 5280 | } |
| 5281 | |
| 5282 | /// The very same invariant on a subtitle lane, in that lane's own two units: |
| 5283 | /// sorted by `start`, no two placements overlapping, no empty placement at |
| 5284 | /// either end. Asserted after every mutation, exactly as its twin is. |
| 5285 | fn subs_sorted_disjoint(subs: &[SubClip]) -> bool { |
| 5286 | subs.iter() |
| 5287 | .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0) |
| 5288 | && subs.windows(2).all(|w| w[0].end() <= w[1].start) |
| 5289 | } |
| 5290 | |
| 5291 | /// What `frames` timeline frames are worth in microseconds at `fps`, signed -- |
| 5292 | /// the one conversion between a lane's clock and a cue's, and `0` for a rate |
| 5293 | /// that is not one (every caller of this has already refused such a rate). |
| 5294 | fn us_of(frames: i64, fps: f64) -> i64 { |
| 5295 | match fps.is_finite() && fps > 0.0 { |
| 5296 | true => ((frames as f64) / fps * 1e6).round() as i64, |
| 5297 | false => 0, |
| 5298 | } |
| 5299 | } |
| 5300 | |
| 5301 | /// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`, |
| 5302 | /// dropping what is inside the hole, splitting what straddles it and trimming |
| 5303 | /// what overlaps an edge. The windows follow the cut by proportion |
| 5304 | /// ([`SubClip::window_at`]), so what is left says exactly the words it said. |
| 5305 | fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) { |
| 5306 | let mut out = Vec::with_capacity(subs.len() + 1); |
| 5307 | for s in subs.drain(..) { |
| 5308 | if s.end() <= start || s.start >= end { |
| 5309 | out.push(s); |
| 5310 | continue; |
| 5311 | } |
| 5312 | if s.start < start { |
| 5313 | out.push(SubClip { |
| 5314 | frames: start - s.start, |
| 5315 | out_us: s.window_at(start), |
| 5316 | // Both pieces lose the group id, for [`clear`]'s reason: one |
| 5317 | // id on two boxes of one lane is the one thing it may never |
| 5318 | // mean. |
| 5319 | link: None, |
| 5320 | ..s |
| 5321 | }); |
| 5322 | } |
| 5323 | if s.end() > end { |
| 5324 | out.push(SubClip { |
| 5325 | start: end, |
| 5326 | frames: s.end() - end, |
| 5327 | in_us: s.window_at(end), |
| 5328 | link: None, |
| 5329 | ..s |
| 5330 | }); |
| 5331 | } |
| 5332 | } |
| 5333 | *subs = out; |
| 5334 | } |
| 5335 | |
| 5336 | /// [`open_room`] for a subtitle lane: slides everything from `at` on later by |
| 5337 | /// `len`, splitting a placement that straddles `at` so the two halves end up on |
| 5338 | /// either side of the hole. A `len` of 0 is that split alone, which is what a |
| 5339 | /// [`Project::split`] over a subtitle lane is. |
| 5340 | fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) { |
| 5341 | if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) { |
| 5342 | let s = subs[idx]; |
| 5343 | let cut = s.window_at(at); |
| 5344 | subs[idx] = SubClip { |
| 5345 | frames: at - s.start, |
| 5346 | out_us: cut, |
| 5347 | link: None, |
| 5348 | ..s |
| 5349 | }; |
| 5350 | subs.insert( |
| 5351 | idx + 1, |
| 5352 | SubClip { |
| 5353 | start: at, |
| 5354 | frames: s.end() - at, |
| 5355 | in_us: cut, |
| 5356 | link: None, |
| 5357 | ..s |
| 5358 | }, |
| 5359 | ); |
| 5360 | } |
| 5361 | for s in subs.iter_mut().filter(|s| s.start >= at) { |
| 5362 | s.start += len; |
| 5363 | } |
| 5364 | } |
| 5365 | |
| 5366 | /// [`joinable`] for a subtitle lane: the first of the two placements a |
| 5367 | /// [`Project::regroup`] at `frame` would rejoin. What a split could have |
| 5368 | /// produced and nothing else -- they touch on the timeline, they read the same |
| 5369 | /// track, and the second one's window carries on where the first's stopped. |
| 5370 | fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> { |
| 5371 | let idx = subs.iter().position(|s| s.end() == frame)?; |
| 5372 | let next = subs.get(idx + 1)?; |
| 5373 | (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us) |
| 5374 | .then_some(idx) |
| 5375 | } |
| 5376 | |
| 5377 | /// How far one `edge` of the caption at `idx` may travel against its own lane's |
| 5378 | /// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the |
| 5379 | /// rate, which a caption *following* a group's trim does not have to be exact |
| 5380 | /// about -- its own walls, its own one surviving frame, and nothing that needs |
| 5381 | /// a clock. |
| 5382 | fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) { |
| 5383 | let s = &subs[idx]; |
| 5384 | match edge { |
| 5385 | Edge::Start => ( |
| 5386 | idx.checked_sub(1).map_or(0, |p| subs[p].end()), |
| 5387 | s.end() - 1, |
| 5388 | ), |
| 5389 | Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)), |
| 5390 | } |
| 5391 | } |
| 5392 | |
| 5393 | /// Move one `edge` of `s` to timeline frame `to`, its window following by the |
| 5394 | /// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run |
| 5395 | /// forwards and backwards. The caption a group's trim is carrying has no rate |
| 5396 | /// of its own and needs none: what one frame of it is worth in microseconds is |
| 5397 | /// the window it already shows over the frames it already takes. |
| 5398 | fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) { |
| 5399 | let per_frame = s.window_us() / i64::from(s.frames.max(1)); |
| 5400 | let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from)); |
| 5401 | match edge { |
| 5402 | Edge::Start => { |
| 5403 | s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1); |
| 5404 | s.frames = s.end() - to; |
| 5405 | s.start = to; |
| 5406 | } |
| 5407 | Edge::End => { |
| 5408 | s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1); |
| 5409 | s.frames = to - s.start; |
| 5410 | } |
| 5411 | } |
| 5412 | debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0); |
| 5413 | } |
| 5414 | |
| 5415 | /// The grouping invariant, checked in release at [`Project::from_parts`] and |
| 5416 | /// asserted by the tests after every edit: a link id names **at most one** |
| 5417 | /// placement per lane -- a clip on a media lane or a caption on a subtitle |
| 5418 | /// one, whichever carries it. That is all "these move together" can mean now |
| 5419 | /// that a group is assembled by hand: the members keep their own spans and |
| 5420 | /// their own offsets, and what binds them is the id alone. |
| 5421 | /// |
| 5422 | /// Deliberately *not* a pairing of two lanes, and never a span rule: with N |
| 5423 | /// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two |
| 5424 | /// placements of one group may cover different frames -- the offset-preserving |
| 5425 | /// group a hand builds with [`Project::group_all`], which a drag moves by one |
| 5426 | /// delta rather than by one span. |
| 5427 | /// |
| 5428 | /// A link no other lane carries is legal and is not an error: lifting one half |
| 5429 | /// of a group ([`Project::lift`]) leaves exactly that, and a save of that |
| 5430 | /// timeline has to load again. |
| 5431 | /// [`links_are_consistent`](self::links_are_consistent) for a whole project, |
| 5432 | /// asked by the sweep suite's universal law. |
| 5433 | #[cfg(test)] |
| 5434 | pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> { |
| 5435 | links_are_consistent(&p.lanes) |
| 5436 | } |
| 5437 | |
| 5438 | fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> { |
| 5439 | let handles = handles(lanes); |
| 5440 | for (data, lane) in lanes.iter().zip(&handles) { |
| 5441 | for (i, c) in data.clips.iter().enumerate() { |
| 5442 | let Some(id) = c.link else { continue }; |
| 5443 | if data.clips[..i].iter().any(|prev| prev.link == Some(id)) { |
| 5444 | return Err( |
| 5445 | format!("link {id} names two clips in the {} lane", lane.label()).into(), |
| 5446 | ); |
| 5447 | } |
| 5448 | } |
| 5449 | // ...and the same for the captions, in their own list on the same lane: |
| 5450 | // a subtitle lane holds no `Clip`, so this is the only list a caption's |
| 5451 | // id could be doubled on. |
| 5452 | for (i, s) in data.subs.iter().enumerate() { |
| 5453 | let Some(id) = s.link else { continue }; |
| 5454 | if data.subs[..i].iter().any(|prev| prev.link == Some(id)) { |
| 5455 | return Err(format!( |
| 5456 | "link {id} names two captions in the {} lane", |
| 5457 | lane.label() |
| 5458 | ) |
| 5459 | .into()); |
| 5460 | } |
| 5461 | } |
| 5462 | } |
| 5463 | Ok(()) |
| 5464 | } |
| 5465 | |
| 5466 | /// Removes the timeline frames `[start, end)` from `clips`: placements inside |
| 5467 | /// it go, one straddling it is split in two, one overlapping an edge is |
| 5468 | /// trimmed. Source frames follow the trim, so what is left plays what it always |
| 5469 | /// played. Leaves the lane sorted and disjoint. |
| 5470 | /// |
| 5471 | /// A piece the hole cut is no longer the take its group id names -- and both |
| 5472 | /// halves of a straddled placement carrying that id would be the same id twice |
| 5473 | /// in one lane -- so what is cut loses its link (see [`links_are_consistent`]). |
| 5474 | fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) { |
| 5475 | let mut out = Vec::with_capacity(clips.len() + 1); |
| 5476 | for c in clips.drain(..) { |
| 5477 | // Disjoint from the hole: untouched. |
| 5478 | if c.end() <= start || c.start >= end { |
| 5479 | out.push(c); |
| 5480 | continue; |
| 5481 | } |
| 5482 | // The head that survives in front of the hole -- as much source as fits |
| 5483 | // in the room in front of it at this clip's own rate ([`Speed::fit`]), |
| 5484 | // which at real time is that room itself. Never *more*: a head that |
| 5485 | // outgrew its room would reach into the hole it is being cut out of, |
| 5486 | // which is exactly the overlap a slow clip punched at a frame its rate |
| 5487 | // cannot address used to leave (at 0.25x a single source frame is four |
| 5488 | // timeline frames, and three frames of room hold none of it). `None` |
| 5489 | // there means no remainder at all, and the piece simply goes. |
| 5490 | if let Some(keep) = c.speed.fit(start.saturating_sub(c.start)) |
| 5491 | && c.start < start |
| 5492 | { |
| 5493 | out.push(Clip { |
| 5494 | fade_in: 0, |
| 5495 | fade_out: 0, |
| 5496 | transition_out: 0, |
| 5497 | out_frame: c.in_frame + keep.min(c.len()), |
| 5498 | link: None, |
| 5499 | ..c |
| 5500 | }); |
| 5501 | } |
| 5502 | // ...and the tail behind it, which keeps reading up to where it would |
| 5503 | // have: measured from its out-point for the head's reason, so what it |
| 5504 | // occupies still ends where the whole clip did -- and dropped whole on |
| 5505 | // the same `None`. |
| 5506 | if let Some(keep) = c.speed.fit(c.end().saturating_sub(end)) |
| 5507 | && c.end() > end |
| 5508 | { |
| 5509 | out.push(Clip { |
| 5510 | fade_in: 0, |
| 5511 | fade_out: 0, |
| 5512 | transition_out: 0, |
| 5513 | start: end, |
| 5514 | in_frame: c.out_frame - keep.min(c.len()), |
| 5515 | link: None, |
| 5516 | ..c |
| 5517 | }); |
| 5518 | } |
| 5519 | } |
| 5520 | *clips = out; |
| 5521 | } |
| 5522 | |
| 5523 | /// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is |
| 5524 | /// behind it back -- the body of [`Project::ripple_delete`] (which passes every |
| 5525 | /// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes |
| 5526 | /// it was scoped to. No snapshot of its own: whose undo step this is belongs to |
| 5527 | /// the caller. |
| 5528 | fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) { |
| 5529 | for &i in on { |
| 5530 | let clips = &mut lanes[i].clips; |
| 5531 | clear(clips, at, at + len); |
| 5532 | for c in clips.iter_mut().filter(|c| c.start >= at) { |
| 5533 | c.start -= len; |
| 5534 | } |
| 5535 | debug_assert!(sorted_disjoint(clips)); |
| 5536 | // The subtitle lanes close the hole with everything else: a caption |
| 5537 | // left standing where the picture it belongs to was cut out is the |
| 5538 | // desync a lane model exists to make impossible. |
| 5539 | let subs = &mut lanes[i].subs; |
| 5540 | sub_clear(subs, at, at + len); |
| 5541 | for s in subs.iter_mut().filter(|s| s.start >= at) { |
| 5542 | s.start -= len; |
| 5543 | } |
| 5544 | debug_assert!(subs_sorted_disjoint(subs)); |
| 5545 | } |
| 5546 | } |
| 5547 | |
| 5548 | /// Every lane, as the index list the two above take: what "the whole timeline" |
| 5549 | /// is spelled as, and the scope [`Project::ripple_delete`] and |
| 5550 | /// [`Project::split`] have always had. |
| 5551 | fn all_lanes(lanes: &[LaneData]) -> Vec<usize> { |
| 5552 | (0..lanes.len()).collect() |
| 5553 | } |
| 5554 | |
| 5555 | /// A caller's region list as a batch may use it: sorted by start, empty entries |
| 5556 | /// dropped, and touching or overlapping entries merged into one. |
| 5557 | /// |
| 5558 | /// Overlapping regions are the one thing a batch cannot take -- cutting the |
| 5559 | /// second would cut frames the first already moved -- and a detector handing |
| 5560 | /// back two that touch means one silence, not two cuts. Merged rather than |
| 5561 | /// refused: this is arithmetic on a preview, not a user's mistake. |
| 5562 | fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> { |
| 5563 | let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect(); |
| 5564 | sorted.sort_by_key(|&(at, _)| at); |
| 5565 | let mut out: Vec<(u32, u32)> = Vec::new(); |
| 5566 | for (at, len) in sorted { |
| 5567 | let end = at.saturating_add(len); |
| 5568 | match out.last_mut() { |
| 5569 | Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1), |
| 5570 | _ => out.push((at, len)), |
| 5571 | } |
| 5572 | } |
| 5573 | out |
| 5574 | } |
| 5575 | |
| 5576 | /// Slides everything from `at` on later by `len`, splitting a placement that |
| 5577 | /// straddles `at` so the two halves end up on either side of the hole. The |
| 5578 | /// insert half of a rippling paste. The two halves lose the group id for the |
| 5579 | /// reason [`clear`] gives. |
| 5580 | fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) { |
| 5581 | if let Some(idx) = splittable(clips, at) { |
| 5582 | let mut tail = clips[idx]; |
| 5583 | // The cut in *source* frames, at the clip's own rate. `splittable` has |
| 5584 | // already refused a frame the rate cannot address, which is why |
| 5585 | // [`Project::paste`] refuses one too rather than opening room inside a |
| 5586 | // clip that cannot be cut there. |
| 5587 | tail.in_frame = split_source(&tail, at).expect("splittable said so"); |
| 5588 | tail.start = at; |
| 5589 | tail.link = None; |
| 5590 | clips[idx].out_frame = tail.in_frame; |
| 5591 | clips[idx].link = None; |
| 5592 | clips.insert(idx + 1, tail); |
| 5593 | } |
| 5594 | for c in clips.iter_mut().filter(|c| c.start >= at) { |
| 5595 | c.start += len; |
| 5596 | } |
| 5597 | } |
| 5598 | |
| 5599 | /// Absolute, symlink-resolved when the file is reachable; the path as given |
| 5600 | /// when it is not -- an unreadable path still deserves an index, it simply |
| 5601 | /// dedups by spelling. |
| 5602 | pub(crate) fn canonical(path: &Path) -> PathBuf { |
| 5603 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) |
| 5604 | } |
| 5605 | |
| 5606 | #[cfg(test)] |
| 5607 | mod tests { |
| 5608 | use super::*; |
| 5609 | |
| 5610 | const FPS: f64 = 30.0; |
| 5611 | /// Never opened -- `Project` is pure data, so a path that does not exist is |
| 5612 | /// simply a path that dedups by spelling. |
| 5613 | const FILE: &str = "/nonexistent/a.mp4"; |
| 5614 | const FILE2: &str = "/nonexistent/b.mp4"; |
| 5615 | |
| 5616 | /// A contiguous placement, group id ignored: what most assertions compare. |
| 5617 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip { |
| 5618 | Clip { |
| 5619 | fade_in: 0, |
| 5620 | fade_out: 0, |
| 5621 | transition_out: 0, |
| 5622 | start, |
| 5623 | in_frame, |
| 5624 | out_frame, |
| 5625 | source, |
| 5626 | link: None, |
| 5627 | eq: None, |
| 5628 | color: None, |
| 5629 | transform: None, |
| 5630 | fit: FitPolicy::default(), |
| 5631 | speed: Speed::NORMAL, |
| 5632 | } |
| 5633 | } |
| 5634 | |
| 5635 | /// A caption placement for pure timeline tests: the track window is the |
| 5636 | /// same duration as the placement, so assertions can stay in frames. |
| 5637 | fn caption(start: u32, frames: u32) -> SubClip { |
| 5638 | SubClip { |
| 5639 | start, |
| 5640 | frames, |
| 5641 | track: 0, |
| 5642 | in_us: 0, |
| 5643 | out_us: i64::from(frames) * 1_000_000, |
| 5644 | link: None, |
| 5645 | } |
| 5646 | } |
| 5647 | |
| 5648 | /// A subtitle palette row for tests that place captions on lanes. |
| 5649 | fn subtitle_track() -> SubtitleTrack { |
| 5650 | SubtitleTrack { |
| 5651 | path: FILE.into(), |
| 5652 | track: None, |
| 5653 | language: "eng".into(), |
| 5654 | name: String::new(), |
| 5655 | label: "eng".into(), |
| 5656 | cues: Vec::new(), |
| 5657 | bitmap: false, |
| 5658 | refused: None, |
| 5659 | } |
| 5660 | } |
| 5661 | |
| 5662 | /// A recognisable equalizer setting: one peak band, `n` telling two of them |
| 5663 | /// apart -- which is what makes the table's dedup and its prune visible. |
| 5664 | fn band_at(n: u32) -> EqParams { |
| 5665 | EqParams { |
| 5666 | bands: vec![crate::eq::Band { |
| 5667 | freq_hz: 1000.0, |
| 5668 | gain_db: f64::from(n) as f32 * 1.5, |
| 5669 | q: 0.707, |
| 5670 | kind: crate::eq::BandKind::Peak, |
| 5671 | }], |
| 5672 | } |
| 5673 | } |
| 5674 | |
| 5675 | /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`] |
| 5676 | /// for the colour table. |
| 5677 | fn grade_at(n: u32) -> ColorParams { |
| 5678 | ColorParams { |
| 5679 | brightness: f64::from(n) as f32 * 0.05, |
| 5680 | ..Default::default() |
| 5681 | } |
| 5682 | } |
| 5683 | |
| 5684 | /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s |
| 5685 | /// twin for the transform table. |
| 5686 | fn transform_at(n: u32) -> TransformParams { |
| 5687 | TransformParams { |
| 5688 | pos_x: f64::from(n) as f32 * 0.05, |
| 5689 | ..Default::default() |
| 5690 | } |
| 5691 | } |
| 5692 | |
| 5693 | /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`]. |
| 5694 | fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> { |
| 5695 | vec![(LaneKind::Video, video), (LaneKind::Audio, audio)] |
| 5696 | } |
| 5697 | |
| 5698 | /// Every lane with its group ids blanked, for comparing shape. |
| 5699 | fn shape(p: &Project) -> Vec<Vec<Clip>> { |
| 5700 | p.lanes() |
| 5701 | .into_iter() |
| 5702 | .map(|l| { |
| 5703 | p.lane(l) |
| 5704 | .iter() |
| 5705 | .map(|c| Clip { link: None, ..*c }) |
| 5706 | .collect() |
| 5707 | }) |
| 5708 | .collect() |
| 5709 | } |
| 5710 | |
| 5711 | /// The *source frame* every timeline frame reads, per lane -- the traversal |
| 5712 | /// a player performs. Deliberately not the clip index: a split changes which |
| 5713 | /// clip a frame belongs to, and nothing else. |
| 5714 | fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> { |
| 5715 | (0..p.timeline_frames() + 2) |
| 5716 | .map(|f| { |
| 5717 | p.lanes() |
| 5718 | .into_iter() |
| 5719 | .map(|l| p.map(l, f).map(|(_, source)| source)) |
| 5720 | .collect() |
| 5721 | }) |
| 5722 | .collect() |
| 5723 | } |
| 5724 | |
| 5725 | /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one |
| 5726 | /// fixture. Built through `split` so the constructor path is exercised too. |
| 5727 | fn three() -> Project { |
| 5728 | let mut p = Project::single(FILE, 9); |
| 5729 | assert!(p.split(3)); |
| 5730 | assert!(p.split(5)); |
| 5731 | assert_eq!( |
| 5732 | shape(&p), |
| 5733 | [ |
| 5734 | vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)], |
| 5735 | vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)], |
| 5736 | ] |
| 5737 | ); |
| 5738 | p |
| 5739 | } |
| 5740 | |
| 5741 | #[test] |
| 5742 | fn single_is_the_whole_file_on_both_lanes() { |
| 5743 | let p = Project::single(FILE, 150); |
| 5744 | assert_eq!(p.clips().len(), 1); |
| 5745 | assert_eq!(p.lane(Lane::A1).len(), 1); |
| 5746 | assert_eq!(p.timeline_frames(), 150); |
| 5747 | assert_eq!(p.clip_spans(), vec![(0, 150)]); |
| 5748 | // grouped: video and audio carry the same link |
| 5749 | assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link); |
| 5750 | assert!(p.clips()[0].link.is_some()); |
| 5751 | // degenerate mapping: timeline == source |
| 5752 | assert_eq!(p.map_timeline(0), Some((0, 0))); |
| 5753 | assert_eq!(p.map_timeline(149), Some((0, 149))); |
| 5754 | assert_eq!(p.map_timeline(150), None); |
| 5755 | // never-empty invariant survives a bogus frame count |
| 5756 | assert_eq!(Project::single(FILE, 0).timeline_frames(), 1); |
| 5757 | } |
| 5758 | |
| 5759 | #[test] |
| 5760 | fn split_cuts_every_lane_and_regroups_it_back() { |
| 5761 | let mut p = Project::single(FILE, 9); |
| 5762 | let before = traversal(&p); |
| 5763 | let before_shape = shape(&p); |
| 5764 | |
| 5765 | assert!(p.split(4)); |
| 5766 | for l in p.lanes() { |
| 5767 | assert_eq!(p.lane(l).len(), 2, "{} split", l.label()); |
| 5768 | } |
| 5769 | // The two sides are two groups, one per side, matching across the lanes. |
| 5770 | let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1)); |
| 5771 | assert_eq!(v[0].link, a[0].link); |
| 5772 | assert_eq!(v[1].link, a[1].link); |
| 5773 | assert_ne!(v[0].link, v[1].link, "the halves are no longer one take"); |
| 5774 | // A split changes no mapping, in either lane. |
| 5775 | assert_eq!(traversal(&p), before, "a split moves nothing"); |
| 5776 | |
| 5777 | assert!(p.regroup(4), "the inverse rejoins them"); |
| 5778 | assert_eq!(shape(&p), before_shape, "bit-exact back to one clip"); |
| 5779 | assert_eq!(traversal(&p), before); |
| 5780 | assert_eq!( |
| 5781 | p.lane(Lane::V1)[0].link, |
| 5782 | p.lane(Lane::A1)[0].link, |
| 5783 | "and the rejoined clip is one group again" |
| 5784 | ); |
| 5785 | } |
| 5786 | |
| 5787 | /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at |
| 5788 | /// the very first frame of a fade-in, unity at its last, equal-power |
| 5789 | /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches |
| 5790 | /// at all. |
| 5791 | #[test] |
| 5792 | fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() { |
| 5793 | let f = Fade { |
| 5794 | elapsed: 0, |
| 5795 | fade_in: 10, |
| 5796 | fade_out: 10, |
| 5797 | total: 40, |
| 5798 | }; |
| 5799 | assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame"); |
| 5800 | assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends"); |
| 5801 | let midpoint = std::f32::consts::FRAC_PI_2 * 0.5; |
| 5802 | assert!( |
| 5803 | (f.gain_at(5) - midpoint.sin()).abs() < 1e-6, |
| 5804 | "equal-power midpoint is sin(pi/4)" |
| 5805 | ); |
| 5806 | assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp"); |
| 5807 | // The fade-out is the same curve, mirrored, counting down from the |
| 5808 | // clip's end: unity at the frame the ramp starts, the same |
| 5809 | // equal-power midpoint, and -- since `total` itself is one past the |
| 5810 | // clip's last valid frame -- the very last frame is one step short of |
| 5811 | // the silence a fade-in's own frame `0` lands on exactly. |
| 5812 | assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts"); |
| 5813 | assert!( |
| 5814 | (f.gain_at(35) - midpoint.sin()).abs() < 1e-6, |
| 5815 | "the fade-out's own equal-power midpoint" |
| 5816 | ); |
| 5817 | assert!( |
| 5818 | (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6, |
| 5819 | "one step short of silence at the clip's last playable frame" |
| 5820 | ); |
| 5821 | } |
| 5822 | |
| 5823 | /// [`Project::crossfade`] refuses a non-audio lane and two clips that are |
| 5824 | /// not adjacent, and otherwise sets the shared edge's fades and nothing |
| 5825 | /// else. |
| 5826 | #[test] |
| 5827 | fn crossfade_only_joins_adjacent_audio_clips() { |
| 5828 | let mut p = Project::single(FILE, 20); |
| 5829 | assert!(p.split(10)); |
| 5830 | assert!( |
| 5831 | !p.crossfade(Lane::V1, 0, 5), |
| 5832 | "video is not an audio lane" |
| 5833 | ); |
| 5834 | assert!( |
| 5835 | !p.crossfade(Lane::A1, 1, 5), |
| 5836 | "there is no clip after idx 1" |
| 5837 | ); |
| 5838 | assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent"); |
| 5839 | let a = p.lane(Lane::A1); |
| 5840 | assert_eq!(a[0].fade_out, 5); |
| 5841 | assert_eq!(a[1].fade_in, 5); |
| 5842 | assert_eq!(a[0].fade_in, 0); |
| 5843 | assert_eq!(a[1].fade_out, 0); |
| 5844 | |
| 5845 | // A gap between two clips is not adjacency, even on an audio lane. |
| 5846 | let mut p2 = Project::single(FILE, 1); |
| 5847 | let a2 = p2.add_lane(LaneKind::Audio); |
| 5848 | assert!(p2.place(a2, 0, clip(0, 0, 3, 0))); |
| 5849 | assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one"); |
| 5850 | assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent"); |
| 5851 | } |
| 5852 | |
| 5853 | /// The rule [`Project::write_split`] follows for the edge the razor makes: |
| 5854 | /// the left half keeps its old [`Clip::fade_in`] (clamped to its new, |
| 5855 | /// shorter length) and loses its [`Clip::fade_out`]; the right half is the |
| 5856 | /// mirror image. |
| 5857 | #[test] |
| 5858 | fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() { |
| 5859 | let mut p = Project::single(FILE, 20); |
| 5860 | assert!(p.set_fade_in(Lane::V1, 0, 15)); |
| 5861 | assert!(p.set_fade_out(Lane::V1, 0, 15)); |
| 5862 | assert!(p.split(5)); |
| 5863 | let v = p.lane(Lane::V1); |
| 5864 | assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames"); |
| 5865 | assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat"); |
| 5866 | assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat"); |
| 5867 | assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15"); |
| 5868 | } |
| 5869 | |
| 5870 | /// [`Project::set_transition_out`] refuses a non-video lane, a clip with |
| 5871 | /// no successor, and two clips that do not touch, and otherwise clamps |
| 5872 | /// the dissolve to the shorter of the two clips it spans. |
| 5873 | #[test] |
| 5874 | fn set_transition_out_only_dissolves_adjacent_video_clips() { |
| 5875 | let mut p = Project::single(FILE, 20); |
| 5876 | assert!(p.split(15), "a short 5-frame tail to clamp against"); |
| 5877 | assert!( |
| 5878 | !p.set_transition_out(Lane::A1, 0, 5), |
| 5879 | "audio is not a video lane" |
| 5880 | ); |
| 5881 | assert!( |
| 5882 | !p.set_transition_out(Lane::V1, 1, 5), |
| 5883 | "there is no clip after idx 1" |
| 5884 | ); |
| 5885 | assert!( |
| 5886 | p.set_transition_out(Lane::V1, 0, 100), |
| 5887 | "the two halves are adjacent" |
| 5888 | ); |
| 5889 | assert_eq!( |
| 5890 | p.transition_out_of(Lane::V1, 0), |
| 5891 | 5, |
| 5892 | "clamped to the shorter neighbour's 5 frames" |
| 5893 | ); |
| 5894 | |
| 5895 | // A gap between two clips is not adjacency, even on the video lane. |
| 5896 | let mut p2 = Project::single(FILE, 1); |
| 5897 | let v2 = p2.add_lane(LaneKind::Video); |
| 5898 | assert!(p2.place(v2, 0, clip(0, 0, 3, 0))); |
| 5899 | assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one"); |
| 5900 | assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent"); |
| 5901 | } |
| 5902 | |
| 5903 | /// The rule [`Project::write_split`] follows for [`Clip::transition_out`], |
| 5904 | /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]: |
| 5905 | /// only the half that kept the clip's original *end* keeps the dissolve, |
| 5906 | /// re-clamped to its own now-shorter length; the head the cut just made |
| 5907 | /// has no successor to dissolve into and starts flat. |
| 5908 | #[test] |
| 5909 | fn a_split_clamps_the_tail_transition_and_zeroes_the_head() { |
| 5910 | let mut p = Project::single(FILE, 20); |
| 5911 | assert!( |
| 5912 | !p.set_transition_out(Lane::V1, 0, 0), |
| 5913 | "one clip on the lane, no successor to dissolve into yet" |
| 5914 | ); |
| 5915 | // Give the clip a dissolve by hand, then cut it in two. |
| 5916 | p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15; |
| 5917 | assert!(p.split(5)); |
| 5918 | let v = p.lane(Lane::V1); |
| 5919 | assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor"); |
| 5920 | assert_eq!( |
| 5921 | v[1].transition_out, 15, |
| 5922 | "the tail's kept dissolve, unclamped: 15 frames fit in 15" |
| 5923 | ); |
| 5924 | } |
| 5925 | |
| 5926 | /// The music video's own path: the take comes apart into halves that carry |
| 5927 | /// ids of their own, one undo puts it back, and two clips over the same |
| 5928 | /// frames become one take again by hand. |
| 5929 | #[test] |
| 5930 | fn a_take_comes_apart_and_goes_back_together() { |
| 5931 | let mut p = Project::single(FILE, 9); |
| 5932 | let one = p.clips()[0].link.expect("a fresh project is one take"); |
| 5933 | assert_eq!(p.lane(Lane::A1)[0].link, Some(one)); |
| 5934 | |
| 5935 | // A third lane in the same group -- and the merge case with it: a |
| 5936 | // placement is in no group, and grouping it in leaves *one* group. |
| 5937 | let v2 = p.add_lane(LaneKind::Video); |
| 5938 | assert!(p.place(v2, 0, clip(0, 0, 9, 0))); |
| 5939 | assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group"); |
| 5940 | p.group(Lane::V1, 0, v2, 0) |
| 5941 | .expect("the same frames, one lane over"); |
| 5942 | let id = p.clips()[0].link.expect("still a group"); |
| 5943 | assert!( |
| 5944 | p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)), |
| 5945 | "one id over the three, not two groups sharing a span" |
| 5946 | ); |
| 5947 | links_are_consistent(&p.lanes).expect("one id, one span"); |
| 5948 | |
| 5949 | // Detached by the sound: every half of the group, not only the two. |
| 5950 | assert!(p.ungroup(Lane::A1, 0)); |
| 5951 | let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect(); |
| 5952 | assert!( |
| 5953 | ids.iter().all(Option::is_some), |
| 5954 | "a half keeps an id of its own" |
| 5955 | ); |
| 5956 | assert!( |
| 5957 | ids.iter() |
| 5958 | .enumerate() |
| 5959 | .all(|(i, a)| ids[..i].iter().all(|b| a != b)), |
| 5960 | "and no two halves are the same group any more: {ids:?}" |
| 5961 | ); |
| 5962 | links_are_consistent(&p.lanes).expect("a lone id is legal"); |
| 5963 | |
| 5964 | // One snapshot for the whole detach. |
| 5965 | assert!(p.undo()); |
| 5966 | assert!( |
| 5967 | p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)), |
| 5968 | "one undo puts the whole group back" |
| 5969 | ); |
| 5970 | |
| 5971 | // And back together by hand: the two the pointer named, and only them. |
| 5972 | assert!(p.ungroup(Lane::V1, 0)); |
| 5973 | p.group(Lane::V1, 0, Lane::A1, 0) |
| 5974 | .expect("both cover [0, 9)"); |
| 5975 | assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link); |
| 5976 | assert_ne!( |
| 5977 | p.lane(v2)[0].link, |
| 5978 | p.lane(Lane::V1)[0].link, |
| 5979 | "the third half stayed detached" |
| 5980 | ); |
| 5981 | links_are_consistent(&p.lanes).expect("one id, one span"); |
| 5982 | } |
| 5983 | |
| 5984 | /// What a group may not be, and what a detach has nothing to take apart -- |
| 5985 | /// none of which may cost an undo step. |
| 5986 | #[test] |
| 5987 | fn a_group_is_one_span_and_one_clip_per_lane() { |
| 5988 | let mut p = three(); |
| 5989 | let before = shape(&p); |
| 5990 | let why = |r: crate::Result<()>| r.expect_err("refused").to_string(); |
| 5991 | |
| 5992 | assert!( |
| 5993 | why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"), |
| 5994 | "two clips of one lane are never one take" |
| 5995 | ); |
| 5996 | assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1")); |
| 5997 | let spans = why(p.group(Lane::V1, 0, Lane::A1, 1)); |
| 5998 | assert!( |
| 5999 | spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"), |
| 6000 | "{spans}" |
| 6001 | ); |
| 6002 | assert!( |
| 6003 | spans.contains("trim them to matching bounds first"), |
| 6004 | "{spans}" |
| 6005 | ); |
| 6006 | assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already")); |
| 6007 | |
| 6008 | // A half nothing else is grouped with is already detached, a placement |
| 6009 | // is in no group at all, and an index that is not there has nothing to |
| 6010 | // detach either. |
| 6011 | assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0))); |
| 6012 | assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group"); |
| 6013 | assert!(p.lift(Lane::A1, 0)); |
| 6014 | assert!(!p.ungroup(Lane::V1, 0), "its group has no other half"); |
| 6015 | assert!(!p.ungroup(Lane::V1, 9), "no clip there"); |
| 6016 | |
| 6017 | // Two undos, one per edit: not one of the refusals pushed a snapshot. |
| 6018 | assert!(p.undo()); |
| 6019 | assert!(p.undo()); |
| 6020 | assert_eq!(shape(&p), before); |
| 6021 | } |
| 6022 | |
| 6023 | /// Where a re-rate puts a playhead: the scene under the cursor stays the |
| 6024 | /// scene under the cursor, measured the way a viewer would -- the source |
| 6025 | /// frame playing at the playhead is the same frame after the write, at |
| 6026 | /// every playhead position the re-rate can catch one. |
| 6027 | #[test] |
| 6028 | fn a_re_rate_keeps_the_frame_under_the_playhead() { |
| 6029 | let caption = |start: u32, frames: u32| SubClip { |
| 6030 | start, |
| 6031 | frames, |
| 6032 | track: 0, |
| 6033 | in_us: 0, |
| 6034 | out_us: i64::from(frames) * 1_000_000, |
| 6035 | link: None, |
| 6036 | }; |
| 6037 | let track = || SubtitleTrack { |
| 6038 | path: FILE.into(), |
| 6039 | track: None, |
| 6040 | language: "eng".into(), |
| 6041 | name: String::new(), |
| 6042 | label: "eng".into(), |
| 6043 | cues: Vec::new(), |
| 6044 | bitmap: false, |
| 6045 | refused: None, |
| 6046 | }; |
| 6047 | // A group of a 300-frame clip and a caption offset 30 frames into it. |
| 6048 | let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]); |
| 6049 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6050 | p.place_sub(s1, 30, caption(30, 240)).expect("placed"); |
| 6051 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6052 | |
| 6053 | // The frame playing at `at`: which clip, and which source frame of it. |
| 6054 | let playing = |p: &Project, at: u32| -> Option<(usize, u32)> { |
| 6055 | p.span_at(Lane::V1, at) |
| 6056 | .and_then(|s| s.from.map(|(source, from)| (source, from))) |
| 6057 | }; |
| 6058 | |
| 6059 | // Inside the held clip: the source frame under the playhead is the |
| 6060 | // same one after the re-rate, at 2x and at half speed both. |
| 6061 | for (what, speed) in [("2x", 2000u16), ("half", 500)] { |
| 6062 | let at = 120; |
| 6063 | let before = playing(&p, at).expect("a clip under the playhead"); |
| 6064 | let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at); |
| 6065 | p.set_speed(Lane::V1, 0, Speed::from_permille(speed)) |
| 6066 | .expect("room for it"); |
| 6067 | let after = playing(&p, mapped.unwrap()).expect("still a clip there"); |
| 6068 | assert_eq!(before, after, "{what}: the same source frame plays"); |
| 6069 | // ...and the write itself is untouched by the question. |
| 6070 | assert!(p.undo(), "{what}: one step back"); |
| 6071 | } |
| 6072 | |
| 6073 | // Past the group -- the clip ends at 300 and the caption at 270, so |
| 6074 | // from 300 on nothing is re-timed under the playhead: unmoved. |
| 6075 | for at in [300u32, 301, 1_000] { |
| 6076 | assert_eq!( |
| 6077 | p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at), |
| 6078 | Some(at), |
| 6079 | "at {at}: outside every member, unmoved" |
| 6080 | ); |
| 6081 | } |
| 6082 | // The boundary is exact: the held clip's own last frame (299) maps |
| 6083 | // to its new one (149 -- the last frame inside [0, 150), where the |
| 6084 | // shrunken clip's last source frame plays), and its first stays put. |
| 6085 | assert_eq!( |
| 6086 | p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299), |
| 6087 | Some(149) |
| 6088 | ); |
| 6089 | assert_eq!( |
| 6090 | p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0), |
| 6091 | Some(0) |
| 6092 | ); |
| 6093 | // A spot the caption shares with the clip maps by the clip (it is |
| 6094 | // what is *playing* there): the held clip's own proportion, which on |
| 6095 | // this fixture is also its head. |
| 6096 | assert_eq!( |
| 6097 | p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90), |
| 6098 | Some(45), |
| 6099 | "the clip under the caption owns the spot" |
| 6100 | ); |
| 6101 | } |
| 6102 | |
| 6103 | /// A playhead inside another clip member of the group: that member keeps |
| 6104 | /// its own head, so the mapping is by its proportion and not the held |
| 6105 | /// clip's -- and the frame under the cursor is still the frame that was. |
| 6106 | #[test] |
| 6107 | fn a_re_rate_maps_a_second_clip_member_about_its_own_head() { |
| 6108 | let mut p = Project::single(FILE, 300); |
| 6109 | // A second clip, grouped with the first but starting 300 later: the |
| 6110 | // head the group shares and its own differ by exactly that. |
| 6111 | let v2 = p.add_lane(LaneKind::Video); |
| 6112 | assert!(p.lift(Lane::A1, 0), "the sound half stands aside"); |
| 6113 | assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2"); |
| 6114 | p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped"); |
| 6115 | |
| 6116 | let at = 450; // inside the second member, 150 past its head |
| 6117 | let before = p.span_at(v2, at).and_then(|s| s.from); |
| 6118 | let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at); |
| 6119 | p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) |
| 6120 | .expect("room for it"); |
| 6121 | let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from); |
| 6122 | assert_eq!(before, after, "the second member's own frame plays"); |
| 6123 | // ...and the mapping itself: 150 past its head halves, the head stays. |
| 6124 | assert_eq!(mapped, Some(375)); |
| 6125 | } |
| 6126 | |
| 6127 | /// The link counter a load seeds sits past every id the file names, |
| 6128 | /// captions included: a hand-grouped caption may carry the highest id there |
| 6129 | /// is, and a counter that read the clips alone would hand it to the next |
| 6130 | /// group that asked -- silently grouping the caption with clips it never |
| 6131 | /// met. |
| 6132 | #[test] |
| 6133 | fn the_link_counter_sits_past_a_caption_only_id() { |
| 6134 | let track = || SubtitleTrack { |
| 6135 | path: FILE.into(), |
| 6136 | track: None, |
| 6137 | language: "eng".into(), |
| 6138 | name: String::new(), |
| 6139 | label: "eng".into(), |
| 6140 | cues: Vec::new(), |
| 6141 | bitmap: false, |
| 6142 | refused: None, |
| 6143 | }; |
| 6144 | let mut p = Project::single(FILE, 9); |
| 6145 | p.add_lane(LaneKind::Subtitle); |
| 6146 | let caption = SubClip { |
| 6147 | start: 0, |
| 6148 | frames: 6, |
| 6149 | track: 0, |
| 6150 | in_us: 0, |
| 6151 | out_us: 6_000_000, |
| 6152 | // The highest id in the file, and only a caption carries it. |
| 6153 | link: Some(1), |
| 6154 | }; |
| 6155 | let mut p = p |
| 6156 | .with_subtitles(vec![track()]) |
| 6157 | .with_subs(vec![Vec::new(), Vec::new(), vec![caption]]) |
| 6158 | .expect("a caption may carry the file's highest id"); |
| 6159 | |
| 6160 | // A new group on lanes the caption is not on mints the next id -- which |
| 6161 | // must not be the caption's. |
| 6162 | let v2 = p.add_lane(LaneKind::Video); |
| 6163 | assert!(p.place(v2, 0, clip(0, 0, 9, 0))); |
| 6164 | p.group_all(&[(Lane::V1, 0), (v2, 0)]) |
| 6165 | .expect("the clips group"); |
| 6166 | let minted = p.lane(Lane::V1)[0].link.expect("grouped"); |
| 6167 | assert_ne!( |
| 6168 | minted, |
| 6169 | 1, |
| 6170 | "the caption's id is not re-issued to clips" |
| 6171 | ); |
| 6172 | assert_eq!( |
| 6173 | p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link, |
| 6174 | Some(1), |
| 6175 | "the caption keeps its own group" |
| 6176 | ); |
| 6177 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6178 | } |
| 6179 | |
| 6180 | /// A rate re-times the caption members of the group by the ratio it gives |
| 6181 | /// the held clip: the span on the timeline compresses about the held clip's |
| 6182 | /// head, the words' own window untouched -- and one undo puts it back. |
| 6183 | #[test] |
| 6184 | fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() { |
| 6185 | let caption = |start: u32, frames: u32| SubClip { |
| 6186 | start, |
| 6187 | frames, |
| 6188 | track: 0, |
| 6189 | in_us: 0, |
| 6190 | out_us: i64::from(frames) * 1_000_000, |
| 6191 | link: None, |
| 6192 | }; |
| 6193 | let track = || SubtitleTrack { |
| 6194 | path: FILE.into(), |
| 6195 | track: None, |
| 6196 | language: "eng".into(), |
| 6197 | name: String::new(), |
| 6198 | label: "eng".into(), |
| 6199 | cues: Vec::new(), |
| 6200 | bitmap: false, |
| 6201 | refused: None, |
| 6202 | }; |
| 6203 | let grouped = || { |
| 6204 | let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]); |
| 6205 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6206 | p.place_sub(s1, 0, caption(0, 90)).expect("placed"); |
| 6207 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6208 | (p, s1) |
| 6209 | }; |
| 6210 | |
| 6211 | // An aligned take, doubled: the caption plays in half the frames. |
| 6212 | let (mut p, s1) = grouped(); |
| 6213 | p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) |
| 6214 | .expect("room for it"); |
| 6215 | assert_eq!(p.lane(Lane::V1)[0].frames(), 45); |
| 6216 | let s = p.sub_lane(s1)[0]; |
| 6217 | assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline"); |
| 6218 | assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched"); |
| 6219 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6220 | assert!(p.undo()); |
| 6221 | assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back"); |
| 6222 | |
| 6223 | // An offset group, slowed to half: the caption's *offset from the held |
| 6224 | // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at |
| 6225 | // 0.5x, and still ends where the clip does. |
| 6226 | let (mut p, s1) = grouped(); |
| 6227 | p.lift_sub(s1, 0); |
| 6228 | p.place_sub(s1, 30, caption(30, 60)).expect("placed"); |
| 6229 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6230 | p.set_speed(Lane::V1, 0, Speed::from_permille(500)) |
| 6231 | .expect("room for it"); |
| 6232 | assert_eq!(p.lane(Lane::V1)[0].frames(), 180); |
| 6233 | let s = p.sub_lane(s1)[0]; |
| 6234 | assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip"); |
| 6235 | assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip"); |
| 6236 | |
| 6237 | // A stretch that runs the caption into its neighbour is refused, by |
| 6238 | // lane and frame, and costs no undo step. |
| 6239 | let (mut p, s1) = grouped(); |
| 6240 | p.lift_sub(s1, 0); |
| 6241 | p.place_sub(s1, 0, caption(0, 90)).expect("placed"); |
| 6242 | p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour"); |
| 6243 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6244 | let history = p.history.len(); |
| 6245 | let err = p |
| 6246 | .set_speed(Lane::V1, 0, Speed::from_permille(500)) |
| 6247 | .unwrap_err() |
| 6248 | .to_string(); |
| 6249 | assert!( |
| 6250 | err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"), |
| 6251 | "{err}" |
| 6252 | ); |
| 6253 | assert_eq!(p.history.len(), history, "a refusal costs no undo step"); |
| 6254 | } |
| 6255 | |
| 6256 | /// The silence scan's speed-up re-times the captions on a scoped lane with |
| 6257 | /// everything else: the piece inside the region plays in the region's new |
| 6258 | /// frames, and what sits behind the region slides up with the clips. |
| 6259 | #[test] |
| 6260 | fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() { |
| 6261 | let caption = |start: u32, frames: u32| SubClip { |
| 6262 | start, |
| 6263 | frames, |
| 6264 | track: 0, |
| 6265 | in_us: 0, |
| 6266 | out_us: i64::from(frames) * 1_000_000, |
| 6267 | link: None, |
| 6268 | }; |
| 6269 | let track = || SubtitleTrack { |
| 6270 | path: FILE.into(), |
| 6271 | track: None, |
| 6272 | language: "eng".into(), |
| 6273 | name: String::new(), |
| 6274 | label: "eng".into(), |
| 6275 | cues: Vec::new(), |
| 6276 | bitmap: false, |
| 6277 | refused: None, |
| 6278 | }; |
| 6279 | let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]); |
| 6280 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6281 | // Words over the region [30, 60) and words behind it. |
| 6282 | p.place_sub(s1, 30, caption(30, 30)).expect("placed"); |
| 6283 | p.place_sub(s1, 60, caption(60, 30)).expect("placed"); |
| 6284 | |
| 6285 | // The region [30, 60) plays at 4x: 30 frames become 8, everything |
| 6286 | // behind slides up 22. |
| 6287 | // The scope is what the card's Take row says, caption lane included. |
| 6288 | p.speed_regions( |
| 6289 | &[(30, 30)], |
| 6290 | Speed::from_permille(4000), |
| 6291 | &[Lane::V1, Lane::A1, s1], |
| 6292 | ) |
| 6293 | .expect("the region speeds up"); |
| 6294 | let subs = p.sub_lane(s1); |
| 6295 | assert_eq!( |
| 6296 | (subs[0].start, subs[0].frames), |
| 6297 | (30, 8), |
| 6298 | "the piece inside plays in the region's new frames" |
| 6299 | ); |
| 6300 | assert_eq!( |
| 6301 | (subs[1].start, subs[1].frames), |
| 6302 | (38, 30), |
| 6303 | "the piece behind slides up by what the region gave back" |
| 6304 | ); |
| 6305 | assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs)); |
| 6306 | } |
| 6307 | |
| 6308 | /// [`Project::speeded_playhead`]'s caption arm fires only when the |
| 6309 | /// playhead is inside a caption member and outside every clip member -- |
| 6310 | /// a shape every other fixture avoids by keeping its caption inside the |
| 6311 | /// held clip. Here the caption overhangs the clip's tail, and the |
| 6312 | /// playhead standing in that overhang is answered by the caption's own |
| 6313 | /// piece: it scales about the held clip's head by the held clip's own |
| 6314 | /// proportion, same as [`write_speed`](Project::write_speed) re-times it. |
| 6315 | #[test] |
| 6316 | fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() { |
| 6317 | let caption = |start: u32, frames: u32| SubClip { |
| 6318 | start, |
| 6319 | frames, |
| 6320 | track: 0, |
| 6321 | in_us: 0, |
| 6322 | out_us: i64::from(frames) * 1_000_000, |
| 6323 | link: None, |
| 6324 | }; |
| 6325 | let track = || SubtitleTrack { |
| 6326 | path: FILE.into(), |
| 6327 | track: None, |
| 6328 | language: "eng".into(), |
| 6329 | name: String::new(), |
| 6330 | label: "eng".into(), |
| 6331 | cues: Vec::new(), |
| 6332 | bitmap: false, |
| 6333 | refused: None, |
| 6334 | }; |
| 6335 | let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]); |
| 6336 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6337 | // The caption spans [80, 100) -- ten frames past the clip's own end |
| 6338 | // at 90 -- grouped with the clip so it re-times by the clip's ratio. |
| 6339 | p.place_sub(s1, 80, caption(80, 20)).expect("placed"); |
| 6340 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6341 | // At 2x the clip halves to 45 frames; the overhang frame 95, which |
| 6342 | // no clip member's old span reaches, is the caption's own question: |
| 6343 | // half of 95 is 47.5, rounded to 48. |
| 6344 | assert_eq!( |
| 6345 | p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95), |
| 6346 | Some(48), |
| 6347 | "the overhang frame answers through the caption's own piece" |
| 6348 | ); |
| 6349 | } |
| 6350 | |
| 6351 | /// `write_speed` and `speeded_playhead` are two questions of the SAME |
| 6352 | /// map ([`map`]'s architecture law): a caption's landed span comes from |
| 6353 | /// the map's own ends, and the playhead standing at the caption's own |
| 6354 | /// last frame before the write has to land exactly where the write put |
| 6355 | /// it -- across clip lengths and rates that round differently, and an |
| 6356 | /// odd-length caption straddling the clip's own tail edge, the corner |
| 6357 | /// where `write_speed` used to answer a frame short. |
| 6358 | #[test] |
| 6359 | fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() { |
| 6360 | let caption = |start: u32, frames: u32| SubClip { |
| 6361 | start, |
| 6362 | frames, |
| 6363 | track: 0, |
| 6364 | in_us: 0, |
| 6365 | out_us: i64::from(frames) * 1_000_000, |
| 6366 | link: None, |
| 6367 | }; |
| 6368 | let track = || SubtitleTrack { |
| 6369 | path: FILE.into(), |
| 6370 | track: None, |
| 6371 | language: "eng".into(), |
| 6372 | name: String::new(), |
| 6373 | label: "eng".into(), |
| 6374 | cues: Vec::new(), |
| 6375 | bitmap: false, |
| 6376 | refused: None, |
| 6377 | }; |
| 6378 | for &len in &[90u32, 91, 177, 300, 301] { |
| 6379 | for &permille in &[500u16, 2000, 2500, 3000] { |
| 6380 | let mut p = Project::single(FILE, len).with_subtitles(vec![track()]); |
| 6381 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6382 | // An odd-length caption straddling the clip's tail edge: its |
| 6383 | // own last frame lands past the held clip. |
| 6384 | let c_start = len.saturating_sub(3); |
| 6385 | p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed"); |
| 6386 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6387 | let speed = Speed::from_permille(permille); |
| 6388 | let last = c_start + 7 - 1; |
| 6389 | let mapped = p |
| 6390 | .speeded_playhead(Lane::V1, 0, speed, last) |
| 6391 | .expect("the caption is there"); |
| 6392 | if p.set_speed(Lane::V1, 0, speed).is_err() { |
| 6393 | continue; // a refusal changes nothing: not this law's cell |
| 6394 | } |
| 6395 | let landed = p.sub_lane(s1)[0]; |
| 6396 | if permille >= 1000 { |
| 6397 | // A speed-up compresses the timeline: many old frames |
| 6398 | // share one new frame, so the caption's own last old |
| 6399 | // frame lands flush with the write's own boundary -- |
| 6400 | // the exact law [`write_speed`]'s worked drift-fix case |
| 6401 | // is stated against. |
| 6402 | assert_eq!( |
| 6403 | mapped, |
| 6404 | landed.end() - 1, |
| 6405 | "len {len} permille {permille}: the playhead at the caption's own \ |
| 6406 | last frame lands where the write actually put it" |
| 6407 | ); |
| 6408 | } else { |
| 6409 | // A slow-down expands it: one old frame becomes several |
| 6410 | // new ones, and `apply` answers where that frame's own |
| 6411 | // block *starts*, not where the caption's last new |
| 6412 | // frame (the end of that same block) sits -- a |
| 6413 | // one-frame gap inherent to the piece's own semantics, |
| 6414 | // not a drift between the two callers. Both still have |
| 6415 | // to agree the answer sits inside the caption the write |
| 6416 | // actually landed. |
| 6417 | assert!( |
| 6418 | (landed.start..landed.end()).contains(&mapped), |
| 6419 | "len {len} permille {permille}: the playhead lands inside the \ |
| 6420 | caption the write actually put ({landed:?}), got {mapped}" |
| 6421 | ); |
| 6422 | } |
| 6423 | } |
| 6424 | } |
| 6425 | } |
| 6426 | |
| 6427 | /// A grouped caption's cues re-time with its clip: the placement's window |
| 6428 | /// crossed the timeline at its own proportion before any rate, and a |
| 6429 | /// re-rate changes that proportion (the frames compress, the window does |
| 6430 | /// not). A cue eight seconds into a window played at 2x crosses the screen |
| 6431 | /// four seconds in -- and at unity every cue lands exactly where it always |
| 6432 | /// did, byte for byte. |
| 6433 | #[test] |
| 6434 | fn a_grouped_captions_cues_re_time_with_its_clip() { |
| 6435 | let track = SubtitleTrack { |
| 6436 | path: FILE.into(), |
| 6437 | track: None, |
| 6438 | language: "eng".into(), |
| 6439 | name: String::new(), |
| 6440 | label: "eng".into(), |
| 6441 | cues: vec![crate::subtitle::Cue { |
| 6442 | start_us: 8_000_000, |
| 6443 | end_us: 9_000_000, |
| 6444 | text: "late line".into(), |
| 6445 | image: None, |
| 6446 | }], |
| 6447 | bitmap: false, |
| 6448 | refused: None, |
| 6449 | }; |
| 6450 | let mut p = Project::single(FILE, 300).with_subtitles(vec![track]); |
| 6451 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6452 | // Ten seconds of the track over ten seconds of timeline: unity. |
| 6453 | p.place_sub( |
| 6454 | s1, |
| 6455 | 0, |
| 6456 | SubClip { |
| 6457 | start: 0, |
| 6458 | frames: 300, |
| 6459 | track: 0, |
| 6460 | in_us: 0, |
| 6461 | out_us: 10_000_000, |
| 6462 | link: None, |
| 6463 | }, |
| 6464 | ) |
| 6465 | .expect("placed"); |
| 6466 | |
| 6467 | // Unity: the cue sits at its own [8s, 9s), to the microsecond. |
| 6468 | let unity = p.sub_lane_cues(s1, FPS); |
| 6469 | assert_eq!( |
| 6470 | unity |
| 6471 | .iter() |
| 6472 | .map(|c| (c.start_us, c.end_us, &*c.text)) |
| 6473 | .collect::<Vec<_>>(), |
| 6474 | [(8_000_000, 9_000_000, "late line")], |
| 6475 | "a unity placement maps exactly as it always did" |
| 6476 | ); |
| 6477 | |
| 6478 | // Grouped with the clip and re-rated to 2x: the same window now crosses |
| 6479 | // in half the time, so the cue at 8s of it lands 4s in. |
| 6480 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6481 | p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) |
| 6482 | .expect("room for it"); |
| 6483 | let re_timed = p.sub_lane_cues(s1, FPS); |
| 6484 | assert_eq!( |
| 6485 | re_timed |
| 6486 | .iter() |
| 6487 | .map(|c| (c.start_us, c.end_us)) |
| 6488 | .collect::<Vec<_>>(), |
| 6489 | [(4_000_000, 4_500_000)], |
| 6490 | "the cue crosses with the clip's new rate" |
| 6491 | ); |
| 6492 | } |
| 6493 | |
| 6494 | /// A video arriving on a timeline of words mutates none of them: the |
| 6495 | /// import's rippling insert used to open room on the subtitle lanes too, |
| 6496 | /// splitting a caption it landed inside and sliding the rest behind the |
| 6497 | /// video -- the hand asked for an add, and got a cut it never made. The |
| 6498 | /// words keep their own clock; co-travel is what a group is for. |
| 6499 | #[test] |
| 6500 | fn an_arriving_clip_never_touches_the_captions() { |
| 6501 | let caption = |start: u32, frames: u32| SubClip { |
| 6502 | start, |
| 6503 | frames, |
| 6504 | track: 0, |
| 6505 | in_us: i64::from(start) * 1_000_000 / 30, |
| 6506 | out_us: i64::from(start + frames) * 1_000_000 / 30, |
| 6507 | link: None, |
| 6508 | }; |
| 6509 | let track = || SubtitleTrack { |
| 6510 | path: FILE.into(), |
| 6511 | track: None, |
| 6512 | language: "eng".into(), |
| 6513 | name: String::new(), |
| 6514 | label: "eng".into(), |
| 6515 | cues: Vec::new(), |
| 6516 | bitmap: false, |
| 6517 | refused: None, |
| 6518 | }; |
| 6519 | // A timeline of words alone: 60 frames of caption, no media clips. |
| 6520 | let mut p = Project::single(FILE, 60) |
| 6521 | .with_subtitles(vec![track()]); |
| 6522 | for l in [Lane::V1, Lane::A1] { |
| 6523 | while !p.lane(l).is_empty() { |
| 6524 | p.lift(l, 0); |
| 6525 | } |
| 6526 | } |
| 6527 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6528 | p.place_sub(s1, 0, caption(0, 60)).expect("placed"); |
| 6529 | let before = p.sub_lane(s1).to_vec(); |
| 6530 | |
| 6531 | // The video lands BEFORE the caption's span: nothing moves. |
| 6532 | let vid = clip(0, 0, 30, 0); |
| 6533 | assert!(p.paste(0, vid), "the video goes down at the head"); |
| 6534 | assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock"); |
| 6535 | |
| 6536 | // ...and OVERLAPPING it, dead centre: no split, no shift, byte for |
| 6537 | // byte the placement the hand made. |
| 6538 | assert!(p.paste(15, vid), "a second video lands inside the caption"); |
| 6539 | assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved"); |
| 6540 | assert_eq!(p.sub_lane(s1).len(), 1, "and uncut"); |
| 6541 | assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed"); |
| 6542 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6543 | } |
| 6544 | |
| 6545 | /// The region's caption pieces re-time by mapped boundaries forced apart: |
| 6546 | /// rounding start and length independently can land two cues on one frame, |
| 6547 | /// and the artifact is clamped -- one frame each, in order, none past the |
| 6548 | /// region's new end -- never an overlap on the lane. |
| 6549 | #[test] |
| 6550 | fn a_regions_caption_pieces_never_round_onto_one_another() { |
| 6551 | let caption = |start: u32, frames: u32| SubClip { |
| 6552 | start, |
| 6553 | frames, |
| 6554 | track: 0, |
| 6555 | in_us: 0, |
| 6556 | out_us: i64::from(frames) * 1_000_000, |
| 6557 | link: None, |
| 6558 | }; |
| 6559 | let track = |n| SubtitleTrack { |
| 6560 | path: FILE.into(), |
| 6561 | track: None, |
| 6562 | language: "eng".into(), |
| 6563 | name: String::new(), |
| 6564 | label: format!("eng{n}"), |
| 6565 | cues: Vec::new(), |
| 6566 | bitmap: false, |
| 6567 | refused: None, |
| 6568 | }; |
| 6569 | // Three lanes, one repro shape each: adjacent one-frame cues, a |
| 6570 | // three-frame pair, and the region's last cue against the first |
| 6571 | // caption behind it. The region [0, 30) plays at 2x: 15 frames. |
| 6572 | let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]); |
| 6573 | let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect(); |
| 6574 | p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed"); |
| 6575 | p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed"); |
| 6576 | p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed"); |
| 6577 | p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed"); |
| 6578 | p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed"); |
| 6579 | p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed"); |
| 6580 | |
| 6581 | let mut scope = vec![Lane::V1, Lane::A1]; |
| 6582 | scope.extend(lanes.iter().copied()); |
| 6583 | p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope) |
| 6584 | .expect("the region speeds up"); |
| 6585 | // Adjacent one-frame cues: both map to frame 5, and are forced apart. |
| 6586 | let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> { |
| 6587 | p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect() |
| 6588 | }; |
| 6589 | assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order"); |
| 6590 | // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6), |
| 6591 | // and the walk pushes the second to where the first ends. |
| 6592 | assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order"); |
| 6593 | // The last cue of the region ends exactly where the region now does |
| 6594 | // (frame 15), and the caption behind it lands on that same frame: |
| 6595 | // touching, never overlapping. |
| 6596 | assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region"); |
| 6597 | for &lane in &lanes { |
| 6598 | assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs)); |
| 6599 | } |
| 6600 | } |
| 6601 | |
| 6602 | /// The scope law names a caption half too: a scoped cut that would move one |
| 6603 | // track of a group whose caption sits outside the scope is refused. |
| 6604 | #[test] |
| 6605 | fn the_scope_law_refuses_a_caption_half_outside_the_scope() { |
| 6606 | let caption = |start: u32, frames: u32| SubClip { |
| 6607 | start, |
| 6608 | frames, |
| 6609 | track: 0, |
| 6610 | in_us: 0, |
| 6611 | out_us: i64::from(frames) * 1_000_000, |
| 6612 | link: None, |
| 6613 | }; |
| 6614 | let track = || SubtitleTrack { |
| 6615 | path: FILE.into(), |
| 6616 | track: None, |
| 6617 | language: "eng".into(), |
| 6618 | name: String::new(), |
| 6619 | label: "eng".into(), |
| 6620 | cues: Vec::new(), |
| 6621 | bitmap: false, |
| 6622 | refused: None, |
| 6623 | }; |
| 6624 | let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]); |
| 6625 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6626 | p.place_sub(s1, 0, caption(0, 90)).expect("placed"); |
| 6627 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6628 | |
| 6629 | // The subtitle lane is not in the scope, so the group's caption half |
| 6630 | // sits outside it: refused, in the law's own words. |
| 6631 | let err = p |
| 6632 | .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1]) |
| 6633 | .unwrap_err() |
| 6634 | .to_string(); |
| 6635 | assert!( |
| 6636 | err.contains("is one take with the S1 caption at frame 0"), |
| 6637 | "{err}" |
| 6638 | ); |
| 6639 | |
| 6640 | // ...and with the caption's lane in the scope, the cut carries it: |
| 6641 | // the words over the hole go, and the words behind slide up. |
| 6642 | p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1]) |
| 6643 | .expect("the whole group is in the scope"); |
| 6644 | let subs = p.sub_lane(s1); |
| 6645 | assert_eq!( |
| 6646 | subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(), |
| 6647 | [(0, 10), (10, 75)], |
| 6648 | "the caption is cut and shifted with the clips" |
| 6649 | ); |
| 6650 | } |
| 6651 | |
| 6652 | /// The caption a hand groups: `group_all` over clips *and* a caption, the |
| 6653 | /// mates riding along, the offsets kept, the refusals in words. |
| 6654 | #[test] |
| 6655 | fn a_hand_built_group_holds_clips_and_a_caption() { |
| 6656 | let caption = |start: u32, frames: u32| SubClip { |
| 6657 | start, |
| 6658 | frames, |
| 6659 | track: 0, |
| 6660 | in_us: 0, |
| 6661 | out_us: i64::from(frames) * 1_000_000, |
| 6662 | link: None, |
| 6663 | }; |
| 6664 | let track = || SubtitleTrack { |
| 6665 | path: FILE.into(), |
| 6666 | track: None, |
| 6667 | language: "eng".into(), |
| 6668 | name: String::new(), |
| 6669 | label: "eng".into(), |
| 6670 | cues: Vec::new(), |
| 6671 | bitmap: false, |
| 6672 | refused: None, |
| 6673 | }; |
| 6674 | let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]); |
| 6675 | let v2 = p.add_lane(LaneKind::Video); |
| 6676 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6677 | // A layer at its own offset, and a caption over the head of the take. |
| 6678 | assert!(p.place(v2, 2, clip(2, 0, 7, 0))); |
| 6679 | p.place_sub(s1, 0, caption(0, 6)).expect("placed"); |
| 6680 | |
| 6681 | // Too few, one lane twice, and an index that is not there: words, no |
| 6682 | // snapshot. |
| 6683 | let history = p.history.len(); |
| 6684 | assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more")); |
| 6685 | assert!(p |
| 6686 | .group_all(&[(Lane::V1, 0), (Lane::V1, 0)]) |
| 6687 | .unwrap_err() |
| 6688 | .to_string() |
| 6689 | .contains("V1 is picked twice")); |
| 6690 | assert!(p |
| 6691 | .group_all(&[(Lane::V1, 0), (s1, 9)]) |
| 6692 | .unwrap_err() |
| 6693 | .to_string() |
| 6694 | .contains("no subtitle 9")); |
| 6695 | assert_eq!(p.history.len(), history, "refusals cost no undo step"); |
| 6696 | |
| 6697 | // The group: the picture, the layer, and the caption -- and the sound |
| 6698 | // the picture was already grouped with comes along unasked. |
| 6699 | p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)]) |
| 6700 | .expect("three picks, three lanes"); |
| 6701 | let id = p.lane(Lane::V1)[0].link.expect("grouped"); |
| 6702 | for lane in [Lane::V1, Lane::A1, v2] { |
| 6703 | assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label()); |
| 6704 | } |
| 6705 | assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member"); |
| 6706 | assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept"); |
| 6707 | assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept"); |
| 6708 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6709 | assert_eq!(p.history.len(), history + 1, "one snapshot for the group"); |
| 6710 | |
| 6711 | // ...and one undo takes it apart again. |
| 6712 | assert!(p.undo()); |
| 6713 | assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again"); |
| 6714 | |
| 6715 | // Detach names a caption like it names a clip: every member an id of |
| 6716 | // its own, which is never `None` (see `ungroup`). |
| 6717 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks"); |
| 6718 | assert!(p.ungroup(s1, 0)); |
| 6719 | let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link); |
| 6720 | assert!(loose_sub.is_some() && loose_clip.is_some()); |
| 6721 | assert_ne!(loose_sub, loose_clip); |
| 6722 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6723 | } |
| 6724 | |
| 6725 | /// Two captions on one sub lane, each already grouped with a *different* |
| 6726 | /// clip: `group_all` over both those clips would merge the two existing |
| 6727 | /// groups into one id and leave both captions on `s1` carrying it -- |
| 6728 | /// `links_are_consistent`'s one-member-per-lane law broken the moment the |
| 6729 | /// group closes. Refused by name, and nothing moves. |
| 6730 | #[test] |
| 6731 | fn group_all_refuses_a_merge_that_doubles_up_a_lane() { |
| 6732 | let caption = |start: u32, frames: u32| SubClip { |
| 6733 | start, |
| 6734 | frames, |
| 6735 | track: 0, |
| 6736 | in_us: 0, |
| 6737 | out_us: i64::from(frames) * 1_000_000, |
| 6738 | link: None, |
| 6739 | }; |
| 6740 | let track = || SubtitleTrack { |
| 6741 | path: FILE.into(), |
| 6742 | track: None, |
| 6743 | language: "eng".into(), |
| 6744 | name: String::new(), |
| 6745 | label: "eng".into(), |
| 6746 | cues: Vec::new(), |
| 6747 | bitmap: false, |
| 6748 | refused: None, |
| 6749 | }; |
| 6750 | let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]); |
| 6751 | let v2 = p.add_lane(LaneKind::Video); |
| 6752 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6753 | assert!(p.place(v2, 0, clip(0, 0, 90, 0))); |
| 6754 | p.place_sub(s1, 0, caption(0, 30)).expect("placed"); |
| 6755 | p.place_sub(s1, 30, caption(30, 30)).expect("placed"); |
| 6756 | // V1 grouped with the first caption, v2 with the second -- two |
| 6757 | // separate groups, each already one member per lane. |
| 6758 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6759 | p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped"); |
| 6760 | let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link); |
| 6761 | |
| 6762 | let history = p.history.len(); |
| 6763 | let err = p |
| 6764 | .group_all(&[(Lane::V1, 0), (v2, 0)]) |
| 6765 | .unwrap_err() |
| 6766 | .to_string(); |
| 6767 | assert!(err.contains("one placement per lane"), "{err}"); |
| 6768 | assert_eq!(p.history.len(), history, "the refusal costs no undo step"); |
| 6769 | assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched"); |
| 6770 | assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched"); |
| 6771 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6772 | } |
| 6773 | |
| 6774 | /// A split hands the caption of a group the same ids it hands the clips: |
| 6775 | /// the left halves keep the group, the right halves share a fresh one. |
| 6776 | #[test] |
| 6777 | fn a_split_cuts_a_grouped_caption_with_its_clips() { |
| 6778 | let caption = |start: u32, frames: u32| SubClip { |
| 6779 | start, |
| 6780 | frames, |
| 6781 | track: 0, |
| 6782 | in_us: 0, |
| 6783 | out_us: i64::from(frames) * 1_000_000, |
| 6784 | link: None, |
| 6785 | }; |
| 6786 | let track = || SubtitleTrack { |
| 6787 | path: FILE.into(), |
| 6788 | track: None, |
| 6789 | language: "eng".into(), |
| 6790 | name: String::new(), |
| 6791 | label: "eng".into(), |
| 6792 | cues: Vec::new(), |
| 6793 | bitmap: false, |
| 6794 | refused: None, |
| 6795 | }; |
| 6796 | let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]); |
| 6797 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6798 | p.place_sub(s1, 0, caption(0, 9)).expect("placed"); |
| 6799 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6800 | let take = p.lane(Lane::V1)[0].link.expect("the group id"); |
| 6801 | |
| 6802 | assert!(p.split(4)); |
| 6803 | let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]); |
| 6804 | assert_eq!(left.link, Some(take), "the caption's head keeps the group"); |
| 6805 | assert_eq!(left.frames, 4); |
| 6806 | assert_eq!( |
| 6807 | right.link, |
| 6808 | p.lane(Lane::V1)[1].link, |
| 6809 | "the caption's tail shares the clips' fresh id" |
| 6810 | ); |
| 6811 | assert_ne!(right.link, Some(take)); |
| 6812 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6813 | |
| 6814 | // Regroup at the seam restores the take, caption included. |
| 6815 | assert!(p.regroup(4)); |
| 6816 | assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined"); |
| 6817 | assert_eq!(p.sub_lane(s1)[0].link, Some(take)); |
| 6818 | } |
| 6819 | |
| 6820 | /// Deleting a member of a hand-built group takes the group: every |
| 6821 | /// member's own span out of its own lane, hole closed -- the lanes may |
| 6822 | /// end up out of step, which is what one undo restores together. |
| 6823 | #[test] |
| 6824 | fn deleting_a_grouped_clip_ripples_every_members_own_lane() { |
| 6825 | let caption = |start: u32, frames: u32| SubClip { |
| 6826 | start, |
| 6827 | frames, |
| 6828 | track: 0, |
| 6829 | in_us: 0, |
| 6830 | out_us: i64::from(frames) * 1_000_000, |
| 6831 | link: None, |
| 6832 | }; |
| 6833 | let track = || SubtitleTrack { |
| 6834 | path: FILE.into(), |
| 6835 | track: None, |
| 6836 | language: "eng".into(), |
| 6837 | name: String::new(), |
| 6838 | label: "eng".into(), |
| 6839 | cues: Vec::new(), |
| 6840 | bitmap: false, |
| 6841 | refused: None, |
| 6842 | }; |
| 6843 | let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]); |
| 6844 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6845 | p.place_sub(s1, 2, caption(2, 4)).expect("placed"); |
| 6846 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6847 | // A neighbour on a lane the group does not touch. |
| 6848 | let v2 = p.add_lane(LaneKind::Video); |
| 6849 | assert!(p.place(v2, 10, clip(10, 0, 3, 0))); |
| 6850 | |
| 6851 | // By the picture or by the caption, the same whole-group delete. |
| 6852 | assert!(p.delete_sub_in(s1, 0)); |
| 6853 | assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1"); |
| 6854 | assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane"); |
| 6855 | assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays"); |
| 6856 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6857 | assert!(p.undo(), "one step puts the group back"); |
| 6858 | assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all"); |
| 6859 | } |
| 6860 | |
| 6861 | /// The delete law, one statement for every anchor: a caption deleted |
| 6862 | /// WITH its group ripples its lane exactly as its clip siblings do -- |
| 6863 | /// the hole closes and what follows slides up -- while a caption lifted |
| 6864 | /// alone leaves its gap, as it always has. And the delete of a grouped |
| 6865 | /// clip takes the group from whichever member was clicked. |
| 6866 | #[test] |
| 6867 | fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() { |
| 6868 | let caption = |start: u32, frames: u32| SubClip { |
| 6869 | start, |
| 6870 | frames, |
| 6871 | track: 0, |
| 6872 | in_us: 0, |
| 6873 | out_us: i64::from(frames) * 1_000_000, |
| 6874 | link: None, |
| 6875 | }; |
| 6876 | let track = || SubtitleTrack { |
| 6877 | path: FILE.into(), |
| 6878 | track: None, |
| 6879 | language: "eng".into(), |
| 6880 | name: String::new(), |
| 6881 | label: "eng".into(), |
| 6882 | cues: Vec::new(), |
| 6883 | bitmap: false, |
| 6884 | refused: None, |
| 6885 | }; |
| 6886 | // V+A+S grouped, with a second caption BEHIND the group's caption: |
| 6887 | // closing the hole is what the second caption's position says. |
| 6888 | let group = || { |
| 6889 | let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]); |
| 6890 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6891 | p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption"); |
| 6892 | p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind"); |
| 6893 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6894 | (p, s1) |
| 6895 | }; |
| 6896 | |
| 6897 | // Deleted by the picture: all three lanes close. |
| 6898 | let (mut p, s1) = group(); |
| 6899 | assert!(p.delete_in(Lane::V1, 0)); |
| 6900 | assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1"); |
| 6901 | assert!(p.lane(Lane::A1).is_empty(), "and the sound's"); |
| 6902 | assert_eq!( |
| 6903 | p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(), |
| 6904 | [60], |
| 6905 | "the caption's lane closed by its own span: the follower slid up" |
| 6906 | ); |
| 6907 | assert!(p.undo(), "one step"); |
| 6908 | assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all"); |
| 6909 | |
| 6910 | // By the sound: the same whole-group delete. |
| 6911 | let (mut p, s1) = group(); |
| 6912 | assert!(p.delete_in(Lane::A1, 0)); |
| 6913 | assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty()); |
| 6914 | assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too"); |
| 6915 | |
| 6916 | // By the caption itself: the same again. |
| 6917 | let (mut p, s1) = group(); |
| 6918 | assert!(p.delete_sub_in(s1, 0)); |
| 6919 | assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty()); |
| 6920 | assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door"); |
| 6921 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6922 | |
| 6923 | // A caption lifted ALONE still leaves its gap: the ungrouped law, |
| 6924 | // unchanged. |
| 6925 | let (mut p, s1) = group(); |
| 6926 | assert!(p.ungroup(s1, 0), "the caption stands alone"); |
| 6927 | assert!(p.lift_sub(s1, 0)); |
| 6928 | assert_eq!( |
| 6929 | p.sub_lane(s1)[0].start, 90, |
| 6930 | "the follower stayed put: a lone caption's lift is a gap" |
| 6931 | ); |
| 6932 | } |
| 6933 | |
| 6934 | /// Dragging a grouped caption carries its clips, one delta for all of them |
| 6935 | /// -- and a caption in no group refuses an overlap exactly as it always did. |
| 6936 | #[test] |
| 6937 | fn dragging_a_grouped_caption_carries_its_group() { |
| 6938 | let caption = |start: u32, frames: u32| SubClip { |
| 6939 | start, |
| 6940 | frames, |
| 6941 | track: 0, |
| 6942 | in_us: 0, |
| 6943 | out_us: i64::from(frames) * 1_000_000, |
| 6944 | link: None, |
| 6945 | }; |
| 6946 | let track = || SubtitleTrack { |
| 6947 | path: FILE.into(), |
| 6948 | track: None, |
| 6949 | language: "eng".into(), |
| 6950 | name: String::new(), |
| 6951 | label: "eng".into(), |
| 6952 | cues: Vec::new(), |
| 6953 | bitmap: false, |
| 6954 | refused: None, |
| 6955 | }; |
| 6956 | let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]); |
| 6957 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 6958 | p.place_sub(s1, 2, caption(2, 4)).expect("placed"); |
| 6959 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 6960 | |
| 6961 | // Same lane, further along: everyone moves by the same eight frames. |
| 6962 | p.move_sub(s1, 0, s1, 10).expect("room for all of it"); |
| 6963 | assert_eq!(p.sub_lane(s1)[0].start, 10); |
| 6964 | assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta"); |
| 6965 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 6966 | |
| 6967 | // ...and an ungrouped caption is the caption it always was. |
| 6968 | assert!(p.ungroup(s1, 0)); |
| 6969 | let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]); |
| 6970 | let s1 = q.add_lane(LaneKind::Subtitle); |
| 6971 | q.place_sub(s1, 0, caption(0, 4)).expect("placed"); |
| 6972 | q.place_sub(s1, 5, caption(5, 4)).expect("placed"); |
| 6973 | assert!(q |
| 6974 | .move_sub(s1, 0, s1, 3) |
| 6975 | .unwrap_err() |
| 6976 | .to_string() |
| 6977 | .contains("already covers")); |
| 6978 | } |
| 6979 | |
| 6980 | /// A trim carries a group's caption by the same delta as its clips, clamped |
| 6981 | /// to the caption's own walls -- the offsets between the members survive. |
| 6982 | #[test] |
| 6983 | fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() { |
| 6984 | let caption = |start: u32, frames: u32| SubClip { |
| 6985 | start, |
| 6986 | frames, |
| 6987 | track: 0, |
| 6988 | in_us: 0, |
| 6989 | out_us: i64::from(frames) * 1_000_000, |
| 6990 | link: None, |
| 6991 | }; |
| 6992 | let track = || SubtitleTrack { |
| 6993 | path: FILE.into(), |
| 6994 | track: None, |
| 6995 | language: "eng".into(), |
| 6996 | name: String::new(), |
| 6997 | label: "eng".into(), |
| 6998 | cues: Vec::new(), |
| 6999 | bitmap: false, |
| 7000 | refused: None, |
| 7001 | }; |
| 7002 | let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]); |
| 7003 | let s1 = p.add_lane(LaneKind::Subtitle); |
| 7004 | // The caption sits two frames into the take and ends one early. The |
| 7005 | // source runs past the clip, or there is no tail to pull out. |
| 7006 | let src = &[20]; |
| 7007 | p.place_sub(s1, 2, caption(2, 6)).expect("placed"); |
| 7008 | p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped"); |
| 7009 | |
| 7010 | // The tail goes out by three: the clip to 12, the caption to 11. |
| 7011 | assert!(p.trim(Lane::V1, 0, Edge::End, 12, src)); |
| 7012 | assert_eq!(p.lane(Lane::V1)[0].end(), 12); |
| 7013 | assert_eq!( |
| 7014 | (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()), |
| 7015 | (2, 11), |
| 7016 | "the caption follows by the delta" |
| 7017 | ); |
| 7018 | assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us); |
| 7019 | |
| 7020 | // The head comes in by two: everyone's start moves two along. |
| 7021 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src)); |
| 7022 | assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept"); |
| 7023 | assert!(links_are_consistent(&p.lanes).is_ok()); |
| 7024 | } |
| 7025 | |
| 7026 | #[test] |
| 7027 | fn split_refused_at_zero_boundary_end_and_in_a_gap() { |
| 7028 | let mut p = three(); |
| 7029 | let before = shape(&p); |
| 7030 | assert!(!p.split(0), "timeline 0 has nothing before it"); |
| 7031 | assert!(!p.split(3), "existing boundary"); |
| 7032 | assert!(!p.split(5), "existing boundary"); |
| 7033 | assert!(!p.split(9), "one past the last frame"); |
| 7034 | assert!(!p.split(1_000)); |
| 7035 | assert_eq!(shape(&p), before); |
| 7036 | // one undo lands before the *second* split, so the refusals pushed nothing |
| 7037 | assert!(p.undo()); |
| 7038 | assert_eq!(p.clips().len(), 2, "refused splits push no history"); |
| 7039 | |
| 7040 | // ...and a frame that is a gap in both lanes has nothing to split. |
| 7041 | let mut p = three(); |
| 7042 | assert!(p.lift(Lane::V1, 1)); |
| 7043 | assert!(p.lift(Lane::A1, 1)); |
| 7044 | assert!(!p.split(4), "a gap is not a clip"); |
| 7045 | } |
| 7046 | |
| 7047 | #[test] |
| 7048 | fn regroup_refuses_what_a_split_could_not_have_made() { |
| 7049 | let mut p = three(); |
| 7050 | // [3,5) and [5,9) are source-contiguous: that pair rejoins. |
| 7051 | assert!(p.regroup(5)); |
| 7052 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]); |
| 7053 | // A boundary with a gap on one side, and one where the sources do not |
| 7054 | // meet, are both refused. |
| 7055 | let mut p = three(); |
| 7056 | assert!(p.lift(Lane::V1, 1)); |
| 7057 | assert!(p.lift(Lane::A1, 1)); |
| 7058 | assert!(!p.regroup(3), "nothing starts at 3 any more"); |
| 7059 | let mut p = three(); |
| 7060 | for l in p.lanes() { |
| 7061 | assert!(p.place(l, 3, clip(0, 100, 102, 0))); |
| 7062 | } |
| 7063 | assert!(!p.regroup(3), "source 100 does not follow source 3"); |
| 7064 | assert!(!p.regroup(0), "nothing ends at 0"); |
| 7065 | assert!(!p.regroup(1_000)); |
| 7066 | } |
| 7067 | |
| 7068 | #[test] |
| 7069 | fn map_and_spans_sweep_every_boundary() { |
| 7070 | let p = three(); |
| 7071 | assert_eq!(p.timeline_frames(), 9); |
| 7072 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]); |
| 7073 | // contiguous source here, so the clip index is what actually moves |
| 7074 | let expect = [ |
| 7075 | (0, (0, 0)), |
| 7076 | (1, (0, 1)), |
| 7077 | (2, (0, 2)), |
| 7078 | (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip |
| 7079 | (4, (1, 4)), |
| 7080 | (5, (2, 5)), |
| 7081 | (6, (2, 6)), |
| 7082 | (7, (2, 7)), |
| 7083 | (8, (2, 8)), |
| 7084 | ]; |
| 7085 | for (t, want) in expect { |
| 7086 | assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}"); |
| 7087 | } |
| 7088 | assert_eq!(p.map_timeline(9), None); |
| 7089 | // A span is the rest of the clip from where it was asked about. |
| 7090 | assert_eq!( |
| 7091 | p.span_at(Lane::V1, 6), |
| 7092 | Some(Span { |
| 7093 | start: 6, |
| 7094 | len: 3, |
| 7095 | from: Some((0, 6)), |
| 7096 | speed: Speed::NORMAL |
| 7097 | }) |
| 7098 | ); |
| 7099 | assert_eq!(p.span_at(Lane::V1, 9), None); |
| 7100 | } |
| 7101 | |
| 7102 | /// The fit policy is one byte *in* the clip rather than an index into a |
| 7103 | /// table like the eq and the grade: there is nothing for a table to share. |
| 7104 | /// It costs the clip nothing at all -- the fields before it (a `usize` |
| 7105 | /// source and two `Option<u16>`s) already left the struct padded to 40 |
| 7106 | /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two |
| 7107 | /// `u32`s after it (48 bytes), and `transition_out` is a third word -- |
| 7108 | /// 52 bytes of fields, but the struct's own alignment is 8 (from the |
| 7109 | /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of |
| 7110 | /// words after it pads out to the next multiple of 8: 56 bytes total. |
| 7111 | /// The transform index is a third `Option<u16>`, same reason as the eq and |
| 7112 | /// colour ones before it -- it lands in bytes already spent on padding, so |
| 7113 | /// the struct still costs 56. |
| 7114 | /// This is the assert that says so: a clip that grows a word grows every |
| 7115 | /// undo snapshot and every clipboard copy with it. |
| 7116 | #[test] |
| 7117 | fn a_fit_policy_costs_the_clip_no_word() { |
| 7118 | assert_eq!( |
| 7119 | std::mem::size_of::<Clip>(), |
| 7120 | 56, |
| 7121 | "Clip changed size: {} bytes", |
| 7122 | std::mem::size_of::<Clip>() |
| 7123 | ); |
| 7124 | } |
| 7125 | |
| 7126 | /// The clip a copy would hand back: source `[100, 102)`, unrelated to |
| 7127 | /// anything in `three()` so it is recognisable wherever it lands. |
| 7128 | const PASTED: Clip = Clip { |
| 7129 | fade_in: 0, |
| 7130 | fade_out: 0, |
| 7131 | transition_out: 0, |
| 7132 | start: 0, |
| 7133 | in_frame: 100, |
| 7134 | out_frame: 102, |
| 7135 | source: 0, |
| 7136 | link: None, |
| 7137 | eq: None, |
| 7138 | color: None, |
| 7139 | transform: None, |
| 7140 | fit: FitPolicy::Fit, |
| 7141 | speed: Speed::NORMAL, |
| 7142 | }; |
| 7143 | |
| 7144 | #[test] |
| 7145 | fn paste_mid_clip_splits_around_it() { |
| 7146 | let mut p = three(); |
| 7147 | assert!(p.paste(6, PASTED)); // inside [5,9), one frame in |
| 7148 | assert_eq!(p.timeline_frames(), 11); |
| 7149 | assert_eq!( |
| 7150 | shape(&p)[0], |
| 7151 | vec![ |
| 7152 | clip(0, 0, 3, 0), |
| 7153 | clip(3, 3, 5, 0), |
| 7154 | clip(5, 5, 6, 0), |
| 7155 | clip(6, 100, 102, 0), |
| 7156 | clip(8, 6, 9, 0), |
| 7157 | ] |
| 7158 | ); |
| 7159 | assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes"); |
| 7160 | // The pasted frames are exactly where they were asked for, and the |
| 7161 | // split-off remainder resumes after them. |
| 7162 | assert_eq!(p.map_timeline(6), Some((3, 100))); |
| 7163 | assert_eq!(p.map_timeline(7), Some((3, 101))); |
| 7164 | assert_eq!(p.map_timeline(8), Some((4, 6))); |
| 7165 | } |
| 7166 | |
| 7167 | #[test] |
| 7168 | fn paste_at_boundary_zero_and_end() { |
| 7169 | let mut p = three(); |
| 7170 | assert!(p.paste(3, PASTED), "existing boundary: no split"); |
| 7171 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]); |
| 7172 | assert_eq!(p.map_timeline(3), Some((1, 100))); |
| 7173 | |
| 7174 | let mut p = three(); |
| 7175 | assert!(p.paste(0, PASTED)); |
| 7176 | assert_eq!(p.map_timeline(0), Some((0, 100))); |
| 7177 | assert_eq!(p.map_timeline(2), Some((1, 0))); |
| 7178 | |
| 7179 | // At the end: appended, there being nothing in front to leave black. |
| 7180 | let mut p = three(); |
| 7181 | assert!(p.paste(9, PASTED)); |
| 7182 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]); |
| 7183 | // Past it: down on the frame it was asked for, black in front of it -- |
| 7184 | // a row let go on the open bed lands under the ghost that promised it. |
| 7185 | // The clipboard's clamp lives in `PlaybackSession::paste_at`. |
| 7186 | assert!(p.paste(1_000, PASTED)); |
| 7187 | assert_eq!(p.timeline_frames(), 1_002); |
| 7188 | assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000); |
| 7189 | assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000); |
| 7190 | |
| 7191 | // An empty clip is the one thing refused, and it pushes no history. |
| 7192 | let mut p = three(); |
| 7193 | assert!(!p.paste(4, clip(0, 7, 7, 0))); |
| 7194 | assert_eq!(p.clips().len(), 3); |
| 7195 | } |
| 7196 | |
| 7197 | /// The data-loss paste: a clip of a source with no picture used to land on |
| 7198 | /// `V1` as well as `A1`, where it decodes to nothing -- and the save that |
| 7199 | /// carried it was refused on the way back in ("a box with a larger size"). |
| 7200 | #[test] |
| 7201 | fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() { |
| 7202 | let mut p = three(); |
| 7203 | let wav = p.import("/nonexistent/song.wav", 0); |
| 7204 | let copied = Clip { |
| 7205 | fade_in: 0, |
| 7206 | fade_out: 0, |
| 7207 | transition_out: 0, |
| 7208 | source: wav, |
| 7209 | ..PASTED |
| 7210 | }; |
| 7211 | assert!(p.paste(3, copied)); |
| 7212 | // The room is opened on every lane, or the two would slide apart... |
| 7213 | assert_eq!(p.timeline_frames(), 11); |
| 7214 | assert_eq!( |
| 7215 | shape(&p)[0], |
| 7216 | vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)], |
| 7217 | "the video lane got room and nothing else" |
| 7218 | ); |
| 7219 | // ...but the clip itself only reaches the lane that can play it. |
| 7220 | assert_eq!( |
| 7221 | shape(&p)[1], |
| 7222 | vec![ |
| 7223 | clip(0, 0, 3, 0), |
| 7224 | clip(3, 100, 102, wav), |
| 7225 | clip(5, 3, 5, 0), |
| 7226 | clip(7, 5, 9, 0) |
| 7227 | ] |
| 7228 | ); |
| 7229 | // A source with a picture is unchanged: still the grouped pair. |
| 7230 | let mut p = three(); |
| 7231 | assert!(p.paste(3, PASTED)); |
| 7232 | assert_eq!(shape(&p)[0], shape(&p)[1]); |
| 7233 | } |
| 7234 | |
| 7235 | /// A hand-written file may hold a clip that ends at the very last frame |
| 7236 | /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used |
| 7237 | /// to wrap its start round to the front of the lane: an overlap in debug, a |
| 7238 | /// project no reload would accept in release. |
| 7239 | #[test] |
| 7240 | fn a_paste_that_would_run_past_the_last_frame_is_refused() { |
| 7241 | let far = clip(u32::MAX - 90, 0, 90, 0); |
| 7242 | let parts = |c: Clip| { |
| 7243 | Project::from_parts( |
| 7244 | vec![Source::new(FILE, 0)], |
| 7245 | two(vec![c], vec![c]), |
| 7246 | Vec::new(), |
| 7247 | Vec::new(), |
| 7248 | Vec::new(), |
| 7249 | ) |
| 7250 | .expect("valid parts") |
| 7251 | }; |
| 7252 | let mut p = parts(far); |
| 7253 | assert!(!p.paste(0, PASTED), "no room for the two frames it adds"); |
| 7254 | assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing"); |
| 7255 | assert!(!p.undo(), "...and pushes no history either"); |
| 7256 | assert!( |
| 7257 | !p.paste(u32::MAX, PASTED), |
| 7258 | "appending has nowhere to go either: the timeline ends at the last frame" |
| 7259 | ); |
| 7260 | // With room for exactly those frames the same paste is taken. |
| 7261 | let mut p = parts(clip(u32::MAX - 92, 0, 90, 0)); |
| 7262 | assert!(p.paste(0, PASTED)); |
| 7263 | assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX); |
| 7264 | } |
| 7265 | |
| 7266 | #[test] |
| 7267 | fn paste_undoes_in_one_step() { |
| 7268 | let mut p = three(); |
| 7269 | let before = shape(&p); |
| 7270 | assert!(p.paste(6, PASTED)); |
| 7271 | assert!(p.undo()); |
| 7272 | assert_eq!(shape(&p), before, "a paste is one undo step"); |
| 7273 | } |
| 7274 | |
| 7275 | #[test] |
| 7276 | fn a_copy_outlives_the_clip_it_came_from() { |
| 7277 | let mut p = three(); |
| 7278 | let copied = p.clips()[1]; // [3,5) |
| 7279 | assert!(p.delete(1)); |
| 7280 | // Just a frame range: the source is still on disk either way. |
| 7281 | assert!(p.paste(0, copied)); |
| 7282 | assert_eq!(p.map_timeline(0), Some((0, 3))); |
| 7283 | assert_eq!(p.timeline_frames(), 9); |
| 7284 | } |
| 7285 | |
| 7286 | #[test] |
| 7287 | fn delete_closes_the_gap_on_both_lanes() { |
| 7288 | let mut p = three(); |
| 7289 | assert!(p.delete(1)); |
| 7290 | assert_eq!(p.timeline_frames(), 7); |
| 7291 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]); |
| 7292 | assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]); |
| 7293 | // timeline 3 used to be source 3; the gap closed so it is source 5 now |
| 7294 | assert_eq!(p.map_timeline(3), Some((1, 5))); |
| 7295 | assert_eq!(p.map_timeline(6), Some((1, 8))); |
| 7296 | assert_eq!(p.map_timeline(7), None); |
| 7297 | } |
| 7298 | |
| 7299 | #[test] |
| 7300 | fn delete_first_last_and_only() { |
| 7301 | let mut p = three(); |
| 7302 | assert!(p.delete(0)); |
| 7303 | assert_eq!(p.map_timeline(0), Some((0, 3))); |
| 7304 | assert_eq!(p.timeline_frames(), 6); |
| 7305 | |
| 7306 | let mut p = three(); |
| 7307 | assert!(p.delete(2)); |
| 7308 | assert_eq!(p.timeline_frames(), 5); |
| 7309 | assert_eq!(p.map_timeline(4), Some((1, 4))); |
| 7310 | |
| 7311 | assert!(!p.delete(2), "index past the end"); |
| 7312 | assert!(p.delete(1)); |
| 7313 | assert!(p.delete(0), "and the last remaining clip goes too"); |
| 7314 | assert_eq!(p.clips().len(), 0); |
| 7315 | assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable"); |
| 7316 | assert!(!p.delete(0), "there is nothing left to delete"); |
| 7317 | assert!(p.undo(), "one gesture, one undo"); |
| 7318 | assert_eq!(p.clips().len(), 1); |
| 7319 | } |
| 7320 | |
| 7321 | /// The offset model's point: one lane loses a clip, the other does not move. |
| 7322 | #[test] |
| 7323 | fn a_lift_leaves_a_gap_and_moves_nothing() { |
| 7324 | let mut p = three(); |
| 7325 | let video_before = shape(&p)[0].clone(); |
| 7326 | assert!(p.lift(Lane::A1, 1)); |
| 7327 | assert_eq!(shape(&p)[0], video_before, "the picture never moved"); |
| 7328 | assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter"); |
| 7329 | assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]); |
| 7330 | // The hole is a gap: mapped as nothing, spanned as a gap of its length. |
| 7331 | assert_eq!(p.map(Lane::A1, 4), None); |
| 7332 | assert_eq!( |
| 7333 | p.span_at(Lane::A1, 3), |
| 7334 | Some(Span { |
| 7335 | start: 3, |
| 7336 | len: 2, |
| 7337 | from: None, |
| 7338 | speed: Speed::NORMAL |
| 7339 | }) |
| 7340 | ); |
| 7341 | assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on"); |
| 7342 | assert!(p.undo()); |
| 7343 | assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]); |
| 7344 | } |
| 7345 | |
| 7346 | #[test] |
| 7347 | fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() { |
| 7348 | let mut p = three(); |
| 7349 | assert!(p.lift(Lane::A1, 2)); |
| 7350 | assert_eq!(p.timeline_frames(), 9, "video still runs to 9"); |
| 7351 | assert_eq!( |
| 7352 | p.span_at(Lane::A1, 5), |
| 7353 | Some(Span { |
| 7354 | start: 5, |
| 7355 | len: 4, |
| 7356 | from: None, |
| 7357 | speed: Speed::NORMAL |
| 7358 | }), |
| 7359 | "the audio lane holds silence to the end of the picture" |
| 7360 | ); |
| 7361 | assert_eq!(p.span_at(Lane::A1, 9), None); |
| 7362 | // Every lane covers the timeline exactly, gaps included. |
| 7363 | for l in p.lanes() { |
| 7364 | let spans = p.spans_from(l, 0); |
| 7365 | assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label()); |
| 7366 | assert_eq!(spans[0].start, 0); |
| 7367 | } |
| 7368 | } |
| 7369 | |
| 7370 | /// The timeline is emptiable: the last placement comes off like any other, |
| 7371 | /// the project holds "nothing on any lane" as a state, and one undo per |
| 7372 | /// gesture brings it back. |
| 7373 | #[test] |
| 7374 | fn the_last_clip_of_the_last_lane_lifts_and_undoes() { |
| 7375 | let mut p = Project::single(FILE, 9); |
| 7376 | assert!(p.lift(Lane::A1, 0), "a silent timeline is fine"); |
| 7377 | assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too"); |
| 7378 | assert_eq!(p.timeline_frames(), 0); |
| 7379 | assert_eq!(p.composite_span_at(0), None, "nothing to show"); |
| 7380 | assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list"); |
| 7381 | assert!(!p.lift(Lane::A1, 0), "index past the end"); |
| 7382 | assert!(p.undo(), "and the last lift comes back"); |
| 7383 | assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]); |
| 7384 | // A saved-and-loaded empty timeline is a project like any other, and it |
| 7385 | // still names the file its frame rate came from. |
| 7386 | assert!(p.lift(Lane::V1, 0)); |
| 7387 | let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); |
| 7388 | assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline"); |
| 7389 | let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads"); |
| 7390 | assert_eq!(back.timeline_frames(), 0); |
| 7391 | assert_eq!(back.lanes().len(), 2, "and it kept its lanes"); |
| 7392 | } |
| 7393 | |
| 7394 | /// What a keyboard selection walks: one answer per lane, gaps included -- |
| 7395 | /// the composite's own answer is one lane's and cannot say what the audio |
| 7396 | /// lane holds under the same playhead. |
| 7397 | #[test] |
| 7398 | fn lane_clip_at_answers_for_each_lane_separately() { |
| 7399 | let mut p = Project::single(FILE, 9); |
| 7400 | assert!(p.split(3), "both lanes split"); |
| 7401 | assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0)); |
| 7402 | assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1)); |
| 7403 | assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1)); |
| 7404 | assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end"); |
| 7405 | // A gap on one lane leaves the other's clip selectable there. |
| 7406 | assert!(p.lift(Lane::A1, 0)); |
| 7407 | assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing"); |
| 7408 | assert_eq!( |
| 7409 | p.lane_clip_at(Lane::A1, 3), |
| 7410 | Some(0), |
| 7411 | "indices moved with it" |
| 7412 | ); |
| 7413 | assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0)); |
| 7414 | // A lane that is not there is not a panic. |
| 7415 | assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None); |
| 7416 | } |
| 7417 | |
| 7418 | #[test] |
| 7419 | fn place_overwrites_only_its_own_lane() { |
| 7420 | let mut p = three(); |
| 7421 | let audio_before = shape(&p)[1].clone(); |
| 7422 | // Straddles [3,5) and eats into [5,9): the first is trimmed, the second |
| 7423 | // is trimmed, nothing shifts. |
| 7424 | assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0))); |
| 7425 | assert_eq!( |
| 7426 | shape(&p)[0], |
| 7427 | vec![ |
| 7428 | clip(0, 0, 3, 0), |
| 7429 | clip(3, 3, 4, 0), |
| 7430 | clip(4, 100, 102, 0), |
| 7431 | clip(6, 6, 9, 0), |
| 7432 | ] |
| 7433 | ); |
| 7434 | assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched"); |
| 7435 | assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert"); |
| 7436 | |
| 7437 | // Placed inside one clip, it splits it in two. |
| 7438 | let mut p = Project::single(FILE, 9); |
| 7439 | assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0))); |
| 7440 | assert_eq!( |
| 7441 | shape(&p)[0], |
| 7442 | vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)] |
| 7443 | ); |
| 7444 | // ...and placed past the end it makes a gap, which is the whole point. |
| 7445 | assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0))); |
| 7446 | assert_eq!(p.timeline_frames(), 22); |
| 7447 | assert_eq!( |
| 7448 | p.span_at(Lane::V1, 9), |
| 7449 | Some(Span { |
| 7450 | start: 9, |
| 7451 | len: 11, |
| 7452 | from: None, |
| 7453 | speed: Speed::NORMAL |
| 7454 | }) |
| 7455 | ); |
| 7456 | assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip"); |
| 7457 | } |
| 7458 | |
| 7459 | /// A file with sound let go over a further video track: both halves go down, |
| 7460 | /// on the same frames, and the audio row is added when the `+ V` button left |
| 7461 | /// the project without one. One undo takes the lane and both clips back. |
| 7462 | #[test] |
| 7463 | fn a_take_placed_on_a_layer_lands_with_its_sound() { |
| 7464 | let mut p = three(); |
| 7465 | let v2 = p.add_lane(LaneKind::Video); |
| 7466 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet"); |
| 7467 | |
| 7468 | assert!(p.place_take(v2, 4, clip(0, 100, 102, 0))); |
| 7469 | let a2 = Lane::new(LaneKind::Audio, 1); |
| 7470 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added"); |
| 7471 | assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source"); |
| 7472 | assert_eq!(p.lane(v2)[0].start, 4); |
| 7473 | assert_eq!(p.lane(v2)[0].end(), 6); |
| 7474 | assert_eq!( |
| 7475 | p.lane(v2)[0].link, |
| 7476 | p.lane(a2)[0].link, |
| 7477 | "one take, not two placements" |
| 7478 | ); |
| 7479 | assert!(p.lane(v2)[0].link.is_some()); |
| 7480 | assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched"); |
| 7481 | assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it"); |
| 7482 | |
| 7483 | // The pair overwrites its own two lanes and nothing else, exactly as a |
| 7484 | // one-lane place does. |
| 7485 | assert!(p.place_take(v2, 5, clip(0, 200, 203, 0))); |
| 7486 | assert_eq!(p.lane(v2), p.lane(a2)); |
| 7487 | assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there"); |
| 7488 | assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched"); |
| 7489 | |
| 7490 | assert!(p.undo(), "one step for the second pair"); |
| 7491 | assert_eq!(p.lane(v2).len(), 1); |
| 7492 | assert!(p.undo(), "one step for the first pair *and* its lane"); |
| 7493 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]); |
| 7494 | assert!(p.lane(v2).is_empty()); |
| 7495 | |
| 7496 | // Refusals cost nothing: sound placed alone is `place`'s door. |
| 7497 | assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane"); |
| 7498 | assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip"); |
| 7499 | assert!( |
| 7500 | !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)), |
| 7501 | "a lane that is not there" |
| 7502 | ); |
| 7503 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]); |
| 7504 | } |
| 7505 | |
| 7506 | /// The drag between tracks: let go at the frames it already covers the clip |
| 7507 | /// keeps them, one undo takes it back, and every way it can be refused |
| 7508 | /// leaves the project untouched. |
| 7509 | #[test] |
| 7510 | fn move_clip_keeps_the_frames_and_refuses_the_rest() { |
| 7511 | let v2 = Lane::new(LaneKind::Video, 1); |
| 7512 | let mut p = three(); |
| 7513 | assert_eq!(p.add_lane(LaneKind::Video), v2); |
| 7514 | let before = shape(&p); |
| 7515 | |
| 7516 | assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up"); |
| 7517 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]); |
| 7518 | assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2"); |
| 7519 | assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched"); |
| 7520 | assert_eq!(p.timeline_frames(), 9, "a move is not an insert"); |
| 7521 | // One snapshot: a single undo, and the lane list survives it. |
| 7522 | assert!(p.undo()); |
| 7523 | assert_eq!(shape(&p), before); |
| 7524 | |
| 7525 | // A lane that is not there, the lane and frame it is already at, an |
| 7526 | // index that is not there, and a move across kinds: all refused, |
| 7527 | // nothing changed. |
| 7528 | let history = p.history.len(); |
| 7529 | for (from, idx, to, start) in [ |
| 7530 | (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3), |
| 7531 | (Lane::V1, 1, Lane::V1, 3), |
| 7532 | (Lane::V1, 9, v2, 3), |
| 7533 | (Lane::V1, 1, Lane::A1, 3), |
| 7534 | (Lane::A1, 1, v2, 3), |
| 7535 | ] { |
| 7536 | assert!( |
| 7537 | !p.move_clip(from, idx, to, start), |
| 7538 | "{from:?} {idx} -> {to:?} at {start}" |
| 7539 | ); |
| 7540 | } |
| 7541 | assert_eq!(shape(&p), before); |
| 7542 | assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); |
| 7543 | |
| 7544 | // Landing on another clip is refused rather than overwriting it: the |
| 7545 | // pointer named the lane, never the take already sitting there. |
| 7546 | assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)"); |
| 7547 | assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it"); |
| 7548 | assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it"); |
| 7549 | assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]); |
| 7550 | assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]); |
| 7551 | } |
| 7552 | |
| 7553 | /// The drag *along* a track, which is the one every other editor has: the |
| 7554 | /// clip lands on the frame the pointer let it go at, and stops dead against |
| 7555 | /// the neighbour rather than overwriting it. |
| 7556 | #[test] |
| 7557 | fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() { |
| 7558 | let sources = vec![Source::new(FILE, 0)]; |
| 7559 | let lanes = vec![ |
| 7560 | (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]), |
| 7561 | (LaneKind::Audio, vec![clip(0, 0, 3, 0)]), |
| 7562 | ]; |
| 7563 | let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts"); |
| 7564 | let before = shape(&p); |
| 7565 | |
| 7566 | // Into the gap, exactly where it was let go -- nothing else moves. |
| 7567 | assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5)); |
| 7568 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]); |
| 7569 | assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched"); |
| 7570 | // Dragged past the clip in front of it: clamped to its wall, laid end |
| 7571 | // to end with it, never over it. |
| 7572 | assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0)); |
| 7573 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]); |
| 7574 | // One undo per drag, and both of them together are the state it started |
| 7575 | // in -- the frames each clip plays never changed. |
| 7576 | assert!(p.undo() && p.undo()); |
| 7577 | assert_eq!(shape(&p), before); |
| 7578 | |
| 7579 | // A drop that changes nothing is a click, not an edit. |
| 7580 | let history = p.history.len(); |
| 7581 | assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10)); |
| 7582 | assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); |
| 7583 | } |
| 7584 | |
| 7585 | /// A drag carries the whole take: the sound half travels exactly as far as |
| 7586 | /// the picture does, and the tighter of their two walls stops both. |
| 7587 | #[test] |
| 7588 | fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() { |
| 7589 | let mut p = three(); |
| 7590 | assert!( |
| 7591 | p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2), |
| 7592 | "room to the right" |
| 7593 | ); |
| 7594 | let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids"); |
| 7595 | assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped"); |
| 7596 | // Something in the sound's way, and nothing at all in the picture's. |
| 7597 | assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)"); |
| 7598 | let before = shape(&p); |
| 7599 | |
| 7600 | assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right"); |
| 7601 | assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did"); |
| 7602 | assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it"); |
| 7603 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); |
| 7604 | assert!(p.undo()); |
| 7605 | assert_eq!(shape(&p), before, "one undo for the whole take"); |
| 7606 | } |
| 7607 | |
| 7608 | /// The drag that does both at once -- another lane *and* another frame -- |
| 7609 | /// which is what a pointer let go over a lane always names. |
| 7610 | #[test] |
| 7611 | fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() { |
| 7612 | let v2 = Lane::new(LaneKind::Video, 1); |
| 7613 | let mut p = three(); |
| 7614 | assert_eq!(p.add_lane(LaneKind::Video), v2); |
| 7615 | |
| 7616 | assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20"); |
| 7617 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]); |
| 7618 | assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer"); |
| 7619 | assert_eq!( |
| 7620 | p.lane(Lane::A1)[2].start, |
| 7621 | 20, |
| 7622 | "its sound travelled the same distance" |
| 7623 | ); |
| 7624 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); |
| 7625 | assert_eq!(p.timeline_frames(), 24, "a move is not an insert"); |
| 7626 | } |
| 7627 | |
| 7628 | /// How long `FILE` is, which is what a trim's tail is allowed to reach: |
| 7629 | /// [`three`] cuts up all nine of its frames. |
| 7630 | const SRC: &[u32] = &[9]; |
| 7631 | |
| 7632 | /// The drag on a clip's tail: it plays less (or more) of its source, nothing |
| 7633 | /// else on the lane moves, and every wall stops the edge rather than |
| 7634 | /// refusing the gesture. |
| 7635 | #[test] |
| 7636 | fn trimming_the_tail_stops_at_every_wall() { |
| 7637 | let mut p = three(); |
| 7638 | |
| 7639 | // Pulled in: a gap opens behind it and the clip after it stays put. |
| 7640 | assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC)); |
| 7641 | assert_eq!( |
| 7642 | shape(&p)[0], |
| 7643 | vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)] |
| 7644 | ); |
| 7645 | assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing"); |
| 7646 | assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap"); |
| 7647 | |
| 7648 | // ...and back out, no further than the clip behind it. |
| 7649 | assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC)); |
| 7650 | assert_eq!( |
| 7651 | shape(&p)[0][1], |
| 7652 | clip(3, 3, 5, 0), |
| 7653 | "stopped at the neighbour" |
| 7654 | ); |
| 7655 | assert!( |
| 7656 | !p.trim(Lane::V1, 1, Edge::End, 8, SRC), |
| 7657 | "already at the wall" |
| 7658 | ); |
| 7659 | |
| 7660 | // One frame of clip always survives, however far back the pointer went. |
| 7661 | assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC)); |
| 7662 | assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0)); |
| 7663 | |
| 7664 | // The last clip has no neighbour, so what stops it is the file: nine |
| 7665 | // frames is nine frames. |
| 7666 | assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC)); |
| 7667 | assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC)); |
| 7668 | assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take"); |
| 7669 | assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further"); |
| 7670 | // A source nobody told us the length of may not grow at all -- an |
| 7671 | // out-point past the end of a file is a save that will not open again. |
| 7672 | assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[])); |
| 7673 | assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown"); |
| 7674 | } |
| 7675 | |
| 7676 | /// The head pulled in takes the in-point with it -- what stays plays what it |
| 7677 | /// always played -- and stops at the source's own first frame. |
| 7678 | #[test] |
| 7679 | fn trimming_the_head_moves_the_in_point() { |
| 7680 | let mut p = three(); |
| 7681 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); |
| 7682 | assert_eq!( |
| 7683 | shape(&p)[0][0], |
| 7684 | clip(2, 2, 3, 0), |
| 7685 | "two frames off the front" |
| 7686 | ); |
| 7687 | assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2"); |
| 7688 | assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap"); |
| 7689 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again"); |
| 7690 | assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0)); |
| 7691 | // One frame survives here too. |
| 7692 | assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC)); |
| 7693 | assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0)); |
| 7694 | |
| 7695 | // A clip that does not begin at its source's first frame: its head goes |
| 7696 | // back to source frame 0 and not one frame further. |
| 7697 | let mut p = Project::single(FILE, 9); |
| 7698 | assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0))); |
| 7699 | assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it"); |
| 7700 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC)); |
| 7701 | assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left"); |
| 7702 | } |
| 7703 | |
| 7704 | /// A clip whose in-point is *past* its own start -- what a ripple delete |
| 7705 | /// leaves, the piece in front of it gone and this one slid back to frame 0 |
| 7706 | /// carrying the in-point the cut gave it. Its head has more source behind it |
| 7707 | /// than the timeline has room for, and the timeline's own first frame is the |
| 7708 | /// wall: asking is not an overflow, and the answer is 0. |
| 7709 | #[test] |
| 7710 | fn a_ripple_closed_clip_can_still_be_head_trimmed() { |
| 7711 | let mut p = Project::single(FILE, 9); |
| 7712 | assert!(p.split(5)); |
| 7713 | assert!(p.delete_in(Lane::V1, 0), "the first piece goes"); |
| 7714 | assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5"); |
| 7715 | |
| 7716 | assert_eq!( |
| 7717 | p.trim_room(Lane::V1, 0, Edge::Start, SRC), |
| 7718 | Some((0, 3)), |
| 7719 | "back to frame 0 at most, and one frame of clip always survives" |
| 7720 | ); |
| 7721 | assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there"); |
| 7722 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); |
| 7723 | assert_eq!( |
| 7724 | shape(&p)[0], |
| 7725 | vec![clip(2, 7, 9, 0)], |
| 7726 | "the in-point followed" |
| 7727 | ); |
| 7728 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out"); |
| 7729 | assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]); |
| 7730 | } |
| 7731 | |
| 7732 | /// A still is trimmed from its head exactly as it is from its tail: it has |
| 7733 | /// no earlier frame to walk an in-point back to, so the wall is the length |
| 7734 | /// the caller's table allows it, measured back from the tail. Measured from |
| 7735 | /// the in-point -- which a placed picture has at 0 -- its left edge could |
| 7736 | /// never be dragged outwards at all. |
| 7737 | #[test] |
| 7738 | fn a_stills_head_stretches_out_like_its_tail() { |
| 7739 | const STILL: &str = "/nonexistent/card.png"; |
| 7740 | /// What a still is held to, as `PlaybackSession` fills the table in. |
| 7741 | const CAP: &[u32] = &[60]; |
| 7742 | |
| 7743 | let mut p = Project::single(STILL, 20); |
| 7744 | assert!(p.lift(Lane::A1, 0), "a picture is silent"); |
| 7745 | assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0"); |
| 7746 | assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0))); |
| 7747 | |
| 7748 | // A source with no entry in the table may not grow, here as at the tail. |
| 7749 | assert_eq!( |
| 7750 | p.trim_room(Lane::V1, 0, Edge::Start, &[]), |
| 7751 | Some((100, 119)), |
| 7752 | "a length nobody told us buys no head room" |
| 7753 | ); |
| 7754 | assert_eq!( |
| 7755 | p.trim_room(Lane::V1, 0, Edge::Start, CAP), |
| 7756 | Some((60, 119)), |
| 7757 | "back to a whole cap's worth, one frame of clip surviving" |
| 7758 | ); |
| 7759 | assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP)); |
| 7760 | assert_eq!( |
| 7761 | shape(&p)[0][0], |
| 7762 | clip(80, 0, 40, 0), |
| 7763 | "twenty frames longer, and still read from the source's first frame" |
| 7764 | ); |
| 7765 | // Past the cap is clamped, exactly as the tail is -- not refused. |
| 7766 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP)); |
| 7767 | assert_eq!( |
| 7768 | shape(&p)[0][0], |
| 7769 | clip(60, 0, 60, 0), |
| 7770 | "a cap's worth, no more" |
| 7771 | ); |
| 7772 | // ...and the clip in front is the nearer wall of the two: no head trim |
| 7773 | // may open an overlap. |
| 7774 | assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP)); |
| 7775 | assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0))); |
| 7776 | assert_eq!( |
| 7777 | p.trim_room(Lane::V1, 1, Edge::Start, CAP), |
| 7778 | Some((85, 119)), |
| 7779 | "up to the neighbour's last frame and not over it" |
| 7780 | ); |
| 7781 | assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP)); |
| 7782 | assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it"); |
| 7783 | assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap"); |
| 7784 | } |
| 7785 | |
| 7786 | /// Linked halves trim as one: a link is one span on however many lanes, so |
| 7787 | /// the sound follows the picture's edge -- and the tightest wall of the two |
| 7788 | /// is what stops both. |
| 7789 | #[test] |
| 7790 | fn linked_halves_trim_together() { |
| 7791 | let mut p = three(); |
| 7792 | let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids"); |
| 7793 | assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped"); |
| 7794 | |
| 7795 | assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC)); |
| 7796 | assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0)); |
| 7797 | assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed"); |
| 7798 | assert!( |
| 7799 | p.trim(Lane::A1, 2, Edge::End, 8, SRC), |
| 7800 | "either half drags it" |
| 7801 | ); |
| 7802 | assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows"); |
| 7803 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); |
| 7804 | |
| 7805 | // Something in the way on the *audio* lane stops the picture's tail as |
| 7806 | // well: the group can only go as far as its tightest member. |
| 7807 | assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0))); |
| 7808 | assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC)); |
| 7809 | assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip"); |
| 7810 | assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0)); |
| 7811 | links_are_consistent(&p.lanes).expect("still one span"); |
| 7812 | } |
| 7813 | |
| 7814 | /// A whole drag is one undo step -- the front-end commits once, at the |
| 7815 | /// release -- and an edge asked to stay where it is costs none at all. |
| 7816 | #[test] |
| 7817 | fn a_trim_is_one_undo_step() { |
| 7818 | let mut p = three(); |
| 7819 | let before = shape(&p); |
| 7820 | let history = p.history.len(); |
| 7821 | |
| 7822 | assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC)); |
| 7823 | assert_eq!(p.history.len(), history + 1, "one snapshot per gesture"); |
| 7824 | assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there"); |
| 7825 | assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip"); |
| 7826 | assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC)); |
| 7827 | assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing"); |
| 7828 | |
| 7829 | assert!(p.undo()); |
| 7830 | assert_eq!(shape(&p), before, "both halves back, in one step"); |
| 7831 | } |
| 7832 | |
| 7833 | /// A moved half stays in its group: a link names a span, not a lane, so the |
| 7834 | /// picture on `V2` is still the same take as the sound under it on `A1`. |
| 7835 | #[test] |
| 7836 | fn move_clip_keeps_the_group() { |
| 7837 | let v2 = Lane::new(LaneKind::Video, 1); |
| 7838 | let mut p = three(); |
| 7839 | p.add_lane(LaneKind::Video); |
| 7840 | let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids"); |
| 7841 | assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped"); |
| 7842 | assert!(p.move_clip(Lane::V1, 1, v2, 3)); |
| 7843 | assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it"); |
| 7844 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); |
| 7845 | assert_eq!( |
| 7846 | p.lane(v2)[0].start, |
| 7847 | p.lane(Lane::A1)[1].start, |
| 7848 | "and still covers the same span as its sound" |
| 7849 | ); |
| 7850 | } |
| 7851 | |
| 7852 | /// The gap-close menu's hit test: what `gap_at` says about a frame at the |
| 7853 | /// head of a lane, between two clips, inside a clip, past the last one, |
| 7854 | /// and on a lane holding nothing at all. |
| 7855 | #[test] |
| 7856 | fn gap_at_finds_the_hole_a_frame_sits_in() { |
| 7857 | let mut p = Project::single(FILE, 1); |
| 7858 | let v = p.add_lane(LaneKind::Video); |
| 7859 | // Empty lane: nothing before and nothing after -- not a gap, since |
| 7860 | // there is nothing to ripple toward. |
| 7861 | assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close"); |
| 7862 | |
| 7863 | assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)"); |
| 7864 | // Before the only clip: the gap runs from the timeline's own head. |
| 7865 | assert_eq!(p.gap_at(v, 0), Some((0, 5))); |
| 7866 | assert_eq!(p.gap_at(v, 4), Some((0, 5))); |
| 7867 | // Inside the clip: not a gap. |
| 7868 | assert_eq!(p.gap_at(v, 5), None); |
| 7869 | assert_eq!(p.gap_at(v, 7), None); |
| 7870 | // Past the only clip: the open end of the lane, not a gap -- there is |
| 7871 | // nothing after it to slide back. |
| 7872 | assert_eq!(p.gap_at(v, 8), None); |
| 7873 | assert_eq!(p.gap_at(v, 100), None); |
| 7874 | |
| 7875 | assert!(p.place(v, 12, clip(12, 0, 2, 0)), "a second clip at [12,14)"); |
| 7876 | // Between the two: the gap [8,12). |
| 7877 | assert_eq!(p.gap_at(v, 8), Some((8, 4))); |
| 7878 | assert_eq!(p.gap_at(v, 11), Some((8, 4))); |
| 7879 | assert_eq!(p.gap_at(v, 14), None, "still the open end"); |
| 7880 | |
| 7881 | assert!( |
| 7882 | p.place(v, 8, clip(8, 0, 4, 0)), |
| 7883 | "fills [8,12) exactly, meeting both neighbours" |
| 7884 | ); |
| 7885 | assert_eq!(p.gap_at(v, 8), None, "adjacent clips leave no frame to name a gap"); |
| 7886 | assert_eq!(p.gap_at(v, 11), None); |
| 7887 | } |
| 7888 | |
| 7889 | /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the |
| 7890 | /// menu named: the clip after the gap slides back on that lane, a clip on |
| 7891 | /// another lane at the very same frame range does not move, and the whole |
| 7892 | /// close is one press of undo. |
| 7893 | #[test] |
| 7894 | fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() { |
| 7895 | let mut p = Project::single(FILE, 1); |
| 7896 | let v = p.add_lane(LaneKind::Video); |
| 7897 | let a = p.add_lane(LaneKind::Audio); |
| 7898 | assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)"); |
| 7899 | assert!( |
| 7900 | p.place(a, 0, clip(0, 0, 3, 0)), |
| 7901 | "A clip at [0,3) -- outside the video lane's gap and this scope" |
| 7902 | ); |
| 7903 | let before = shape(&p); |
| 7904 | let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip"); |
| 7905 | assert_eq!((start, len), (0, 5)); |
| 7906 | assert!(p.cut_regions(&[(start, len)], &[v]).is_ok()); |
| 7907 | assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap"); |
| 7908 | assert_eq!(p.lane(a)[0].start, 0, "the untouched lane's clip did not move"); |
| 7909 | assert!(p.undo(), "one press undoes the whole close"); |
| 7910 | assert_eq!(shape(&p), before, "back to exactly where it was"); |
| 7911 | } |
| 7912 | |
| 7913 | /// A clip carrying an explicit link id -- what a |
| 7914 | /// [`from_parts`](Project::from_parts) fixture below needs to build a take |
| 7915 | /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane` |
| 7916 | /// already builds inline. |
| 7917 | fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip { |
| 7918 | Clip { |
| 7919 | fade_in: 0, |
| 7920 | fade_out: 0, |
| 7921 | transition_out: 0, |
| 7922 | start, |
| 7923 | in_frame, |
| 7924 | out_frame, |
| 7925 | source: 0, |
| 7926 | link: Some(link), |
| 7927 | eq: None, |
| 7928 | color: None, |
| 7929 | transform: None, |
| 7930 | fit: FitPolicy::default(), |
| 7931 | speed: Speed::NORMAL, |
| 7932 | } |
| 7933 | } |
| 7934 | |
| 7935 | /// The ordinary case the defect made a permanent no-op: a gap on `V1` |
| 7936 | /// bordered by a linked take whose `A1` half is empty across the very |
| 7937 | /// same stretch widens the scope to both lanes, so the ripple carries the |
| 7938 | /// take rather than tearing it -- and one undo puts both halves back. |
| 7939 | #[test] |
| 7940 | fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() { |
| 7941 | let sources = vec![Source::new(FILE, 0)]; |
| 7942 | let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)]; |
| 7943 | let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)]; |
| 7944 | let mut p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new()) |
| 7945 | .expect("valid parts"); |
| 7946 | let before = shape(&p); |
| 7947 | assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2))); |
| 7948 | assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 2)), "the same stretch is empty on A1 too"); |
| 7949 | |
| 7950 | let scope = p |
| 7951 | .gap_take_scope(Lane::V1, 3, 2) |
| 7952 | .expect("a matching gap on both halves widens the scope"); |
| 7953 | assert_eq!(scope.len(), 2, "the take's other lane joins"); |
| 7954 | assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1)); |
| 7955 | |
| 7956 | assert!(p.cut_regions(&[(3, 2)], &scope).is_ok()); |
| 7957 | assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back"); |
| 7958 | assert_eq!(p.lane(Lane::A1)[1].start, 3, "A1's far half rode along, in sync"); |
| 7959 | assert!(p.undo(), "one press undoes the whole close"); |
| 7960 | assert_eq!(shape(&p), before, "back to exactly where it was"); |
| 7961 | } |
| 7962 | |
| 7963 | /// The real design question: a take whose gap is not the *same size* on |
| 7964 | /// both lanes cannot ripple by one number without pulling a lane's clip |
| 7965 | /// out from under the other's sync -- refused by name, with the frame |
| 7966 | /// naming which lane is out of step, rather than silently taking real |
| 7967 | /// media off the shorter side. |
| 7968 | #[test] |
| 7969 | fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() { |
| 7970 | let sources = vec![Source::new(FILE, 0)]; |
| 7971 | let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)]; |
| 7972 | // A1's second half starts at 4, not 5: its gap is [3,4), one frame |
| 7973 | // shorter than V1's [3,5) -- a legal offset-preserving group, and |
| 7974 | // still one take. |
| 7975 | let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)]; |
| 7976 | let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new()) |
| 7977 | .expect("valid parts"); |
| 7978 | assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2))); |
| 7979 | assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1"); |
| 7980 | |
| 7981 | let err = p |
| 7982 | .gap_take_scope(Lane::V1, 3, 2) |
| 7983 | .expect_err("a mismatched gap cannot ripple by one number") |
| 7984 | .to_string(); |
| 7985 | assert!(err.contains("A1"), "{err}"); |
| 7986 | assert!(err.contains("out of sync"), "{err}"); |
| 7987 | } |
| 7988 | |
| 7989 | /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays |
| 7990 | /// there -- cannot close without cutting that audio out from under |
| 7991 | /// nothing asked to touch it: refused, not widened silently past. |
| 7992 | #[test] |
| 7993 | fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() { |
| 7994 | let sources = vec![Source::new(FILE, 0)]; |
| 7995 | let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)]; |
| 7996 | // A1 plays through the whole span as one continuous clip, sharing |
| 7997 | // V1's first-half link: nothing empty at frame 3 there at all. |
| 7998 | let audio = vec![linked(0, 0, 9, 1)]; |
| 7999 | let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new()) |
| 8000 | .expect("valid parts"); |
| 8001 | assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2))); |
| 8002 | assert_eq!(p.gap_at(Lane::A1, 3), None, "A1 plays through, no gap there"); |
| 8003 | |
| 8004 | let err = p |
| 8005 | .gap_take_scope(Lane::V1, 3, 2) |
| 8006 | .expect_err("a solid partner cannot ripple with the gap") |
| 8007 | .to_string(); |
| 8008 | assert!(err.contains("A1"), "{err}"); |
| 8009 | assert!(err.contains("detach"), "{err}"); |
| 8010 | } |
| 8011 | |
| 8012 | |
| 8013 | /// The sweep is the single-gap close repeated on one lane, but measured once |
| 8014 | /// and applied from the right. The differing gap lengths here expose a |
| 8015 | /// front-to-back bug: the last clip would be cut against a stale frame after |
| 8016 | /// the first gap shifted it. |
| 8017 | #[test] |
| 8018 | fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() { |
| 8019 | let mut p = Project::single(FILE, 1); |
| 8020 | let v = p.add_lane(LaneKind::Video); |
| 8021 | assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)"); |
| 8022 | assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)"); |
| 8023 | assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)"); |
| 8024 | let before = shape(&p); |
| 8025 | |
| 8026 | assert_eq!(p.gap_count(v), 3); |
| 8027 | let report = p.close_all_gaps_on_lane(v).expect("the lane exists"); |
| 8028 | assert_eq!(report.closed, 3); |
| 8029 | assert!(report.skipped.is_empty()); |
| 8030 | assert_eq!( |
| 8031 | p.lane(v), |
| 8032 | &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)], |
| 8033 | "all gaps closed without eating source frames" |
| 8034 | ); |
| 8035 | assert!(p.undo(), "one undo for the whole sweep"); |
| 8036 | assert_eq!(shape(&p), before); |
| 8037 | } |
| 8038 | |
| 8039 | /// Empty, already-contiguous and tail-only lanes are not controls that do |
| 8040 | /// work. A single clip with a head gap does close, because there is a real |
| 8041 | /// placement to ripple back. |
| 8042 | #[test] |
| 8043 | fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() { |
| 8044 | let mut p = Project::single(FILE, 9); |
| 8045 | let v = p.add_lane(LaneKind::Video); |
| 8046 | let history = p.history.len(); |
| 8047 | let report = p.close_all_gaps_on_lane(v).expect("empty lane exists"); |
| 8048 | assert_eq!(report, GapSweep::default(), "an empty lane has no bounded gap"); |
| 8049 | assert_eq!(p.history.len(), history, "no undo step for a no-op"); |
| 8050 | |
| 8051 | let mut p = Project::single(FILE, 9); |
| 8052 | let v = p.add_lane(LaneKind::Video); |
| 8053 | assert!(p.place(v, 5, clip(5, 0, 3, 0))); |
| 8054 | let before = shape(&p); |
| 8055 | let report = p.close_all_gaps_on_lane(v).expect("single clip lane exists"); |
| 8056 | assert_eq!(report.closed, 1, "the head gap closes"); |
| 8057 | assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]); |
| 8058 | assert!(p.undo()); |
| 8059 | assert_eq!(shape(&p), before); |
| 8060 | |
| 8061 | let mut p = Project::single(FILE, 9); |
| 8062 | let history = p.history.len(); |
| 8063 | let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists"); |
| 8064 | assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps"); |
| 8065 | assert_eq!(p.history.len(), history); |
| 8066 | |
| 8067 | let mut p = Project::single(FILE, 9); |
| 8068 | let v = p.add_lane(LaneKind::Video); |
| 8069 | assert!(p.place(v, 0, clip(0, 0, 3, 0))); |
| 8070 | let history = p.history.len(); |
| 8071 | let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists"); |
| 8072 | assert_eq!(report, GapSweep::default(), "the open-ended tail is not closed"); |
| 8073 | assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]); |
| 8074 | assert_eq!(p.history.len(), history); |
| 8075 | } |
| 8076 | |
| 8077 | /// A sweep closes the gaps that satisfy the linked-take rule and leaves the |
| 8078 | /// rest in place with a count and reason. Here [2,4) matches on both lanes, |
| 8079 | /// while V1's [6,9) has only [6,8) empty on A1. |
| 8080 | #[test] |
| 8081 | fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() { |
| 8082 | let sources = vec![Source::new(FILE, 0)]; |
| 8083 | let video = vec![ |
| 8084 | linked(0, 0, 2, 1), |
| 8085 | linked(4, 4, 6, 2), |
| 8086 | clip(9, 9, 11, 0), |
| 8087 | ]; |
| 8088 | let audio = vec![ |
| 8089 | linked(0, 0, 2, 1), |
| 8090 | linked(4, 4, 6, 2), |
| 8091 | clip(8, 8, 11, 0), |
| 8092 | ]; |
| 8093 | let mut p = |
| 8094 | Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new()) |
| 8095 | .expect("valid parts"); |
| 8096 | let before = shape(&p); |
| 8097 | |
| 8098 | let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists"); |
| 8099 | assert_eq!(report.closed, 1); |
| 8100 | assert_eq!(report.skipped.len(), 1); |
| 8101 | assert_eq!(report.skipped[0].start, 6); |
| 8102 | assert!(report.skipped[0].reason.contains("A1"), "{report:?}"); |
| 8103 | assert!(report.skipped[0].reason.contains("out of sync"), "{report:?}"); |
| 8104 | |
| 8105 | assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved"); |
| 8106 | assert_eq!(p.lane(Lane::A1)[1].start, 2, "and its other half stayed in sync"); |
| 8107 | assert_eq!(p.lane(Lane::V1)[2].start, 7, "the skipped later gap remains"); |
| 8108 | assert_eq!(p.lane(Lane::A1)[2].start, 6, "A1's shorter gap remains shorter"); |
| 8109 | links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole"); |
| 8110 | assert!(p.undo(), "one undo restores every closed gap"); |
| 8111 | assert_eq!(shape(&p), before); |
| 8112 | } |
| 8113 | |
| 8114 | /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against |
| 8115 | /// their own caption storage: head gaps and gaps between cues count, an |
| 8116 | /// empty lane and the tail after the last cue do not. |
| 8117 | #[test] |
| 8118 | fn gap_at_finds_the_hole_a_caption_frame_sits_in() { |
| 8119 | let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]); |
| 8120 | let s = p.add_lane(LaneKind::Subtitle); |
| 8121 | assert_eq!(p.gap_at(s, 0), None, "an empty subtitle lane has nothing to close"); |
| 8122 | |
| 8123 | p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)"); |
| 8124 | assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue"); |
| 8125 | assert_eq!(p.gap_at(s, 4), Some((0, 5))); |
| 8126 | assert_eq!(p.gap_at(s, 5), None, "inside the cue"); |
| 8127 | assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap"); |
| 8128 | |
| 8129 | p.place_sub(s, 12, caption(0, 2)).expect("second cue at [12,14)"); |
| 8130 | assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues"); |
| 8131 | assert_eq!(p.gap_at(s, 11), Some((8, 4))); |
| 8132 | assert_eq!(p.gap_at(s, 14), None, "tail after the last cue is still open-ended"); |
| 8133 | } |
| 8134 | |
| 8135 | /// Closing a caption gap ripples the subtitle lane only. It is not a media |
| 8136 | /// take close, so the video and audio lanes keep their frame positions. |
| 8137 | #[test] |
| 8138 | fn closing_a_caption_gap_ripples_no_video_or_audio_clips() { |
| 8139 | let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]); |
| 8140 | let s = p.add_lane(LaneKind::Subtitle); |
| 8141 | p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)"); |
| 8142 | let before_clips = shape(&p); |
| 8143 | let before_subs = p.sub_lane(s).to_vec(); |
| 8144 | |
| 8145 | let (start, len) = p.gap_at(s, 0).expect("gap before the caption"); |
| 8146 | assert_eq!((start, len), (0, 5)); |
| 8147 | p.cut_regions(&[(start, len)], &[s]).expect("caption lane gap closes"); |
| 8148 | |
| 8149 | assert_eq!(shape(&p), before_clips, "media lanes did not move"); |
| 8150 | assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left"); |
| 8151 | assert!(p.undo(), "one undo restores the caption close"); |
| 8152 | assert_eq!(shape(&p), before_clips); |
| 8153 | assert_eq!(p.sub_lane(s), before_subs); |
| 8154 | } |
| 8155 | |
| 8156 | /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on |
| 8157 | /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no |
| 8158 | /// history entry for empty or already-contiguous lanes. |
| 8159 | #[test] |
| 8160 | fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() { |
| 8161 | let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]); |
| 8162 | let s = p.add_lane(LaneKind::Subtitle); |
| 8163 | let history = p.history.len(); |
| 8164 | let report = p.close_all_gaps_on_lane(s).expect("empty subtitle lane exists"); |
| 8165 | assert_eq!(report, GapSweep::default(), "empty subtitle lane has no bounded gap"); |
| 8166 | assert_eq!(p.history.len(), history, "empty sweep is not an undo step"); |
| 8167 | |
| 8168 | p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)"); |
| 8169 | p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)"); |
| 8170 | p.place_sub(s, 14, caption(0, 1)).expect("middle gap [9,14), tail after 15"); |
| 8171 | let before = p.sub_lane(s).to_vec(); |
| 8172 | |
| 8173 | assert_eq!(p.gap_count(s), 3); |
| 8174 | let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists"); |
| 8175 | assert_eq!(report.closed, 3); |
| 8176 | assert!(report.skipped.is_empty()); |
| 8177 | assert_eq!( |
| 8178 | p.sub_lane(s), |
| 8179 | &[caption(0, 2), caption(2, 2), caption(4, 1)], |
| 8180 | "all bounded caption gaps closed without touching windows" |
| 8181 | ); |
| 8182 | assert!(p.undo(), "one undo restores every caption gap"); |
| 8183 | assert_eq!(p.sub_lane(s), before); |
| 8184 | |
| 8185 | let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]); |
| 8186 | let s = p.add_lane(LaneKind::Subtitle); |
| 8187 | p.place_sub(s, 0, caption(0, 3)).expect("contiguous at the head"); |
| 8188 | let history = p.history.len(); |
| 8189 | let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists"); |
| 8190 | assert_eq!(report, GapSweep::default(), "the open tail is not closed"); |
| 8191 | assert_eq!(p.sub_lane(s), &[caption(0, 3)]); |
| 8192 | assert_eq!(p.history.len(), history); |
| 8193 | } |
| 8194 | |
| 8195 | #[test] |
| 8196 | fn ripple_delete_spans_partial_clips() { |
| 8197 | let mut p = three(); |
| 8198 | // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2. |
| 8199 | assert!(p.ripple_delete(2, 4)); |
| 8200 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]); |
| 8201 | assert_eq!(shape(&p)[1], shape(&p)[0]); |
| 8202 | assert_eq!(p.timeline_frames(), 5); |
| 8203 | assert!(!p.ripple_delete(0, 0), "an empty range is not a delete"); |
| 8204 | assert!(p.undo()); |
| 8205 | assert_eq!(shape(&p), shape(&three())); |
| 8206 | // One that takes everything is a delete like any other: the timeline |
| 8207 | // empties, and the undo it cost brings it back whole. |
| 8208 | assert!(p.ripple_delete(0, 100), "the timeline is emptiable"); |
| 8209 | assert_eq!(p.timeline_frames(), 0); |
| 8210 | assert!( |
| 8211 | !p.ripple_delete(0, 100), |
| 8212 | "and a delete with nothing left to take is not an undo step" |
| 8213 | ); |
| 8214 | assert!(p.undo()); |
| 8215 | assert_eq!(shape(&p), shape(&three())); |
| 8216 | } |
| 8217 | |
| 8218 | #[test] |
| 8219 | fn undo_restores_exactly() { |
| 8220 | let mut p = three(); |
| 8221 | let after_splits = shape(&p); |
| 8222 | assert!(p.delete(1)); |
| 8223 | assert!(p.undo()); |
| 8224 | assert_eq!(shape(&p), after_splits); |
| 8225 | |
| 8226 | // walk all the way back through both splits, then run dry |
| 8227 | assert!(p.undo()); |
| 8228 | assert_eq!(p.clips().len(), 2); |
| 8229 | assert!(p.undo()); |
| 8230 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); |
| 8231 | assert!(!p.undo(), "empty history"); |
| 8232 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); |
| 8233 | } |
| 8234 | |
| 8235 | #[test] |
| 8236 | fn redo_restores_exactly() { |
| 8237 | let mut p = three(); |
| 8238 | assert!(p.delete(1)); |
| 8239 | let after_delete = p.parts(); |
| 8240 | assert!(p.undo()); |
| 8241 | assert!(p.redo()); |
| 8242 | assert_eq!(p.parts(), after_delete, "redo lands back byte-identical"); |
| 8243 | assert!(!p.redo(), "empty redo stack"); |
| 8244 | } |
| 8245 | |
| 8246 | #[test] |
| 8247 | fn edit_after_undo_empties_redo() { |
| 8248 | let mut p = three(); |
| 8249 | assert!(p.delete(1)); |
| 8250 | assert!(p.undo()); |
| 8251 | assert_eq!(p.redo_len(), 1, "undo left a branch to redo"); |
| 8252 | assert!(p.split(1), "a fresh edit"); |
| 8253 | assert_eq!(p.redo_len(), 0, "the fresh edit clears it"); |
| 8254 | assert!(!p.redo(), "so redo has nothing left"); |
| 8255 | } |
| 8256 | |
| 8257 | #[test] |
| 8258 | fn redo_on_empty_stack_is_false() { |
| 8259 | let mut p = three(); |
| 8260 | assert!(!p.redo(), "nothing has been undone yet"); |
| 8261 | } |
| 8262 | |
| 8263 | /// Past the cap the *oldest* step goes, so a long session undoes exactly |
| 8264 | /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever. |
| 8265 | #[test] |
| 8266 | fn history_stops_at_the_cap() { |
| 8267 | let mut p = Project::single(FILE, 400); |
| 8268 | for frame in 1..=150 { |
| 8269 | assert!(p.split(frame), "split {frame} is an edit"); |
| 8270 | } |
| 8271 | assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept"); |
| 8272 | for step in 0..HISTORY_CAP { |
| 8273 | assert!(p.undo(), "undo {step} is inside the cap"); |
| 8274 | } |
| 8275 | assert!(!p.undo(), "and the 101st has nothing left to take"); |
| 8276 | // 100 undos off 150 splits is the timeline after the 50th: the older |
| 8277 | // steps were dropped, not the newer ones. |
| 8278 | assert_eq!(p.clips().len(), 51); |
| 8279 | } |
| 8280 | |
| 8281 | /// Undo/redo by hand across a split must never merge two takes into one |
| 8282 | /// group by reusing an id. |
| 8283 | #[test] |
| 8284 | fn group_ids_are_never_reused() { |
| 8285 | let mut p = Project::single(FILE, 9); |
| 8286 | assert!(p.split(3)); |
| 8287 | let first = p.clips()[1].link; |
| 8288 | assert!(p.undo()); |
| 8289 | assert!(p.split(5)); |
| 8290 | assert_ne!(p.clips()[1].link, first, "a retired id must not come back"); |
| 8291 | } |
| 8292 | |
| 8293 | #[test] |
| 8294 | fn segments_from_reads_the_audio_lane() { |
| 8295 | let p = three(); |
| 8296 | // mid-clip: partial first segment, whole clips after it |
| 8297 | assert_eq!( |
| 8298 | p.segments_from(4, FPS), |
| 8299 | vec![ |
| 8300 | (Some(0), 4.0 / 30.0, 5.0 / 30.0), |
| 8301 | (Some(0), 5.0 / 30.0, 9.0 / 30.0) |
| 8302 | ] |
| 8303 | ); |
| 8304 | // on a boundary: nothing partial |
| 8305 | assert_eq!( |
| 8306 | p.segments_from(3, FPS), |
| 8307 | vec![ |
| 8308 | (Some(0), 3.0 / 30.0, 5.0 / 30.0), |
| 8309 | (Some(0), 5.0 / 30.0, 9.0 / 30.0) |
| 8310 | ] |
| 8311 | ); |
| 8312 | // from the top: one entry per clip |
| 8313 | assert_eq!(p.segments_from(0, FPS).len(), 3); |
| 8314 | // last clip only |
| 8315 | assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]); |
| 8316 | // past the end / unusable fps |
| 8317 | assert!(p.segments_from(9, FPS).is_empty()); |
| 8318 | assert!(p.segments_from(0, 0.0).is_empty()); |
| 8319 | assert!(p.segments_from(0, f64::NAN).is_empty()); |
| 8320 | } |
| 8321 | |
| 8322 | #[test] |
| 8323 | fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() { |
| 8324 | let mut p = three(); |
| 8325 | assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5) |
| 8326 | assert_eq!( |
| 8327 | p.segments_from(0, FPS), |
| 8328 | vec![ |
| 8329 | (Some(0), 0.0, 3.0 / 30.0), |
| 8330 | (None, 0.0, 2.0 / 30.0), |
| 8331 | (Some(0), 5.0 / 30.0, 9.0 / 30.0), |
| 8332 | ] |
| 8333 | ); |
| 8334 | // The list still covers exactly the timeline: that is what stops the |
| 8335 | // master clock stalling at the hole. |
| 8336 | let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); |
| 8337 | assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}"); |
| 8338 | // Starting inside the gap trims the silence, not the clip after it. |
| 8339 | assert_eq!( |
| 8340 | p.segments_from(4, FPS), |
| 8341 | vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)] |
| 8342 | ); |
| 8343 | // ...and a lane that is nothing but gap is a run of silence. |
| 8344 | assert!(p.lift(Lane::A1, 0)); |
| 8345 | assert!(p.lift(Lane::A1, 0)); |
| 8346 | assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]); |
| 8347 | } |
| 8348 | |
| 8349 | /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9) |
| 8350 | /// of source 0 then [0,4) of source 1. |
| 8351 | fn two_sources() -> Project { |
| 8352 | let mut p = three(); |
| 8353 | let s = p.import(FILE2, 0); |
| 8354 | assert_eq!(s, 1); |
| 8355 | assert!(p.append_clip(s, 4)); |
| 8356 | p |
| 8357 | } |
| 8358 | |
| 8359 | #[test] |
| 8360 | fn import_dedups_and_appends() { |
| 8361 | let mut p = Project::single(FILE, 9); |
| 8362 | assert_eq!(p.sources().len(), 1, "the opened file is source 0"); |
| 8363 | assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0"); |
| 8364 | assert_eq!(p.import(FILE2, 0), 1); |
| 8365 | assert_eq!(p.import(FILE2, 0), 1, "second import of the same path"); |
| 8366 | // ...but the same file on another audio stream is another source: it is |
| 8367 | // what a clip names, and a clip plays exactly one stream. |
| 8368 | assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source"); |
| 8369 | assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair"); |
| 8370 | assert_eq!(p.sources()[2].audio_stream, 1); |
| 8371 | assert!(p.append_clip(2, 4), "a stream entry is placeable"); |
| 8372 | assert!(p.undo()); |
| 8373 | assert_eq!(p.sources().len(), 3); |
| 8374 | assert!(!p.append_clip(3, 5), "unknown source index"); |
| 8375 | assert_eq!(p.clips().len(), 1, "a refusal changes nothing"); |
| 8376 | |
| 8377 | // Two spellings of one real file are one source: this is the case the |
| 8378 | // raw-path comparison above would get wrong. |
| 8379 | let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs"); |
| 8380 | let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs"); |
| 8381 | let mut p = Project::single(here, 9); |
| 8382 | assert_eq!(p.import(detour, 0), 0); |
| 8383 | assert_eq!(p.sources().len(), 1); |
| 8384 | } |
| 8385 | |
| 8386 | #[test] |
| 8387 | fn append_clip_is_one_undo_step() { |
| 8388 | let mut p = two_sources(); |
| 8389 | assert_eq!(p.timeline_frames(), 13); |
| 8390 | assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1)); |
| 8391 | assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane"); |
| 8392 | assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9"); |
| 8393 | assert!(p.undo()); |
| 8394 | assert_eq!(shape(&p), shape(&three()), "one step back to one source"); |
| 8395 | assert_eq!( |
| 8396 | p.sources().len(), |
| 8397 | 2, |
| 8398 | "the orphan source entry stays -- indexes are forever" |
| 8399 | ); |
| 8400 | // ...and it is still usable, so a redo-by-hand costs no reimport. |
| 8401 | assert!(p.append_clip(1, 0)); |
| 8402 | assert_eq!(p.clips()[3].len(), 1, "clamped like `single`"); |
| 8403 | } |
| 8404 | |
| 8405 | #[test] |
| 8406 | fn edits_carry_the_source_along() { |
| 8407 | let mut p = two_sources(); |
| 8408 | // A split inside the second source splits into two source-1 clips. |
| 8409 | assert!(p.split(11)); |
| 8410 | assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1)); |
| 8411 | assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1)); |
| 8412 | |
| 8413 | // A source-1 clip pasted into source-0 territory keeps its file, and so |
| 8414 | // does the source-0 half that got split off around it. |
| 8415 | let copied = p.clips()[4]; |
| 8416 | assert!(p.paste(1, copied)); |
| 8417 | assert_eq!(p.clips()[1].source, 1); |
| 8418 | assert_eq!(p.clips()[1].in_frame, 2); |
| 8419 | assert_eq!(p.clips()[2].source, 0); |
| 8420 | assert!(p.undo()); |
| 8421 | assert_eq!(p.clips()[1].source, 0, "undo restores sources too"); |
| 8422 | } |
| 8423 | |
| 8424 | #[test] |
| 8425 | fn segments_from_names_the_source() { |
| 8426 | let p = two_sources(); |
| 8427 | // Mid-clip in source 0, then the rest of source 0, then source 1 whole. |
| 8428 | assert_eq!( |
| 8429 | p.segments_from(4, FPS), |
| 8430 | vec![ |
| 8431 | (Some(0), 4.0 / 30.0, 5.0 / 30.0), |
| 8432 | (Some(0), 5.0 / 30.0, 9.0 / 30.0), |
| 8433 | (Some(1), 0.0, 4.0 / 30.0), |
| 8434 | ] |
| 8435 | ); |
| 8436 | // Mid-clip in source 1: only that source is left. |
| 8437 | assert_eq!( |
| 8438 | p.segments_from(10, FPS), |
| 8439 | vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)] |
| 8440 | ); |
| 8441 | assert!(p.segments_from(13, FPS).is_empty()); |
| 8442 | // Segments still cover exactly the timeline across the join. |
| 8443 | let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); |
| 8444 | assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9); |
| 8445 | } |
| 8446 | |
| 8447 | #[test] |
| 8448 | fn segments_follow_deletes_and_fps() { |
| 8449 | let mut p = three(); |
| 8450 | assert!(p.delete(0)); |
| 8451 | // source seconds, not timeline: deleting the head does not shift them |
| 8452 | let segs = p.segments_from(0, 25.0); |
| 8453 | assert_eq!( |
| 8454 | segs, |
| 8455 | vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)] |
| 8456 | ); |
| 8457 | let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum(); |
| 8458 | assert!( |
| 8459 | (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, |
| 8460 | "segments must cover exactly the timeline: {played}" |
| 8461 | ); |
| 8462 | } |
| 8463 | |
| 8464 | #[test] |
| 8465 | fn orphan_sources_are_pruned_and_the_clips_reindexed() { |
| 8466 | // Import a second file, undo it: source 1 is now an orphan. |
| 8467 | let mut p = two_sources(); |
| 8468 | assert!(p.undo()); |
| 8469 | let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); |
| 8470 | assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone"); |
| 8471 | assert!(eq.is_empty(), "and a project with no equalizer writes none"); |
| 8472 | assert!(color.is_empty(), "nor a colour it never graded with"); |
| 8473 | assert_eq!( |
| 8474 | lanes, |
| 8475 | two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()), |
| 8476 | "the clips are untouched" |
| 8477 | ); |
| 8478 | |
| 8479 | // Three sources where only the middle one is orphaned: the survivors |
| 8480 | // renumber, and the clips follow. |
| 8481 | let mut p = Project::single(FILE, 9); |
| 8482 | assert_eq!(p.import(FILE2, 0), 1); |
| 8483 | assert_eq!(p.import("/nonexistent/c.mp4", 0), 2); |
| 8484 | assert!(p.append_clip(2, 4)); |
| 8485 | let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); |
| 8486 | assert_eq!( |
| 8487 | sources, |
| 8488 | vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)] |
| 8489 | ); |
| 8490 | assert_eq!( |
| 8491 | lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(), |
| 8492 | [0, 1] |
| 8493 | ); |
| 8494 | // ...and what comes out is loadable, with the same timeline. |
| 8495 | let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts"); |
| 8496 | assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); |
| 8497 | assert_eq!(reloaded.sources().len(), 2); |
| 8498 | } |
| 8499 | |
| 8500 | /// Taking a file out of the library: refused by name -- lanes and counts -- |
| 8501 | /// while a clip still plays from it, and once nothing does, the entry goes |
| 8502 | /// and every clip that indexed past it is renumbered onto the short list. |
| 8503 | #[test] |
| 8504 | fn remove_source_refuses_what_plays_and_renumbers_what_is_left() { |
| 8505 | // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes), |
| 8506 | // plus a second stream of FILE as source 2 with a take of its own. |
| 8507 | let mut p = two_sources(); |
| 8508 | assert_eq!(p.import(FILE, 1), 2, "another stream is another source"); |
| 8509 | assert!(p.append_clip(2, 4)); |
| 8510 | |
| 8511 | let refusal = p |
| 8512 | .remove_source(1) |
| 8513 | .expect_err("a source with clips on it cannot go") |
| 8514 | .to_string(); |
| 8515 | assert!(refusal.contains(FILE2), "names the file: {refusal}"); |
| 8516 | assert!( |
| 8517 | refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"), |
| 8518 | "names the lanes holding it: {refusal}" |
| 8519 | ); |
| 8520 | assert!(refusal.contains("still plays"), "{refusal}"); |
| 8521 | assert_eq!(p.sources().len(), 3, "a refusal changes nothing"); |
| 8522 | assert_eq!(shape(&p)[0][3].source, 1); |
| 8523 | |
| 8524 | // Delete FILE2's take -- the whole span, on every lane -- and the entry |
| 8525 | // is free to go. Source 2's clips become source 1's. |
| 8526 | assert!(p.delete_in(Lane::V1, 3)); |
| 8527 | assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it"); |
| 8528 | p.remove_source(1).expect("nothing plays FILE2 any more"); |
| 8529 | assert_eq!( |
| 8530 | p.sources(), |
| 8531 | [Source::new(FILE, 0), Source::new(FILE, 1)], |
| 8532 | "the middle entry is gone" |
| 8533 | ); |
| 8534 | assert_eq!( |
| 8535 | shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(), |
| 8536 | [0, 0, 0, 1], |
| 8537 | "the clips past it renumbered" |
| 8538 | ); |
| 8539 | assert_eq!( |
| 8540 | shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(), |
| 8541 | [0, 0, 0, 1], |
| 8542 | "on every lane" |
| 8543 | ); |
| 8544 | // What is left is a project that still loads, which is the whole point |
| 8545 | // of renumbering rather than leaving a hole. |
| 8546 | let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); |
| 8547 | Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts"); |
| 8548 | } |
| 8549 | |
| 8550 | /// The two edges of a removal: it retires the undo stack (the corner-cut on |
| 8551 | /// [`Project::remove_source`]), and the last entry goes like any other |
| 8552 | /// once nothing plays it -- a project may name no file at all. |
| 8553 | #[test] |
| 8554 | fn remove_source_retires_undo_and_empties_the_library() { |
| 8555 | let mut p = two_sources(); |
| 8556 | assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first"); |
| 8557 | assert!(!p.history.is_empty(), "there is something to undo"); |
| 8558 | p.remove_source(1).expect("nothing plays FILE2"); |
| 8559 | assert!( |
| 8560 | p.history.is_empty(), |
| 8561 | "a snapshot naming the removed source must not survive it" |
| 8562 | ); |
| 8563 | assert!(!p.undo(), "and so there is nothing left to undo"); |
| 8564 | |
| 8565 | // The last file standing is held to the one rule every row is -- what |
| 8566 | // plays cannot go -- and to no other. |
| 8567 | assert_eq!(p.sources().len(), 1); |
| 8568 | let refusal = p |
| 8569 | .remove_source(0) |
| 8570 | .expect_err("its clips are still on the lanes") |
| 8571 | .to_string(); |
| 8572 | assert!(refusal.contains("still plays"), "{refusal}"); |
| 8573 | assert_eq!(p.sources().len(), 1, "a refusal changes nothing"); |
| 8574 | while p.delete_in(Lane::V1, 0) {} |
| 8575 | p.remove_source(0) |
| 8576 | .expect("the last row goes like any other"); |
| 8577 | assert!( |
| 8578 | p.sources().is_empty(), |
| 8579 | "a project may name no file at all: an empty library over an empty timeline" |
| 8580 | ); |
| 8581 | assert_eq!(p.timeline_frames(), 0); |
| 8582 | assert!( |
| 8583 | p.remove_source(0).is_err(), |
| 8584 | "and an index that is not there is refused, not panicked on" |
| 8585 | ); |
| 8586 | } |
| 8587 | |
| 8588 | /// A clip's equalizer is the clip's: it survives every edit that copies a |
| 8589 | /// placement, and it comes back with an undo. |
| 8590 | #[test] |
| 8591 | fn an_equalizer_follows_the_clip_through_split_copy_and_undo() { |
| 8592 | let mut p = three(); |
| 8593 | assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat"); |
| 8594 | assert!(p.set_eq(Lane::A1, 0, Some(band_at(2)))); |
| 8595 | assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); |
| 8596 | assert!( |
| 8597 | p.eq_of(Lane::V1, 0).is_none(), |
| 8598 | "one clip, not the lane above" |
| 8599 | ); |
| 8600 | |
| 8601 | // Cutting an EQ'd clip must not silence half of it: both halves inherit. |
| 8602 | assert!(p.split(1)); |
| 8603 | assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); |
| 8604 | assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2))); |
| 8605 | assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat"); |
| 8606 | |
| 8607 | // A clipboard copy carries it -- onto another lane, at that. |
| 8608 | let copied = p.lane(Lane::A1)[1]; |
| 8609 | assert!(p.place(Lane::V1, 20, copied)); |
| 8610 | assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2))); |
| 8611 | assert!(p.undo()); |
| 8612 | assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off"); |
| 8613 | |
| 8614 | // ...and a change to one is one undo step, in both directions. |
| 8615 | assert!(p.set_eq(Lane::A1, 0, Some(band_at(5)))); |
| 8616 | assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5))); |
| 8617 | assert!(p.undo()); |
| 8618 | assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); |
| 8619 | assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit"); |
| 8620 | assert!(p.eq_of(Lane::A1, 0).is_none()); |
| 8621 | assert!(p.undo()); |
| 8622 | assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); |
| 8623 | |
| 8624 | // Two refusals, neither of which costs an undo step. |
| 8625 | let mut nan = band_at(1); |
| 8626 | nan.bands[0].q = f32::INFINITY; |
| 8627 | assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there"); |
| 8628 | assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band"); |
| 8629 | assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); |
| 8630 | assert!(p.undo()); |
| 8631 | assert_eq!( |
| 8632 | p.lane(Lane::A1).len(), |
| 8633 | 3, |
| 8634 | "one step back is before the split" |
| 8635 | ); |
| 8636 | assert!(p.undo()); |
| 8637 | assert!( |
| 8638 | p.eq_of(Lane::A1, 0).is_none(), |
| 8639 | "and the next is before the setting: the refusals pushed none" |
| 8640 | ); |
| 8641 | } |
| 8642 | |
| 8643 | /// The table is append-only within a session, exactly as the sources are, so |
| 8644 | /// an undone setting is still in it -- and a save is where it goes. |
| 8645 | #[test] |
| 8646 | fn an_undone_equalizer_is_pruned_when_the_project_is_saved() { |
| 8647 | let mut p = three(); |
| 8648 | assert!(p.set_eq(Lane::V1, 0, Some(band_at(1)))); |
| 8649 | assert!(p.set_eq(Lane::V1, 0, Some(band_at(2)))); |
| 8650 | assert!(p.undo(), "back to the first setting"); |
| 8651 | assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1))); |
| 8652 | |
| 8653 | let (_, lanes, eq, _, _) = p.without_orphan_sources(); |
| 8654 | assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written"); |
| 8655 | assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers"); |
| 8656 | assert_eq!(lanes[0].1[1].eq, None); |
| 8657 | |
| 8658 | // One curve on three clips is one entry: settings that are equal share. |
| 8659 | assert!(p.set_eq(Lane::V1, 1, Some(band_at(1)))); |
| 8660 | assert!(p.set_eq(Lane::A1, 2, Some(band_at(1)))); |
| 8661 | let (_, lanes, eq, _, _) = p.without_orphan_sources(); |
| 8662 | assert_eq!(eq.len(), 1, "equal settings share their entry"); |
| 8663 | assert_eq!(lanes[1].1[2].eq, Some(0)); |
| 8664 | reloads(&p, "an equalizer that outlived an undo"); |
| 8665 | } |
| 8666 | |
| 8667 | /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a |
| 8668 | /// grade is the clip's, through every edit that copies a placement. |
| 8669 | #[test] |
| 8670 | fn a_colour_follows_the_clip_through_split_copy_and_undo() { |
| 8671 | let mut p = three(); |
| 8672 | assert!( |
| 8673 | p.color_of(Lane::V1, 0).is_none(), |
| 8674 | "a fresh clip is ungraded" |
| 8675 | ); |
| 8676 | assert!(p.set_color(Lane::V1, 0, Some(grade_at(2)))); |
| 8677 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); |
| 8678 | assert!( |
| 8679 | p.color_of(Lane::A1, 0).is_none(), |
| 8680 | "one clip, not the lane below" |
| 8681 | ); |
| 8682 | assert!( |
| 8683 | p.eq_of(Lane::V1, 0).is_none(), |
| 8684 | "and a grade is not an equalizer" |
| 8685 | ); |
| 8686 | |
| 8687 | // Cutting a graded clip must not grade half of it: both halves inherit. |
| 8688 | assert!(p.split(1)); |
| 8689 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); |
| 8690 | assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2))); |
| 8691 | assert!( |
| 8692 | p.color_of(Lane::V1, 2).is_none(), |
| 8693 | "the clip after it is ungraded" |
| 8694 | ); |
| 8695 | |
| 8696 | // A clipboard copy carries it -- onto another lane, at that. |
| 8697 | let copied = p.lane(Lane::V1)[1]; |
| 8698 | assert!(p.place(Lane::A1, 20, copied)); |
| 8699 | assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2))); |
| 8700 | assert!(p.undo()); |
| 8701 | assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off"); |
| 8702 | |
| 8703 | // ...and a change to one is one undo step, in both directions. |
| 8704 | assert!(p.set_color(Lane::V1, 0, Some(grade_at(5)))); |
| 8705 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5))); |
| 8706 | assert!(p.undo()); |
| 8707 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); |
| 8708 | assert!( |
| 8709 | p.set_color(Lane::V1, 0, None), |
| 8710 | "and taking it off is an edit" |
| 8711 | ); |
| 8712 | assert!(p.color_of(Lane::V1, 0).is_none()); |
| 8713 | assert!(p.undo()); |
| 8714 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); |
| 8715 | |
| 8716 | // Two refusals, neither of which costs an undo step. |
| 8717 | let nan = ColorParams { |
| 8718 | contrast: f32::NAN, |
| 8719 | ..grade_at(1) |
| 8720 | }; |
| 8721 | assert!( |
| 8722 | !p.set_color(Lane::V1, 99, Some(grade_at(1))), |
| 8723 | "no clip there" |
| 8724 | ); |
| 8725 | assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value"); |
| 8726 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); |
| 8727 | assert!(p.undo()); |
| 8728 | assert_eq!( |
| 8729 | p.lane(Lane::V1).len(), |
| 8730 | 3, |
| 8731 | "one step back is before the split" |
| 8732 | ); |
| 8733 | assert!(p.undo()); |
| 8734 | assert!( |
| 8735 | p.color_of(Lane::V1, 0).is_none(), |
| 8736 | "and the next is before the grade: the refusals pushed none" |
| 8737 | ); |
| 8738 | } |
| 8739 | |
| 8740 | /// A slider drag is one gesture: the press snapshots, every sample after it |
| 8741 | /// only regrades, and the single undo lands on what the clip was *before* |
| 8742 | /// the hand touched it -- not one step back down the drag. |
| 8743 | #[test] |
| 8744 | fn a_whole_colour_drag_undoes_in_one_step() { |
| 8745 | let mut p = three(); |
| 8746 | assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press"); |
| 8747 | for n in 2..=8 { |
| 8748 | assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample"); |
| 8749 | } |
| 8750 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8))); |
| 8751 | assert!(p.undo()); |
| 8752 | assert!( |
| 8753 | p.color_of(Lane::V1, 0).is_none(), |
| 8754 | "one undo is the whole gesture, back to ungraded" |
| 8755 | ); |
| 8756 | |
| 8757 | // The live write refuses what the snapshotting one refuses, and a |
| 8758 | // refusal still costs no history either way. |
| 8759 | assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1)))); |
| 8760 | assert!(!p.set_color_live( |
| 8761 | Lane::V1, |
| 8762 | 0, |
| 8763 | Some(ColorParams { |
| 8764 | contrast: f32::NAN, |
| 8765 | ..grade_at(1) |
| 8766 | }) |
| 8767 | )); |
| 8768 | assert!(p.undo()); |
| 8769 | assert_eq!( |
| 8770 | p.lane(Lane::V1).len(), |
| 8771 | 2, |
| 8772 | "the next step back is the split before the drag: no sample pushed one" |
| 8773 | ); |
| 8774 | } |
| 8775 | |
| 8776 | /// The colour table is append-only within a session, exactly as the eq one |
| 8777 | /// is -- and a save is where an undone grade goes. |
| 8778 | #[test] |
| 8779 | fn an_undone_colour_is_pruned_when_the_project_is_saved() { |
| 8780 | let mut p = three(); |
| 8781 | assert!(p.set_color(Lane::V1, 0, Some(grade_at(1)))); |
| 8782 | assert!(p.set_color(Lane::V1, 0, Some(grade_at(2)))); |
| 8783 | assert!(p.undo(), "back to the first grade"); |
| 8784 | assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1))); |
| 8785 | |
| 8786 | let (_, lanes, _, color, _) = p.without_orphan_sources(); |
| 8787 | assert_eq!( |
| 8788 | color, |
| 8789 | vec![grade_at(1)], |
| 8790 | "what nothing plays is not written" |
| 8791 | ); |
| 8792 | assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers"); |
| 8793 | assert_eq!(lanes[0].1[1].color, None); |
| 8794 | |
| 8795 | // One grade on three clips is one entry: settings that are equal share. |
| 8796 | assert!(p.set_color(Lane::V1, 1, Some(grade_at(1)))); |
| 8797 | assert!(p.set_color(Lane::A1, 2, Some(grade_at(1)))); |
| 8798 | let (_, lanes, _, color, _) = p.without_orphan_sources(); |
| 8799 | assert_eq!(color.len(), 1, "equal grades share their entry"); |
| 8800 | assert_eq!(lanes[1].1[2].color, Some(0)); |
| 8801 | reloads(&p, "a colour that outlived an undo"); |
| 8802 | |
| 8803 | // An equalizer and a grade on one clip are two independent tables. |
| 8804 | assert!(p.set_eq(Lane::V1, 0, Some(band_at(3)))); |
| 8805 | let (_, lanes, eq, color, _) = p.without_orphan_sources(); |
| 8806 | assert_eq!((eq.len(), color.len()), (1, 1)); |
| 8807 | assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0))); |
| 8808 | } |
| 8809 | |
| 8810 | /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a |
| 8811 | /// placement is the clip's, through every edit that copies one. |
| 8812 | #[test] |
| 8813 | fn a_transform_follows_the_clip_through_split_copy_and_undo() { |
| 8814 | let mut p = three(); |
| 8815 | assert!( |
| 8816 | p.transform_of(Lane::V1, 0).is_none(), |
| 8817 | "a fresh clip is untransformed" |
| 8818 | ); |
| 8819 | assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2)))); |
| 8820 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); |
| 8821 | assert!( |
| 8822 | p.transform_of(Lane::A1, 0).is_none(), |
| 8823 | "one clip, not the lane below" |
| 8824 | ); |
| 8825 | assert!( |
| 8826 | p.color_of(Lane::V1, 0).is_none(), |
| 8827 | "and a placement is not a grade" |
| 8828 | ); |
| 8829 | |
| 8830 | // Cutting a transformed clip must not transform half of it: both |
| 8831 | // halves inherit. |
| 8832 | assert!(p.split(1)); |
| 8833 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); |
| 8834 | assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2))); |
| 8835 | assert!( |
| 8836 | p.transform_of(Lane::V1, 2).is_none(), |
| 8837 | "the clip after it is untransformed" |
| 8838 | ); |
| 8839 | |
| 8840 | // A clipboard copy carries it -- onto another lane, at that. |
| 8841 | let copied = p.lane(Lane::V1)[1]; |
| 8842 | assert!(p.place(Lane::A1, 20, copied)); |
| 8843 | assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2))); |
| 8844 | assert!(p.undo()); |
| 8845 | assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off"); |
| 8846 | |
| 8847 | // ...and a change to one is one undo step, in both directions. |
| 8848 | assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5)))); |
| 8849 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5))); |
| 8850 | assert!(p.undo()); |
| 8851 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); |
| 8852 | assert!( |
| 8853 | p.set_transform(Lane::V1, 0, None), |
| 8854 | "and taking it off is an edit" |
| 8855 | ); |
| 8856 | assert!(p.transform_of(Lane::V1, 0).is_none()); |
| 8857 | assert!(p.undo()); |
| 8858 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); |
| 8859 | |
| 8860 | // Two refusals, neither of which costs an undo step. |
| 8861 | let nan = TransformParams { |
| 8862 | scale: f32::NAN, |
| 8863 | ..transform_at(1) |
| 8864 | }; |
| 8865 | assert!( |
| 8866 | !p.set_transform(Lane::V1, 99, Some(transform_at(1))), |
| 8867 | "no clip there" |
| 8868 | ); |
| 8869 | assert!( |
| 8870 | !p.set_transform(Lane::V1, 0, Some(nan)), |
| 8871 | "not a finite value" |
| 8872 | ); |
| 8873 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2))); |
| 8874 | assert!(p.undo()); |
| 8875 | assert_eq!( |
| 8876 | p.lane(Lane::V1).len(), |
| 8877 | 3, |
| 8878 | "one step back is before the split" |
| 8879 | ); |
| 8880 | assert!(p.undo()); |
| 8881 | assert!( |
| 8882 | p.transform_of(Lane::V1, 0).is_none(), |
| 8883 | "and the next is before the placement: the refusals pushed none" |
| 8884 | ); |
| 8885 | } |
| 8886 | |
| 8887 | /// The transform table is append-only within a session, exactly as the eq |
| 8888 | /// and colour ones are -- and a save is where an undone placement goes. |
| 8889 | #[test] |
| 8890 | fn an_undone_transform_is_pruned_when_the_project_is_saved() { |
| 8891 | let mut p = three(); |
| 8892 | assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1)))); |
| 8893 | assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2)))); |
| 8894 | assert!(p.undo(), "back to the first placement"); |
| 8895 | assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1))); |
| 8896 | |
| 8897 | let (_, lanes, _, _, transform) = p.without_orphan_sources(); |
| 8898 | assert_eq!( |
| 8899 | transform, |
| 8900 | vec![transform_at(1)], |
| 8901 | "what nothing plays is not written" |
| 8902 | ); |
| 8903 | assert_eq!( |
| 8904 | lanes[0].1[0].transform, |
| 8905 | Some(0), |
| 8906 | "and the survivor renumbers" |
| 8907 | ); |
| 8908 | assert_eq!(lanes[0].1[1].transform, None); |
| 8909 | |
| 8910 | // One placement on three clips is one entry: settings that are equal |
| 8911 | // share. |
| 8912 | assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1)))); |
| 8913 | assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1)))); |
| 8914 | let (_, lanes, _, _, transform) = p.without_orphan_sources(); |
| 8915 | assert_eq!(transform.len(), 1, "equal placements share their entry"); |
| 8916 | assert_eq!(lanes[1].1[2].transform, Some(0)); |
| 8917 | reloads(&p, "a transform that outlived an undo"); |
| 8918 | |
| 8919 | // A grade and a placement on one clip are two independent tables. |
| 8920 | assert!(p.set_color(Lane::V1, 0, Some(grade_at(3)))); |
| 8921 | let (_, lanes, _, color, transform) = p.without_orphan_sources(); |
| 8922 | assert_eq!((color.len(), transform.len()), (1, 1)); |
| 8923 | assert_eq!( |
| 8924 | (lanes[0].1[0].color, lanes[0].1[0].transform), |
| 8925 | (Some(0), Some(0)) |
| 8926 | ); |
| 8927 | } |
| 8928 | |
| 8929 | /// Not a claim about correctness but about cost: a clip is copied on every |
| 8930 | /// paste, every undo snapshot and every lane clone, so its size is worth |
| 8931 | /// knowing. The eq index fit the padding a `Copy` clip already had; the |
| 8932 | /// colour one did not, and the struct grew a word. The transform index is |
| 8933 | /// a third `Option<u16>`, and it fits the padding the fit policy and the |
| 8934 | /// transition byte already left behind, so the struct did not grow again. |
| 8935 | #[test] |
| 8936 | fn a_clip_is_still_a_small_copy() { |
| 8937 | assert_eq!( |
| 8938 | std::mem::size_of::<Clip>(), |
| 8939 | 56, |
| 8940 | "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index" |
| 8941 | ); |
| 8942 | } |
| 8943 | |
| 8944 | #[test] |
| 8945 | fn from_parts_has_no_history_and_checks_the_invariants() { |
| 8946 | let (sources, lanes, eq, color, _transform) = three().without_orphan_sources(); |
| 8947 | let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone()); |
| 8948 | let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new()) |
| 8949 | .expect("valid parts"); |
| 8950 | assert_eq!(p.clips(), three().clips()); |
| 8951 | assert!(!p.undo(), "a loaded project has nothing to undo"); |
| 8952 | assert!(p.split(4), "...and is editable from there"); |
| 8953 | assert!(p.undo()); |
| 8954 | |
| 8955 | // A lane may be empty, and so may every lane -- an emptied timeline is a |
| 8956 | // project. No lane at all is not one: there would be nothing to place on. |
| 8957 | assert!( |
| 8958 | Project::from_parts( |
| 8959 | sources.clone(), |
| 8960 | two(video.clone(), Vec::new()), |
| 8961 | Vec::new(), |
| 8962 | Vec::new(), |
| 8963 | Vec::new(), |
| 8964 | ) |
| 8965 | .is_ok() |
| 8966 | ); |
| 8967 | assert!( |
| 8968 | Project::from_parts( |
| 8969 | sources.clone(), |
| 8970 | two(Vec::new(), Vec::new()), |
| 8971 | Vec::new(), |
| 8972 | Vec::new(), |
| 8973 | Vec::new(), |
| 8974 | ) |
| 8975 | .is_ok() |
| 8976 | ); |
| 8977 | assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err()); |
| 8978 | let bad: [Vec<Clip>; 5] = [ |
| 8979 | vec![clip(0, 0, 3, 1)], // source that is not there |
| 8980 | vec![clip(0, 3, 3, 0)], // empty clip |
| 8981 | vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order |
| 8982 | vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping |
| 8983 | vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame |
| 8984 | ]; |
| 8985 | for clips in bad { |
| 8986 | assert!( |
| 8987 | Project::from_parts( |
| 8988 | sources.clone(), |
| 8989 | two(clips.clone(), Vec::new()), |
| 8990 | Vec::new(), |
| 8991 | Vec::new(), |
| 8992 | Vec::new(), |
| 8993 | ) |
| 8994 | .is_err(), |
| 8995 | "{clips:?}" |
| 8996 | ); |
| 8997 | assert!( |
| 8998 | Project::from_parts( |
| 8999 | sources.clone(), |
| 9000 | two(video.clone(), clips.clone()), |
| 9001 | Vec::new(), |
| 9002 | Vec::new(), |
| 9003 | Vec::new(), |
| 9004 | ) |
| 9005 | .is_err() |
| 9006 | ); |
| 9007 | // ...and on a third lane, which is checked by the same walk. |
| 9008 | assert!( |
| 9009 | Project::from_parts( |
| 9010 | sources.clone(), |
| 9011 | vec![ |
| 9012 | (LaneKind::Video, video.clone()), |
| 9013 | (LaneKind::Audio, audio.clone()), |
| 9014 | (LaneKind::Video, clips), |
| 9015 | ], |
| 9016 | Vec::new(), |
| 9017 | Vec::new(), |
| 9018 | Vec::new(), |
| 9019 | ) |
| 9020 | .is_err() |
| 9021 | ); |
| 9022 | } |
| 9023 | // An equalizer index no table entry answers, and a table entry the file |
| 9024 | // format could not have written, are refused at this door too. |
| 9025 | let eqd = |i: u16| { |
| 9026 | vec![Clip { |
| 9027 | fade_in: 0, |
| 9028 | fade_out: 0, |
| 9029 | transition_out: 0, |
| 9030 | eq: Some(i), |
| 9031 | ..video[0] |
| 9032 | }] |
| 9033 | }; |
| 9034 | assert!( |
| 9035 | Project::from_parts( |
| 9036 | sources.clone(), |
| 9037 | two(eqd(0), Vec::new()), |
| 9038 | Vec::new(), |
| 9039 | Vec::new(), |
| 9040 | Vec::new(), |
| 9041 | ) |
| 9042 | .is_err() |
| 9043 | ); |
| 9044 | let mut nan = band_at(1); |
| 9045 | nan.bands[0].freq_hz = f32::NAN; |
| 9046 | assert!( |
| 9047 | Project::from_parts( |
| 9048 | sources.clone(), |
| 9049 | two(eqd(0), Vec::new()), |
| 9050 | vec![nan], |
| 9051 | Vec::new(), |
| 9052 | Vec::new(), |
| 9053 | ) |
| 9054 | .is_err() |
| 9055 | ); |
| 9056 | let loaded = Project::from_parts( |
| 9057 | sources.clone(), |
| 9058 | two(eqd(0), Vec::new()), |
| 9059 | vec![band_at(1)], |
| 9060 | Vec::new(), |
| 9061 | Vec::new(), |
| 9062 | ) |
| 9063 | .expect("an eq the table holds"); |
| 9064 | assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1))); |
| 9065 | |
| 9066 | // The same two refusals for a colour, at the same door. |
| 9067 | let graded = |i: u16| { |
| 9068 | vec![Clip { |
| 9069 | fade_in: 0, |
| 9070 | fade_out: 0, |
| 9071 | transition_out: 0, |
| 9072 | color: Some(i), |
| 9073 | fit: FitPolicy::default(), |
| 9074 | speed: Speed::NORMAL, |
| 9075 | ..video[0] |
| 9076 | }] |
| 9077 | }; |
| 9078 | assert!( |
| 9079 | Project::from_parts( |
| 9080 | sources.clone(), |
| 9081 | two(graded(0), Vec::new()), |
| 9082 | Vec::new(), |
| 9083 | Vec::new(), |
| 9084 | Vec::new(), |
| 9085 | ) |
| 9086 | .is_err(), |
| 9087 | "a colour index no entry answers" |
| 9088 | ); |
| 9089 | assert!( |
| 9090 | Project::from_parts( |
| 9091 | sources.clone(), |
| 9092 | two(graded(0), Vec::new()), |
| 9093 | Vec::new(), |
| 9094 | vec![ColorParams { |
| 9095 | tint: f32::NAN, |
| 9096 | ..grade_at(1) |
| 9097 | }], |
| 9098 | Vec::new(), |
| 9099 | ) |
| 9100 | .is_err(), |
| 9101 | "a value the file format could not have written" |
| 9102 | ); |
| 9103 | let loaded = Project::from_parts( |
| 9104 | sources.clone(), |
| 9105 | two(graded(0), Vec::new()), |
| 9106 | Vec::new(), |
| 9107 | vec![grade_at(1)], |
| 9108 | Vec::new(), |
| 9109 | ) |
| 9110 | .expect("a colour the table holds"); |
| 9111 | assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1))); |
| 9112 | |
| 9113 | // Group ids survive a load, and the next split gets a fresh one. |
| 9114 | let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts"); |
| 9115 | assert!(p.split(4)); |
| 9116 | assert!(p.clips().iter().all(|c| c.link.is_some())); |
| 9117 | } |
| 9118 | |
| 9119 | /// The grouping rules, at the untrusted door and after every edit that can |
| 9120 | /// touch a link. A link id is at most one placement per lane -- a clip or a |
| 9121 | /// caption, whichever carries it -- and no sequence of edits may produce |
| 9122 | /// otherwise, because what an edit produces is what a save writes and a load |
| 9123 | /// reads. |
| 9124 | /// |
| 9125 | /// Amended for the offset-preserving group: the members keep their own |
| 9126 | /// spans, so two placements of one id covering different frames is *legal* |
| 9127 | /// -- it is what a hand-built group is -- and the only refusal left is the |
| 9128 | /// doubled id inside one lane. |
| 9129 | #[test] |
| 9130 | fn a_link_id_is_never_two_clips_of_one_lane() { |
| 9131 | let sources = vec![Source::new(FILE, 0)]; |
| 9132 | let linked = |start, in_frame, out_frame, link| Clip { |
| 9133 | fade_in: 0, |
| 9134 | fade_out: 0, |
| 9135 | transition_out: 0, |
| 9136 | start, |
| 9137 | in_frame, |
| 9138 | out_frame, |
| 9139 | source: 0, |
| 9140 | link: Some(link), |
| 9141 | eq: None, |
| 9142 | color: None, |
| 9143 | transform: None, |
| 9144 | fit: FitPolicy::default(), |
| 9145 | speed: Speed::NORMAL, |
| 9146 | }; |
| 9147 | |
| 9148 | // The door: a doubled id inside one lane, refused by name. |
| 9149 | let err = |video: Vec<Clip>, audio: Vec<Clip>| { |
| 9150 | Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new()) |
| 9151 | .expect_err("refused") |
| 9152 | .to_string() |
| 9153 | }; |
| 9154 | assert!( |
| 9155 | err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new()) |
| 9156 | .contains("link 7 names two clips in the V1 lane"), |
| 9157 | "a duplicate id inside one lane is refused by name" |
| 9158 | ); |
| 9159 | // ...and the same doubling on a subtitle lane, in its own words: a |
| 9160 | // caption is the other placement an id may name. |
| 9161 | let caption = |start: u32, frames: u32, link| SubClip { |
| 9162 | start, |
| 9163 | frames, |
| 9164 | track: 0, |
| 9165 | in_us: 0, |
| 9166 | out_us: i64::from(frames) * 1_000_000, |
| 9167 | link: Some(link), |
| 9168 | }; |
| 9169 | let subs = LaneData { |
| 9170 | clips: Vec::new(), |
| 9171 | subs: vec![caption(0, 3, 7), caption(4, 3, 7)], |
| 9172 | ..LaneData::new(LaneKind::Subtitle, Vec::new()) |
| 9173 | }; |
| 9174 | assert_eq!( |
| 9175 | links_are_consistent(&[subs]).unwrap_err().to_string(), |
| 9176 | "link 7 names two captions in the S1 lane" |
| 9177 | ); |
| 9178 | // A pair covering *different* frames is legal now: the members of a |
| 9179 | // hand-built group keep their own spans, and what binds them is the id. |
| 9180 | let apart = Project::from_parts( |
| 9181 | sources.clone(), |
| 9182 | two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]), |
| 9183 | Vec::new(), |
| 9184 | Vec::new(), |
| 9185 | Vec::new(), |
| 9186 | ); |
| 9187 | assert!(apart.is_ok(), "offsets within one group load: {apart:?}"); |
| 9188 | // A one-sided link is *not* an error: it is what a lift leaves behind. |
| 9189 | let mut p = Project::single(FILE, 9); |
| 9190 | assert!(p.lift(Lane::A1, 0)); |
| 9191 | let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources(); |
| 9192 | assert!( |
| 9193 | Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(), |
| 9194 | "a lifted lane's project has to load again" |
| 9195 | ); |
| 9196 | |
| 9197 | // The edits: nothing below may break either rule. |
| 9198 | let consistent = |p: &Project, what: &str| { |
| 9199 | assert!( |
| 9200 | links_are_consistent(&p.lanes).is_ok(), |
| 9201 | "{what}: {:?}", |
| 9202 | p.lanes |
| 9203 | ); |
| 9204 | }; |
| 9205 | let mut p = three(); |
| 9206 | let copied = p.clips()[0]; |
| 9207 | assert!( |
| 9208 | copied.link.is_some(), |
| 9209 | "the clipboard clip carries its group" |
| 9210 | ); |
| 9211 | assert!(p.lift(Lane::V1, 0)); |
| 9212 | assert!(p.place(Lane::V1, 0, copied)); |
| 9213 | assert!(p.place(Lane::V1, 20, copied), "and again, further out"); |
| 9214 | assert_eq!( |
| 9215 | p.clips().iter().filter(|c| c.link == copied.link).count(), |
| 9216 | 0, |
| 9217 | "a placement belongs to no group, so it cannot duplicate one" |
| 9218 | ); |
| 9219 | consistent(&p, "lift + place twice"); |
| 9220 | assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle"); |
| 9221 | consistent(&p, "place through a grouped clip"); |
| 9222 | assert!(p.paste(6, copied), "a rippling paste through another"); |
| 9223 | consistent(&p, "paste"); |
| 9224 | assert!(p.split(2)); |
| 9225 | consistent(&p, "split"); |
| 9226 | assert!(p.ripple_delete(1, 3)); |
| 9227 | consistent(&p, "ripple_delete"); |
| 9228 | assert!(p.undo()); |
| 9229 | consistent(&p, "undo"); |
| 9230 | } |
| 9231 | |
| 9232 | /// What an edit produces is what a save writes, so *every* state the public |
| 9233 | /// API can reach has to load again. The two the verifier panel found where |
| 9234 | /// it did not: a split and a regroup handed one group id to two clips that |
| 9235 | /// were not the same span, because the lanes had been edited apart. |
| 9236 | #[test] |
| 9237 | fn every_reachable_state_reloads() { |
| 9238 | let mut p = Project::single(FILE, 150); |
| 9239 | assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0))); |
| 9240 | assert!(p.split(10), "the lanes are cut apart at 10"); |
| 9241 | reloads(&p, "place on one lane, then split"); |
| 9242 | |
| 9243 | let mut p = Project::single(FILE, 150); |
| 9244 | assert!(p.split(30)); |
| 9245 | assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays"); |
| 9246 | assert!(p.regroup(30), "only the audio lane can rejoin"); |
| 9247 | assert!(p.split(60)); |
| 9248 | reloads(&p, "lift, regroup one lane, split"); |
| 9249 | |
| 9250 | // Two audio streams of one file, both placed: two source entries with |
| 9251 | // one path between them, which is the state a stream picked out of the |
| 9252 | // library reaches -- and the state a save has to write and read back. |
| 9253 | let mut p = Project::single(FILE, 150); |
| 9254 | let second = p.import(FILE, 1); |
| 9255 | assert_eq!(second, 1, "the same file on another stream is a new source"); |
| 9256 | assert!(p.append_clip(second, 150)); |
| 9257 | assert!(p.split(200)); |
| 9258 | reloads( |
| 9259 | &p, |
| 9260 | "a second audio stream of the same file, placed and split", |
| 9261 | ); |
| 9262 | let (sources, ..) = p.without_orphan_sources(); |
| 9263 | assert_eq!( |
| 9264 | sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(), |
| 9265 | [0, 1], |
| 9266 | "both entries survive the orphan prune: both are played" |
| 9267 | ); |
| 9268 | } |
| 9269 | |
| 9270 | /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is |
| 9271 | /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil) |
| 9272 | /// is the stamp playback puts on a decoded source frame -- and the *last* |
| 9273 | /// source frame the pump is still holding at a timeline frame has to be |
| 9274 | /// exactly the one the export encoded there, at every rate. Anything else is |
| 9275 | /// A/V drift that grows with the clip, and no test of either side alone |
| 9276 | /// would see it. |
| 9277 | /// |
| 9278 | /// (Grafted from the rival build of this feature, whose floor/ceil pairing |
| 9279 | /// is a better answer than the floor/floor this had: floor/floor put the |
| 9280 | /// preview a whole held frame off the export at slow rates.) |
| 9281 | #[test] |
| 9282 | fn speed_maps_both_ways() { |
| 9283 | for permille in (250..=4000).step_by(1) { |
| 9284 | let speed = Speed::from_permille(permille); |
| 9285 | assert_eq!(speed.permille(), permille, "no clamping in range"); |
| 9286 | for d in 0..200u32 { |
| 9287 | let want = speed.source_at(d); |
| 9288 | // What the pump shows at `d` is the last frame whose stamp has |
| 9289 | // come due -- and it is `want`, the frame the export encodes |
| 9290 | // there. Slowed, that is the frame it is still holding; sped up, |
| 9291 | // it is the newest of the several that arrived. |
| 9292 | let held = (0..=want + 8) |
| 9293 | .filter(|&s| speed.timeline_at(s) <= d) |
| 9294 | .next_back(); |
| 9295 | assert_eq!(held, Some(want), "{speed} at timeline frame {d}"); |
| 9296 | } |
| 9297 | for n in 1..300u32 { |
| 9298 | // A footprint is never zero: a clip occupying no timeline frame |
| 9299 | // is a placement the lane invariants cannot hold. |
| 9300 | let frames = speed.frames(n); |
| 9301 | assert!(frames >= 1, "{speed} of {n} frames"); |
| 9302 | // ...and its last timeline frame never reads past the clip. |
| 9303 | assert!( |
| 9304 | speed.source_at(frames - 1) < n, |
| 9305 | "{speed}: the last timeline frame of {n} reads past the clip" |
| 9306 | ); |
| 9307 | // The trim inverse never overshoots the room it was given, and |
| 9308 | // answers for every room a footprint can be. |
| 9309 | let fit = speed.fit(frames).expect("a clip fits its own footprint"); |
| 9310 | assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew"); |
| 9311 | // A room narrower than one source frame's own footprint holds |
| 9312 | // nothing, and says so rather than rounding something into it. |
| 9313 | assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow"); |
| 9314 | assert_eq!(speed.room(0), 0, "{speed}: no head is no room"); |
| 9315 | } |
| 9316 | } |
| 9317 | // Real time is the identity map, byte for byte. |
| 9318 | for d in 0..1000 { |
| 9319 | assert_eq!(Speed::NORMAL.source_at(d), d); |
| 9320 | assert_eq!(Speed::NORMAL.timeline_at(d), d); |
| 9321 | assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1)); |
| 9322 | assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1))); |
| 9323 | assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1); |
| 9324 | } |
| 9325 | // The one door: no zero, no reverse, nothing past the ends. |
| 9326 | assert_eq!(Speed::from_permille(0), Speed::MIN); |
| 9327 | assert_eq!(Speed::from_permille(249), Speed::MIN); |
| 9328 | assert_eq!(Speed::from_permille(4001), Speed::MAX); |
| 9329 | assert_eq!(Speed::from_permille(1000), Speed::NORMAL); |
| 9330 | assert_eq!(Speed::NORMAL.to_string(), "1.00x"); |
| 9331 | assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); |
| 9332 | } |
| 9333 | |
| 9334 | /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an |
| 9335 | /// export encodes at a timeline frame is the one playback is holding there, |
| 9336 | /// a file is as long in timeline frames as the seconds it lasts, and the two |
| 9337 | /// compose so a speeded clip at another rate is exactly both. |
| 9338 | #[test] |
| 9339 | fn rate_composes_with_speed() { |
| 9340 | // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976, |
| 9341 | // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be |
| 9342 | // the identity map or a single-rate project would move. |
| 9343 | for (source_fps, timeline_fps) in [ |
| 9344 | (24000. / 1001., 30.), |
| 9345 | (30., 24000. / 1001.), |
| 9346 | (60., 30.), |
| 9347 | (25., 30.), |
| 9348 | (30., 30.), |
| 9349 | ] { |
| 9350 | let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate"); |
| 9351 | for n in 0..2000u32 { |
| 9352 | let source = rate.source_at(n); |
| 9353 | // The stamp is the *first* timeline-rate frame that shows it, so |
| 9354 | // the picture on screen at `n` is the picture encoded at `n`. |
| 9355 | let held = (0..=source + 4) |
| 9356 | .filter(|&s| rate.timeline_at(s) <= n) |
| 9357 | .next_back(); |
| 9358 | assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}"); |
| 9359 | } |
| 9360 | // A file of `count` frames is `timeline_at(count)` frames long here, |
| 9361 | // and its last one still reads a frame the file has. |
| 9362 | for count in 1..500u32 { |
| 9363 | let frames = rate.timeline_at(count); |
| 9364 | assert!(frames >= 1, "a file is never zero frames long"); |
| 9365 | assert!( |
| 9366 | rate.source_at(frames - 1) < count, |
| 9367 | "{source_fps} on {timeline_fps}: {count} frames reads past the file" |
| 9368 | ); |
| 9369 | } |
| 9370 | // No drift: the mapping is one exact division of the *rate itself*, |
| 9371 | // not an accumulation and not a rounded rate, so an hour in is as |
| 9372 | // true as the first second. (Held to the real ratio of the two rates |
| 9373 | // the caller asked for -- `as_f64` would be true of a wrong rate.) |
| 9374 | for n in [1u32, 100, 10_000, 500_000, 3_000_000] { |
| 9375 | let want = f64::from(n) * source_fps / timeline_fps; |
| 9376 | assert!( |
| 9377 | (f64::from(rate.source_at(n)) - want).abs() < 1., |
| 9378 | "{source_fps} on {timeline_fps}: frame {n} drifted" |
| 9379 | ); |
| 9380 | } |
| 9381 | } |
| 9382 | // The timeline's own rate is the identity, whichever way it is written. |
| 9383 | assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time()); |
| 9384 | assert!( |
| 9385 | Rate::from_fps(30.0004, 30.) |
| 9386 | .expect("30.0004 over 30") |
| 9387 | .is_real_time(), |
| 9388 | "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001" |
| 9389 | ); |
| 9390 | // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the |
| 9391 | // one thing `matches_timeline` refuses a file for now that the rate gate |
| 9392 | // is gone. |
| 9393 | assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all"); |
| 9394 | assert!(Rate::from_fps(30., f64::NAN).is_err()); |
| 9395 | for n in 0..1000 { |
| 9396 | assert_eq!(Rate::REAL_TIME.source_at(n), n); |
| 9397 | assert_eq!(Rate::REAL_TIME.timeline_at(n), n); |
| 9398 | } |
| 9399 | // ...and the composition, in the order the decoder's door applies it: |
| 9400 | // the speed picks the clip's (timeline-rate) frame, the rate picks the |
| 9401 | // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two |
| 9402 | // timeline frames per frame shown, each of them exactly 800/1001 of a |
| 9403 | // file frame. |
| 9404 | let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30"); |
| 9405 | let speed = Speed::from_permille(2000); |
| 9406 | for d in 0..100u32 { |
| 9407 | assert_eq!( |
| 9408 | rate.source_at(speed.source_at(d)), |
| 9409 | (u64::from(d) * 2 * 800 / 1001) as u32, |
| 9410 | "2x of a 23.976 fps file at timeline frame {d}" |
| 9411 | ); |
| 9412 | } |
| 9413 | } |
| 9414 | |
| 9415 | /// The mapping a speed changes, and the one it does not: a 2x clip reads two |
| 9416 | /// source frames per timeline frame and still starts at its own in-point, |
| 9417 | /// and a half-speed one shows every source frame twice. |
| 9418 | #[test] |
| 9419 | fn a_rate_maps_timeline_frames_onto_source_frames() { |
| 9420 | let mut p = Project::single(FILE, 40); |
| 9421 | p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) |
| 9422 | .expect("room enough"); |
| 9423 | assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x"); |
| 9424 | assert_eq!( |
| 9425 | p.map(Lane::V1, 0), |
| 9426 | Some((0, 0)), |
| 9427 | "and it starts where it did" |
| 9428 | ); |
| 9429 | assert_eq!(p.map(Lane::V1, 1), Some((0, 2))); |
| 9430 | assert_eq!(p.map(Lane::V1, 19), Some((0, 38))); |
| 9431 | assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does"); |
| 9432 | // The span a decoder is handed: as many source frames as it will read, |
| 9433 | // which is the last shown frame's own and not one more -- timeline frame |
| 9434 | // 19 shows source frame 38, so 39 frames are read and the 40th is a |
| 9435 | // picture nothing would display. |
| 9436 | let span = p.span_at(Lane::V1, 0).expect("a span"); |
| 9437 | assert_eq!((span.len, span.source_len()), (20, 39)); |
| 9438 | assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows"); |
| 9439 | // ...and the same clip the other way round. |
| 9440 | let mut p = Project::single(FILE, 40); |
| 9441 | p.set_speed(Lane::V1, 0, Speed::from_permille(500)) |
| 9442 | .expect("room enough"); |
| 9443 | assert_eq!(p.timeline_frames(), 80); |
| 9444 | assert_eq!(p.map(Lane::V1, 0), Some((0, 0))); |
| 9445 | assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice"); |
| 9446 | assert_eq!(p.map(Lane::V1, 2), Some((0, 1))); |
| 9447 | assert_eq!( |
| 9448 | p.map(Lane::V1, 79), |
| 9449 | Some((0, 39)), |
| 9450 | "and the last timeline frame is still inside the source range" |
| 9451 | ); |
| 9452 | } |
| 9453 | |
| 9454 | /// A trim of a speeded clip is still a trim of its *source*, and the edge |
| 9455 | /// still stops at the wall: the room a rate leaves is measured in timeline |
| 9456 | /// frames and the range it commits in source ones. |
| 9457 | #[test] |
| 9458 | fn trimming_a_speeded_clip_stays_inside_its_room() { |
| 9459 | let mut p = Project::single(FILE, 40); |
| 9460 | p.set_speed(Lane::V1, 0, Speed::from_permille(2000)) |
| 9461 | .expect("room enough"); |
| 9462 | // A second clip butted against the first, so the wall is a real one. |
| 9463 | assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0))); |
| 9464 | let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip"); |
| 9465 | assert_eq!(room, (1, 20), "out to the neighbour and no further"); |
| 9466 | assert!( |
| 9467 | !p.trim(Lane::V1, 0, Edge::End, 30, &[40]), |
| 9468 | "clamped to the wall, which is where the edge already is" |
| 9469 | ); |
| 9470 | let c = p.clips()[0]; |
| 9471 | assert_eq!(c.end(), 20, "so nothing moved"); |
| 9472 | assert_eq!(c.out_frame, 40, "and it is still the whole source range"); |
| 9473 | // ...and in: half the timeline frames is half the source range. |
| 9474 | assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40])); |
| 9475 | let c = p.clips()[0]; |
| 9476 | assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames"); |
| 9477 | assert_eq!(c.end(), 10, "and ten timeline frames of them"); |
| 9478 | assert!(sorted_disjoint(p.clips())); |
| 9479 | } |
| 9480 | |
| 9481 | /// The frames a rate cannot address: at half speed each source frame is on |
| 9482 | /// screen twice, and the cut between the two showings is not a cut in the |
| 9483 | /// file. Refused, so the two halves always add up to the clip that was cut. |
| 9484 | #[test] |
| 9485 | fn a_slow_clip_cuts_only_where_its_source_has_a_frame() { |
| 9486 | let mut p = Project::single(FILE, 10); |
| 9487 | p.set_speed(Lane::V1, 0, Speed::from_permille(500)) |
| 9488 | .expect("room enough"); |
| 9489 | assert_eq!(p.timeline_frames(), 20); |
| 9490 | assert!( |
| 9491 | !p.split(3), |
| 9492 | "an odd frame is between two showings of one frame" |
| 9493 | ); |
| 9494 | assert_eq!(p.clips().len(), 1, "and nothing was cut"); |
| 9495 | assert!(p.split(4), "an even one is a frame boundary"); |
| 9496 | let halves = p.clips().to_vec(); |
| 9497 | assert_eq!( |
| 9498 | (halves[0].end(), halves[1].start, halves[1].end()), |
| 9499 | (4, 4, 20), |
| 9500 | "the halves meet, and still end where the clip did" |
| 9501 | ); |
| 9502 | assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames"); |
| 9503 | assert!(p.regroup(4), "and the inverse puts it back"); |
| 9504 | assert_eq!(p.clips().len(), 1); |
| 9505 | } |
| 9506 | |
| 9507 | /// The same claim, swept: random op sequences off the public surface, the |
| 9508 | /// project reloaded after every one of them. A failure prints its seed, and |
| 9509 | /// the seed replays the whole sequence. |
| 9510 | #[test] |
| 9511 | fn random_edit_sequences_reload() { |
| 9512 | // Two thousand, not two hundred: the overlap a hole punched into a slow |
| 9513 | // clip at a frame its rate cannot address leaves behind sat in ~0.7% of |
| 9514 | // sequences, and a 200-seed sweep walked straight past it (it took a |
| 9515 | // judge's 2000-seed run to surface `place` at all). A sweep this cheap |
| 9516 | // has no business being the narrow one. |
| 9517 | for seed in 0..2000u64 { |
| 9518 | let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); |
| 9519 | let mut next = move |n: u32| { |
| 9520 | // xorshift64*: no dependency, and the seed replays it exactly. |
| 9521 | rng ^= rng << 13; |
| 9522 | rng ^= rng >> 7; |
| 9523 | rng ^= rng << 17; |
| 9524 | (rng >> 33) as u32 % n |
| 9525 | }; |
| 9526 | let mut p = Project::single(FILE, 40); |
| 9527 | for step in 0..24 { |
| 9528 | let frame = next(44); |
| 9529 | // A clipboard copy carries the group id of the take it came from |
| 9530 | // -- the input that made a placement duplicate an id -- and, one |
| 9531 | // time in three, a rate of its own: a *speeded clip placed over |
| 9532 | // a speeded clip* is the shape whose remainders have to be run |
| 9533 | // through `Speed::fit`, and it is not a shape the lanes hand out |
| 9534 | // on their own often enough to be sure of. |
| 9535 | let mut copied = *p |
| 9536 | .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 }) |
| 9537 | .get(next(4) as usize) |
| 9538 | .unwrap_or(&clip(0, 0, 5, 0)); |
| 9539 | if next(3) == 0 { |
| 9540 | copied.speed = Speed::from_permille(250 + next(16) as u16 * 250); |
| 9541 | } |
| 9542 | let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 }; |
| 9543 | let idx = next(4) as usize; |
| 9544 | let _ = match next(16) { |
| 9545 | // A clip dragged along its own lane to wherever the pointer |
| 9546 | // let it go: the op that moves a placement without changing |
| 9547 | // what it plays, so what it may not do is land on top of the |
| 9548 | // neighbour it was dragged at. |
| 9549 | 15 => p.move_clip(lane, idx, lane, frame), |
| 9550 | // ...and a second `place`, so a punch lands inside a clip |
| 9551 | // far more often than one op in fourteen would put it there. |
| 9552 | 14 => p.place(lane, frame, copied), |
| 9553 | 0 => p.split(frame), |
| 9554 | 1 => p.regroup(frame), |
| 9555 | 2 => p.lift(lane, idx), |
| 9556 | 3 => p.place(lane, frame, copied), |
| 9557 | 4 => p.paste(frame, copied), |
| 9558 | 5 => p.ripple_delete(frame, next(9)), |
| 9559 | 6 => p.delete(idx), |
| 9560 | 7 => p.undo(), |
| 9561 | // An equalizer put on and taken off in the mix: what a clip |
| 9562 | // carries has to reload with it, and the entries an undo |
| 9563 | // orphans must not come back out of the prune. |
| 9564 | 8 => p.set_eq(lane, idx, Some(band_at(next(4)))), |
| 9565 | 9 => p.set_eq(lane, idx, None), |
| 9566 | // ...and a colour grade in the same mix, for the same |
| 9567 | // reason: it rides on the clip and its orphans must go. |
| 9568 | 10 => p.set_color(lane, idx, Some(grade_at(next(4)))), |
| 9569 | 11 => p.set_color(lane, idx, None), |
| 9570 | // ...and a rate in with them, which is the one of the three |
| 9571 | // that moves *placements*: a clip that grew has to be |
| 9572 | // refused rather than overlap, and one that shrank leaves a |
| 9573 | // lane that still loads. Both are what `reloads` asks. |
| 9574 | 12 => p |
| 9575 | .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250)) |
| 9576 | .is_ok(), |
| 9577 | _ => p.append_clip(0, 1 + next(9)), |
| 9578 | }; |
| 9579 | reloads(&p, &format!("seed {seed}, step {step}")); |
| 9580 | } |
| 9581 | } |
| 9582 | } |
| 9583 | |
| 9584 | /// The save/load round trip a project must survive: the parts a save writes, |
| 9585 | /// handed back to the constructor a load goes through -- every lane of them, |
| 9586 | /// and the reloaded timeline has to be the same lanes in the same order. |
| 9587 | fn reloads(p: &Project, what: &str) { |
| 9588 | let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources(); |
| 9589 | match Project::from_parts(sources, lanes, eq, color, transform) { |
| 9590 | Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes), |
| 9591 | Ok(back) => { |
| 9592 | assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed"); |
| 9593 | // Placements, not whole clips: an orphan prune renumbers the |
| 9594 | // sources a clip names, which is the point of it. |
| 9595 | let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> { |
| 9596 | p.lanes().into_iter().map(|l| p.lane_spans(l)).collect() |
| 9597 | }; |
| 9598 | assert_eq!(spans(&back), spans(p), "{what}: the placements changed"); |
| 9599 | // The prune renumbers the eq table too, so what has to survive |
| 9600 | // is the settings themselves, clip by clip. |
| 9601 | let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> { |
| 9602 | p.lanes() |
| 9603 | .into_iter() |
| 9604 | .map(|l| { |
| 9605 | (0..p.lane(l).len()) |
| 9606 | .map(|i| p.eq_of(l, i).cloned()) |
| 9607 | .collect() |
| 9608 | }) |
| 9609 | .collect() |
| 9610 | }; |
| 9611 | assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed"); |
| 9612 | // The colour table renumbers in the same prune, so the same |
| 9613 | // claim: the params a clip names, not the index it names them by. |
| 9614 | let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> { |
| 9615 | p.lanes() |
| 9616 | .into_iter() |
| 9617 | .map(|l| { |
| 9618 | (0..p.lane(l).len()) |
| 9619 | .map(|i| p.color_of(l, i).copied()) |
| 9620 | .collect() |
| 9621 | }) |
| 9622 | .collect() |
| 9623 | }; |
| 9624 | assert_eq!(colors(&back), colors(p), "{what}: the colours changed"); |
| 9625 | // ...and the transform table, by the same claim again. |
| 9626 | let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> { |
| 9627 | p.lanes() |
| 9628 | .into_iter() |
| 9629 | .map(|l| { |
| 9630 | (0..p.lane(l).len()) |
| 9631 | .map(|i| p.transform_of(l, i).copied()) |
| 9632 | .collect() |
| 9633 | }) |
| 9634 | .collect() |
| 9635 | }; |
| 9636 | assert_eq!( |
| 9637 | transforms(&back), |
| 9638 | transforms(p), |
| 9639 | "{what}: the transforms changed" |
| 9640 | ); |
| 9641 | } |
| 9642 | } |
| 9643 | } |
| 9644 | |
| 9645 | /// The two invariants [`Project::from_parts`] checks that are about *lanes* |
| 9646 | /// -- each one sorted and disjoint, and one span per group id -- asserted |
| 9647 | /// directly, where the point is the invariant rather than the round trip. |
| 9648 | fn invariants_hold(p: &Project, what: &str) { |
| 9649 | for lane in p.lanes() { |
| 9650 | assert!( |
| 9651 | sorted_disjoint(p.lane(lane)), |
| 9652 | "{what}: {} is out of order or overlaps itself: {:?}", |
| 9653 | lane.label(), |
| 9654 | p.lane(lane) |
| 9655 | ); |
| 9656 | } |
| 9657 | if let Err(e) = links_are_consistent(&p.lanes) { |
| 9658 | panic!("{what}: {e}\n{:?}", p.lanes); |
| 9659 | } |
| 9660 | } |
| 9661 | |
| 9662 | /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and |
| 9663 | /// edited without any other lane hearing about it. A handle naming a lane |
| 9664 | /// that is not there reads as empty and refuses to mutate. |
| 9665 | #[test] |
| 9666 | fn a_third_lane_is_a_peer() { |
| 9667 | let mut p = three(); |
| 9668 | assert_eq!(p.lane_count(LaneKind::Video), 1); |
| 9669 | assert_eq!(p.lane_count(LaneKind::Audio), 1); |
| 9670 | let v2 = p.add_lane(LaneKind::Video); |
| 9671 | assert_eq!(v2, Lane::new(LaneKind::Video, 1)); |
| 9672 | assert_eq!(v2.label(), "V2"); |
| 9673 | assert_eq!(p.lane_count(LaneKind::Video), 2); |
| 9674 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]); |
| 9675 | assert!(p.lane(v2).is_empty(), "a new lane holds nothing"); |
| 9676 | |
| 9677 | // A handle for a lane that is not there: empty, and no mutation takes. |
| 9678 | let v3 = Lane::new(LaneKind::Video, 2); |
| 9679 | assert!(p.lane(v3).is_empty()); |
| 9680 | assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement"); |
| 9681 | assert!(!p.lift(v3, 0)); |
| 9682 | assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made"); |
| 9683 | |
| 9684 | // Placing on V2 moves nothing else, and the lane can outrun the rest. |
| 9685 | let before = shape(&p); |
| 9686 | assert!(p.place(v2, 4, clip(0, 20, 32, 0))); |
| 9687 | assert_eq!(shape(&p)[0], before[0], "V1 never moved"); |
| 9688 | assert_eq!(shape(&p)[1], before[1], "A1 never moved"); |
| 9689 | assert_eq!(p.lane_spans(v2), vec![(4, 12)]); |
| 9690 | assert_eq!( |
| 9691 | p.timeline_frames(), |
| 9692 | 16, |
| 9693 | "the last lane to end sets the length" |
| 9694 | ); |
| 9695 | assert_eq!(p.map(v2, 5), Some((0, 21))); |
| 9696 | assert_eq!(p.map(v2, 3), None, "V2's own leading gap"); |
| 9697 | assert_eq!( |
| 9698 | p.span_at(v2, 0), |
| 9699 | Some(Span { |
| 9700 | start: 0, |
| 9701 | len: 4, |
| 9702 | from: None, |
| 9703 | speed: Speed::NORMAL |
| 9704 | }) |
| 9705 | ); |
| 9706 | // Every lane still covers the whole timeline, gaps included. |
| 9707 | for l in p.lanes() { |
| 9708 | let spans = p.spans_from(l, 0); |
| 9709 | assert_eq!( |
| 9710 | spans.iter().map(|s| s.len).sum::<u32>(), |
| 9711 | 16, |
| 9712 | "{}", |
| 9713 | l.label() |
| 9714 | ); |
| 9715 | } |
| 9716 | // ...and playback still reads V1 and A1, whatever else is there. |
| 9717 | assert_eq!(p.clips(), p.lane(Lane::V1)); |
| 9718 | assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4)); |
| 9719 | let segments = p.segments_from(0, FPS); |
| 9720 | assert_eq!(segments[..3], three().segments_from(0, FPS)[..]); |
| 9721 | assert_eq!( |
| 9722 | segments[3], |
| 9723 | (None, 0.0, 7.0 / FPS), |
| 9724 | "A1 keeps the clock counting over the picture V2 added" |
| 9725 | ); |
| 9726 | invariants_hold(&p, "place on V2"); |
| 9727 | |
| 9728 | // A lift is that lane's business too, and the lane list undoes. |
| 9729 | assert!(p.lift(v2, 0)); |
| 9730 | assert!(p.lane(v2).is_empty()); |
| 9731 | assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest"); |
| 9732 | assert!(p.undo()); |
| 9733 | assert_eq!(p.lane_spans(v2), vec![(4, 12)]); |
| 9734 | assert!(p.undo()); |
| 9735 | assert!(p.lane(v2).is_empty(), "the placement came off V2"); |
| 9736 | assert!(p.undo(), "and one more step takes the lane itself back"); |
| 9737 | assert_eq!(p.lane_count(LaneKind::Video), 1); |
| 9738 | assert_eq!(shape(&p), shape(&three())); |
| 9739 | } |
| 9740 | |
| 9741 | /// The add taken back: an empty lane comes off, a lane holding clips never |
| 9742 | /// does (and says which clips), the last lane of a kind never does, the |
| 9743 | /// lanes below the one that went move up an `ord`, and one undo puts it |
| 9744 | /// back where it stood. |
| 9745 | #[test] |
| 9746 | fn an_empty_lane_comes_off_again() { |
| 9747 | let mut p = three(); |
| 9748 | let v2 = p.add_lane(LaneKind::Video); |
| 9749 | let v3 = p.add_lane(LaneKind::Video); |
| 9750 | assert!(p.place(v3, 0, clip(0, 0, 3, 0))); |
| 9751 | let why = |r: crate::Result<()>| r.expect_err("refused").to_string(); |
| 9752 | let history = p.history.len(); |
| 9753 | |
| 9754 | // The last lane of its kind stays: `V1`/`A1` are where an import and a |
| 9755 | // paste land, and a project missing one would swallow half of a file |
| 9756 | // dropped on it. |
| 9757 | assert!(why(p.remove_lane(Lane::A1)).contains("only audio track")); |
| 9758 | assert_eq!( |
| 9759 | why(p.remove_lane(Lane::new(LaneKind::Video, 9))), |
| 9760 | "there is no V10 to remove" |
| 9761 | ); |
| 9762 | |
| 9763 | // A lane with clips on it refuses and names them: a track removal never |
| 9764 | // deletes a take. |
| 9765 | let refusal = why(p.remove_lane(v3)); |
| 9766 | assert!(refusal.contains("V3 still holds"), "{refusal}"); |
| 9767 | assert!(refusal.contains(FILE), "{refusal}"); |
| 9768 | assert!(refusal.contains("at frame 0"), "{refusal}"); |
| 9769 | assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there"); |
| 9770 | assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); |
| 9771 | |
| 9772 | // The empty one in the middle goes, and `V3` becomes `V2` -- clip and |
| 9773 | // all. |
| 9774 | p.remove_lane(v2).expect("V2 is empty"); |
| 9775 | assert_eq!(p.lane_count(LaneKind::Video), 2); |
| 9776 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]); |
| 9777 | assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up"); |
| 9778 | assert_eq!(p.history.len(), history + 1, "one snapshot per removal"); |
| 9779 | invariants_hold(&p, "remove V2"); |
| 9780 | |
| 9781 | // ...and one stroke puts the empty lane back above it. |
| 9782 | assert!(p.undo()); |
| 9783 | assert_eq!(p.lane_count(LaneKind::Video), 3); |
| 9784 | assert!(p.lane(v2).is_empty(), "back where it stood, still empty"); |
| 9785 | assert_eq!(p.lane_spans(v3), vec![(0, 3)]); |
| 9786 | } |
| 9787 | |
| 9788 | /// A track dragged to another place in the stack: the whole lane travels -- |
| 9789 | /// clips, gain and kind -- nothing is remapped, an audio track may sit above |
| 9790 | /// a video one, a lane that crosses one of its own kind swaps names with it |
| 9791 | /// (and swaps the composite with it), one undo puts the order back, and a |
| 9792 | /// save carries it. |
| 9793 | #[test] |
| 9794 | fn a_track_is_dragged_to_another_place_in_the_stack() { |
| 9795 | let mut p = three(); |
| 9796 | assert!(p.set_lane_gain_db(Lane::A1, -6.0)); |
| 9797 | let before = shape(&p); |
| 9798 | let history = p.history.len(); |
| 9799 | |
| 9800 | // A1 over V1: the screen is rearranged and nothing else is. Both keep |
| 9801 | // their names -- neither crossed a lane of its own kind -- so every |
| 9802 | // handle a front-end holds still names the track it named before. |
| 9803 | assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1)); |
| 9804 | assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now"); |
| 9805 | assert_eq!( |
| 9806 | shape(&p), |
| 9807 | vec![before[1].clone(), before[0].clone()], |
| 9808 | "each lane's clips travelled with it, and none was remapped" |
| 9809 | ); |
| 9810 | assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain"); |
| 9811 | assert_eq!(p.history.len(), history + 1, "one snapshot per move"); |
| 9812 | invariants_hold(&p, "A1 over V1"); |
| 9813 | |
| 9814 | // Nothing moves for a lane that is not there, a slot that is not, or a |
| 9815 | // lane already standing in the one it was pointed at. |
| 9816 | assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None); |
| 9817 | assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot"); |
| 9818 | assert_eq!(p.move_lane(Lane::A1, 0), None, "already there"); |
| 9819 | assert_eq!(p.history.len(), history + 1, "and none of those snapshot"); |
| 9820 | |
| 9821 | // ...and one stroke puts the order back. |
| 9822 | assert!(p.undo()); |
| 9823 | assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]); |
| 9824 | assert_eq!(shape(&p), before); |
| 9825 | |
| 9826 | // A second video lane over the first: display order *is* the stack, so |
| 9827 | // the last video lane covering a frame is the picture that shows. |
| 9828 | let v2 = p.add_lane(LaneKind::Video); |
| 9829 | assert!(p.place(v2, 0, clip(0, 0, 5, 0))); |
| 9830 | let over = shape(&p)[2].clone(); |
| 9831 | assert_eq!( |
| 9832 | p.composite_span_at(0).map(|s| s.len), |
| 9833 | Some(5), |
| 9834 | "V2's five frames are what frame 0 shows" |
| 9835 | ); |
| 9836 | |
| 9837 | // V2 dragged to the top takes V1's slot -- and V1's name, a label being |
| 9838 | // a position among the lanes of its kind. The picture that wins changes |
| 9839 | // with it: the take that was covering is the covered one now. |
| 9840 | assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position"); |
| 9841 | assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]); |
| 9842 | assert_eq!( |
| 9843 | shape(&p), |
| 9844 | vec![over.clone(), before[0].clone(), before[1].clone()], |
| 9845 | "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own" |
| 9846 | ); |
| 9847 | assert_eq!( |
| 9848 | p.composite_span_at(0).map(|s| s.len), |
| 9849 | Some(3), |
| 9850 | "the lower video lane wins, and it is the old V1 now" |
| 9851 | ); |
| 9852 | invariants_hold(&p, "V2 over V1"); |
| 9853 | |
| 9854 | // A save writes that order and a load takes it back. |
| 9855 | let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); |
| 9856 | assert_eq!( |
| 9857 | lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(), |
| 9858 | [LaneKind::Video, LaneKind::Video, LaneKind::Audio] |
| 9859 | ); |
| 9860 | let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load"); |
| 9861 | assert_eq!(back.lanes(), p.lanes()); |
| 9862 | assert_eq!(shape(&back), shape(&p), "the same lane is still on top"); |
| 9863 | |
| 9864 | assert!(p.undo(), "and the stack goes back to how it stood"); |
| 9865 | assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]); |
| 9866 | } |
| 9867 | |
| 9868 | /// The grouping rule across more than two lanes, under the offset model: a |
| 9869 | /// split *keeps* the group on the left halves and hands the right halves of |
| 9870 | /// that group one fresh id of their own -- a clip in no group comes out of |
| 9871 | /// the cut in none. So a take cut apart is two takes, one per side, and a |
| 9872 | /// lane that was never part of it stays out of both. |
| 9873 | #[test] |
| 9874 | fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() { |
| 9875 | let mut p = Project::single(FILE, 9); |
| 9876 | let take = p.clips()[0].link.expect("a fresh project is one take"); |
| 9877 | let v2 = p.add_lane(LaneKind::Video); |
| 9878 | assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group"); |
| 9879 | assert!(p.split(4)); |
| 9880 | let side = |p: &Project, i: usize| -> Vec<Option<u32>> { |
| 9881 | p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect() |
| 9882 | }; |
| 9883 | let (left, right) = (side(&p, 0), side(&p, 1)); |
| 9884 | // The lanes in order are V1, A1, V2: the take's two keep its id on the |
| 9885 | // left, and the placed clip never had one for the cut to keep. |
| 9886 | assert_eq!( |
| 9887 | left, |
| 9888 | vec![Some(take), Some(take), None], |
| 9889 | "the left halves keep the take" |
| 9890 | ); |
| 9891 | // ...and the right halves of that take are one fresh group. |
| 9892 | assert_eq!(right[0], right[1]); |
| 9893 | assert_ne!(right[0], Some(take)); |
| 9894 | assert_eq!(right[2], None, "an unlinked lane stays unlinked"); |
| 9895 | invariants_hold(&p, "split across three lanes"); |
| 9896 | |
| 9897 | // V2 ends early: the left halves still keep what each clip carried -- |
| 9898 | // the take on V1 and A1, nothing on V2 -- and the fresh right id is |
| 9899 | // shared by exactly the take's lanes. |
| 9900 | let mut p = Project::single(FILE, 9); |
| 9901 | let v2 = p.add_lane(LaneKind::Video); |
| 9902 | assert!(p.place(v2, 0, clip(0, 0, 6, 0))); |
| 9903 | assert!(p.split(3)); |
| 9904 | assert_eq!(p.lane(Lane::V1)[0].link, Some(take)); |
| 9905 | assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement"); |
| 9906 | assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link); |
| 9907 | assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement"); |
| 9908 | invariants_hold(&p, "split where one lane ends early"); |
| 9909 | |
| 9910 | // The inverse rejoins each lane into the group its left half kept. |
| 9911 | assert!(p.regroup(3)); |
| 9912 | assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link); |
| 9913 | assert_eq!( |
| 9914 | p.lane(Lane::V1)[0].link, |
| 9915 | Some(take), |
| 9916 | "the take's id is back, not a fresh one" |
| 9917 | ); |
| 9918 | assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group"); |
| 9919 | invariants_hold(&p, "regroup across three lanes"); |
| 9920 | } |
| 9921 | |
| 9922 | /// A group is one placement per lane, on however many lanes carry the id -- |
| 9923 | /// not a video/audio pair and not a pairing by `ord` -- and the members may |
| 9924 | /// cover whatever frames they cover: the offset between them is what a |
| 9925 | /// hand-built group keeps. Lanes built by hand, because the rule is checked |
| 9926 | /// at the untrusted door and no edit can produce the one thing it refuses. |
| 9927 | #[test] |
| 9928 | fn a_group_may_span_any_lane() { |
| 9929 | let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips); |
| 9930 | let one = |start: u32, end: u32, link| Clip { |
| 9931 | fade_in: 0, |
| 9932 | fade_out: 0, |
| 9933 | transition_out: 0, |
| 9934 | start, |
| 9935 | in_frame: start, |
| 9936 | out_frame: end, |
| 9937 | source: 0, |
| 9938 | link: Some(link), |
| 9939 | eq: None, |
| 9940 | color: None, |
| 9941 | transform: None, |
| 9942 | fit: FitPolicy::default(), |
| 9943 | speed: Speed::NORMAL, |
| 9944 | }; |
| 9945 | // V1, A1, V2, A2 -- one take over [0, 4) on all four. |
| 9946 | let kinds = [ |
| 9947 | LaneKind::Video, |
| 9948 | LaneKind::Audio, |
| 9949 | LaneKind::Video, |
| 9950 | LaneKind::Audio, |
| 9951 | ]; |
| 9952 | let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> { |
| 9953 | kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect() |
| 9954 | }; |
| 9955 | let take = || vec![one(0, 4, 7)]; |
| 9956 | assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok()); |
| 9957 | // The same take on V1 + A2 only, the lanes between it empty: legal, the |
| 9958 | // way a lifted half is legal. |
| 9959 | let across = build([take(), Vec::new(), Vec::new(), take()]); |
| 9960 | assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2"); |
| 9961 | // ...and so is a group whose members disagree about their spans: the |
| 9962 | // offset between them is the hand's business, not the loader's. |
| 9963 | let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]); |
| 9964 | assert!( |
| 9965 | links_are_consistent(&apart).is_ok(), |
| 9966 | "[0, 4) on V1 and [2, 6) on A2 are one group" |
| 9967 | ); |
| 9968 | // One id twice in one lane is still that lane's error, by name. |
| 9969 | let twice = build([ |
| 9970 | Vec::new(), |
| 9971 | Vec::new(), |
| 9972 | vec![one(0, 4, 7), one(4, 8, 7)], |
| 9973 | Vec::new(), |
| 9974 | ]); |
| 9975 | assert_eq!( |
| 9976 | links_are_consistent(&twice).unwrap_err().to_string(), |
| 9977 | "link 7 names two clips in the V2 lane" |
| 9978 | ); |
| 9979 | } |
| 9980 | |
| 9981 | /// Every lane a save writes comes out, in display order and with its kind -- |
| 9982 | /// an empty one included, since it is state a front-end shows -- and a |
| 9983 | /// two-lane project still writes exactly the parts it always did. |
| 9984 | #[test] |
| 9985 | fn a_save_writes_every_lane_it_has() { |
| 9986 | let mut p = three(); |
| 9987 | let before = p.without_orphan_sources(); |
| 9988 | assert_eq!(before.1.len(), 2, "V1 and A1"); |
| 9989 | let v2 = p.add_lane(LaneKind::Video); |
| 9990 | assert!(p.place(v2, 4, clip(0, 20, 32, 0))); |
| 9991 | let a2 = p.add_lane(LaneKind::Audio); |
| 9992 | let (sources, lanes, eq, color, _transform) = p.without_orphan_sources(); |
| 9993 | assert_eq!( |
| 9994 | lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(), |
| 9995 | [ |
| 9996 | LaneKind::Video, |
| 9997 | LaneKind::Audio, |
| 9998 | LaneKind::Video, |
| 9999 | LaneKind::Audio |
| 10000 | ], |
| 10001 | "display order, not video-then-audio" |
| 10002 | ); |
| 10003 | assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written"); |
| 10004 | assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane"); |
| 10005 | // ...and all four load again as the same four. |
| 10006 | let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load"); |
| 10007 | assert_eq!(back.lanes(), p.lanes()); |
| 10008 | assert_eq!(back.lane(a2), p.lane(a2)); |
| 10009 | |
| 10010 | // Taking the lanes back leaves exactly what a two-lane save wrote. |
| 10011 | for _ in 0..3 { |
| 10012 | assert!(p.undo()); |
| 10013 | } |
| 10014 | assert_eq!( |
| 10015 | p.without_orphan_sources(), |
| 10016 | before, |
| 10017 | "byte for byte the same parts a two-lane save always wrote" |
| 10018 | ); |
| 10019 | } |
| 10020 | |
| 10021 | /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with |
| 10022 | /// three lanes and grows more: every lane's own order and the one |
| 10023 | /// span-per-id rule after every op, *and* the reload the v4 format restored |
| 10024 | /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a |
| 10025 | /// project of any number of lanes. |
| 10026 | #[test] |
| 10027 | fn random_edit_sequences_keep_many_lanes_consistent() { |
| 10028 | for seed in 0..2000u64 { |
| 10029 | let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); |
| 10030 | let mut next = move |n: u32| { |
| 10031 | rng ^= rng << 13; |
| 10032 | rng ^= rng >> 7; |
| 10033 | rng ^= rng << 17; |
| 10034 | (rng >> 33) as u32 % n |
| 10035 | }; |
| 10036 | let mut p = Project::single(FILE, 40); |
| 10037 | let v2 = p.add_lane(LaneKind::Video); |
| 10038 | assert!(p.place(v2, 5, clip(0, 0, 20, 0))); |
| 10039 | let lanes = [Lane::V1, Lane::A1, v2]; |
| 10040 | for step in 0..24 { |
| 10041 | let frame = next(44); |
| 10042 | let copied = *p |
| 10043 | .lane(lanes[next(3) as usize]) |
| 10044 | .get(next(4) as usize) |
| 10045 | .unwrap_or(&clip(0, 0, 5, 0)); |
| 10046 | let lane = lanes[next(3) as usize]; |
| 10047 | let idx = next(4) as usize; |
| 10048 | let _ = match next(14) { |
| 10049 | // The drag, in the mix: a clip dragged along its own lane |
| 10050 | // and onto another one, at a frame the pointer picked -- |
| 10051 | // which is where the group rule and the sorted+disjoint one |
| 10052 | // meet, since every half travels the same distance. |
| 10053 | 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame), |
| 10054 | 10 => p.set_eq(lane, idx, Some(band_at(next(4)))), |
| 10055 | 11 => p.set_eq(lane, idx, None), |
| 10056 | // A rate, which on many lanes is the group rule as well: |
| 10057 | // every clip carrying the link moves together or none of |
| 10058 | // them does, and `invariants_hold` is what says so. |
| 10059 | 12 => p |
| 10060 | .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250)) |
| 10061 | .is_ok(), |
| 10062 | 0 => p.split(frame), |
| 10063 | 1 => p.regroup(frame), |
| 10064 | 2 => p.lift(lane, idx), |
| 10065 | 3 => p.place(lane, frame, copied), |
| 10066 | 4 => p.paste(frame, copied), |
| 10067 | 5 => p.ripple_delete(frame, next(9)), |
| 10068 | 6 => p.delete(idx), |
| 10069 | 7 => p.undo(), |
| 10070 | 8 => { |
| 10071 | p.add_lane(if next(2) == 0 { |
| 10072 | LaneKind::Video |
| 10073 | } else { |
| 10074 | LaneKind::Audio |
| 10075 | }); |
| 10076 | true |
| 10077 | } |
| 10078 | _ => p.append_clip(0, 1 + next(9)), |
| 10079 | }; |
| 10080 | invariants_hold(&p, &format!("seed {seed}, step {step}")); |
| 10081 | reloads(&p, &format!("seed {seed}, step {step}")); |
| 10082 | } |
| 10083 | } |
| 10084 | } |
| 10085 | |
| 10086 | /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip |
| 10087 | /// there, `V1` shows again on either side of it, and a frame no video lane |
| 10088 | /// covers is a gap however many lanes there are. |
| 10089 | #[test] |
| 10090 | fn the_composite_is_the_topmost_lane_with_a_clip() { |
| 10091 | let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)]; |
| 10092 | let lanes = vec![ |
| 10093 | // V1: the whole 30 frames of source 0. |
| 10094 | (LaneKind::Video, vec![clip(0, 0, 30, 0)]), |
| 10095 | // V2: source 1 over the middle third. |
| 10096 | (LaneKind::Video, vec![clip(10, 5, 15, 1)]), |
| 10097 | (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), |
| 10098 | ]; |
| 10099 | let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts"); |
| 10100 | assert_eq!( |
| 10101 | p.composite_spans_from(0), |
| 10102 | vec![ |
| 10103 | Span { |
| 10104 | start: 0, |
| 10105 | len: 10, |
| 10106 | from: Some((0, 0)), |
| 10107 | speed: Speed::NORMAL |
| 10108 | }, |
| 10109 | Span { |
| 10110 | start: 10, |
| 10111 | len: 10, |
| 10112 | from: Some((1, 5)), |
| 10113 | speed: Speed::NORMAL |
| 10114 | }, |
| 10115 | Span { |
| 10116 | start: 20, |
| 10117 | len: 10, |
| 10118 | from: Some((0, 20)), |
| 10119 | speed: Speed::NORMAL |
| 10120 | }, |
| 10121 | ], |
| 10122 | "V2 takes over for its own span and hands V1 back" |
| 10123 | ); |
| 10124 | // A mid-span ask resolves the same way, which is what a seek does. |
| 10125 | assert_eq!( |
| 10126 | p.composite_span_at(15), |
| 10127 | Some(Span { |
| 10128 | start: 15, |
| 10129 | len: 5, |
| 10130 | from: Some((1, 10)), |
| 10131 | speed: Speed::NORMAL |
| 10132 | }) |
| 10133 | ); |
| 10134 | assert_eq!(p.composite_span_at(30), None, "past the end"); |
| 10135 | |
| 10136 | // A hole in V1 under V2's clip: black between the two, and black after |
| 10137 | // both run out (the audio lane is still holding the timeline open). |
| 10138 | let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)]; |
| 10139 | let holed = vec![ |
| 10140 | (LaneKind::Video, vec![clip(0, 0, 5, 0)]), |
| 10141 | (LaneKind::Video, vec![clip(10, 0, 10, 1)]), |
| 10142 | (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), |
| 10143 | ]; |
| 10144 | let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts"); |
| 10145 | assert_eq!( |
| 10146 | p.composite_spans_from(0), |
| 10147 | vec![ |
| 10148 | Span { |
| 10149 | start: 0, |
| 10150 | len: 5, |
| 10151 | from: Some((0, 0)), |
| 10152 | speed: Speed::NORMAL |
| 10153 | }, |
| 10154 | Span { |
| 10155 | start: 5, |
| 10156 | len: 5, |
| 10157 | from: None, |
| 10158 | speed: Speed::NORMAL |
| 10159 | }, |
| 10160 | Span { |
| 10161 | start: 10, |
| 10162 | len: 10, |
| 10163 | from: Some((1, 0)), |
| 10164 | speed: Speed::NORMAL |
| 10165 | }, |
| 10166 | Span { |
| 10167 | start: 20, |
| 10168 | len: 10, |
| 10169 | from: None, |
| 10170 | speed: Speed::NORMAL |
| 10171 | }, |
| 10172 | ] |
| 10173 | ); |
| 10174 | |
| 10175 | // One video lane: the composite *is* that lane, span for span -- the |
| 10176 | // promise every existing two-lane project rests on. |
| 10177 | let p = Project::single(FILE, 30); |
| 10178 | assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0)); |
| 10179 | assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7)); |
| 10180 | } |
| 10181 | |
| 10182 | /// Every audio lane holding something gets a play list, and only those. |
| 10183 | #[test] |
| 10184 | fn audio_segments_cover_every_lane_that_holds_something() { |
| 10185 | let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)]; |
| 10186 | let lanes = vec![ |
| 10187 | (LaneKind::Video, vec![clip(0, 0, 30, 0)]), |
| 10188 | (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), |
| 10189 | (LaneKind::Audio, vec![clip(15, 0, 15, 1)]), |
| 10190 | (LaneKind::Audio, Vec::new()), |
| 10191 | ]; |
| 10192 | let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts"); |
| 10193 | let lists = p.audio_segments_from(0, FPS); |
| 10194 | assert_eq!(lists.len(), 2, "the empty lane is not mixed in"); |
| 10195 | assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged"); |
| 10196 | // A2 is a gap up to frame 15, then the whole of source 1. |
| 10197 | assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]); |
| 10198 | |
| 10199 | // No audio lane holds anything: one all-gap list, so such a timeline |
| 10200 | // still plays silence against a master clock. |
| 10201 | let p = Project::from_parts( |
| 10202 | vec![Source::new(FILE, 0)], |
| 10203 | vec![ |
| 10204 | (LaneKind::Video, vec![clip(0, 0, 30, 0)]), |
| 10205 | (LaneKind::Audio, Vec::new()), |
| 10206 | ], |
| 10207 | vec![], |
| 10208 | vec![], |
| 10209 | Vec::new(), |
| 10210 | ) |
| 10211 | .expect("valid parts"); |
| 10212 | assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]); |
| 10213 | } |
| 10214 | } |