forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

timeline_math.rs1334 lines, 57.5 KiBHistoryRawDownload
1//! The timeline's arithmetic: takes, trims, snapping and envelopes.
2
3use crate::*;
4
5/// Whether this clip is a whole take, i.e. whether deleting it may close the
6/// hole under it: a take is what the first pair of lanes carries between them,
7/// `V1`'s picture and the sound grouped with it, and dropping one moves the
8/// frames after it on every lane. A caption a hand grouped with the clip
9/// counts as its partner too: the group is what pairs, not the lane's kind --
10/// and a group answers `true` from *whichever* member's lane the question is
11/// asked from, added row or not, because a grouped delete
12/// ([`PlaybackSession::delete_clip`] -> `Project::delete_members`) closes
13/// every member's own lane by its own span already, not just the first pair's.
14///
15/// Everything else is a half or a layer, and is *lifted* instead: a half whose
16/// picture was lifted (what a lift leaves behind) has no take to ripple, and an
17/// *ungrouped* clip on a further lane is laid over the timeline rather than
18/// part of it -- closing a hole under it would drag the take beneath out of
19/// step with it.
20pub(crate) fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool {
21 let Some(clip) = session.lane_clips(lane).get(idx) else {
22 return false;
23 };
24 let paired = || {
25 session
26 .lanes()
27 .into_iter()
28 .filter(|&other| other != lane)
29 .flat_map(|other| {
30 let clips = session.lane_clips(other).iter().map(|c| c.link);
31 let subs = session.sub_lane(other).iter().map(|s| s.link);
32 clips.chain(subs)
33 })
34 .any(|link| link.is_some() && link == clip.link)
35 };
36 match (lane.kind, lane.ord) {
37 // A clip a hand grouped closes its own lane wherever it sits:
38 // `Project::delete_members` already cuts every member's own span out
39 // of its own lane, whichever lanes those are -- so a caption or clip
40 // grouped onto an added row closes its hole exactly as `V1`/`A1`'s
41 // first pair does, not just the pair itself.
42 _ if paired() => true,
43 (_, 1..) => false,
44 // The picture of a take -- unless the take has been taken apart: a
45 // detached picture (a group id no other lane carries, which is also what
46 // a lift of the sound leaves) is a half like the sound is, and a ripple
47 // under it would drag away the very half it was detached from. A clip in
48 // no group at all is not a half but a placement, and on `V1` a placement
49 // is the take there is.
50 (LaneKind::Video, _) => clip.link.is_none(),
51 // The sound of a take, only while the take is still there: its group is
52 // carried by a clip on some other lane. Reached only when `paired()` is
53 // already false, so this is always false -- kept as its own arm for the
54 // reason a lone `A1` clip is not a take, not because it does the work.
55 (LaneKind::Audio, _) => false,
56 // A subtitle lane carries no `Clip` at all, so the lookup above already
57 // returned: never a take, and never rippled as one.
58 (LaneKind::Subtitle, _) => false,
59 }
60}
61
62/// The clip a Group would pair this one with: the first clip on another track,
63/// in the order the lanes are drawn, covering exactly the same frames and not in
64/// this clip's group already. Exactly the same frames because that is all a
65/// group id can mean (engine `links_are_consistent`), which is what leaves
66/// nothing for a second click to choose. `None` when no track has one, and the
67/// notice says so.
68pub(crate) fn span_partner(
69 session: &PlaybackSession,
70 lane: Lane,
71 idx: usize,
72) -> Option<(Lane, usize)> {
73 let clip = session.lane_clips(lane).get(idx)?.clone();
74 let matches = |other: Lane| {
75 let i = session.lane_clips(other).iter().position(|c| {
76 (c.start, c.end()) == (clip.start, clip.end())
77 && !(c.link.is_some() && c.link == clip.link)
78 })?;
79 Some((other, i))
80 };
81 // Sound before picture (and picture before sound): "group this" means the
82 // other half of the take, and a project whose audio lane was added after a
83 // second video one has that half *after* the layer in storage order -- which
84 // is the order the lanes come in. A same-kind lane is still groupable (V1
85 // and V2 may be one take), but only where no opposite one covers the span.
86 let (opposite, same): (Vec<Lane>, Vec<Lane>) = session
87 .lanes()
88 .into_iter()
89 .filter(|&other| other != lane)
90 .partition(|other| other.kind != lane.kind);
91 opposite.into_iter().chain(same).find_map(matches)
92}
93
94/// What the timeline has picked: every clip and caption a hand ctrl-clicked
95/// into the selection, in click order and with no two the same. The last of
96/// them is the [`anchor`](Selection::anchor) -- the one every action that is
97/// about *one* thing (delete, lift, copy, the equalizer) acts on -- and the
98/// whole list is what a manual Group names to the engine.
99///
100/// Indices move under every edit, exactly as the single mark this replaces
101/// did, so every edit that renumbers a lane clears the picks it cannot keep
102/// honest. Pure and engine-free, so a test can build one without a window.
103#[derive(Clone, Debug, Default, PartialEq)]
104pub(crate) struct Selection {
105 /// `(lane, index into that lane's own list)` -- a subtitle lane's index
106 /// space for a caption, exactly the pair a click was told about.
107 picks: Vec<(Lane, usize)>,
108}
109
110impl Selection {
111 /// Nothing picked: what the timeline starts as and what an edit that moved
112 /// indices leaves behind.
113 pub(crate) fn new() -> Self {
114 Self::default()
115 }
116
117 /// The one a plain click and every selection key leave: the whole of the
118 /// selection, one pick. A click names a thing, and the things it had been
119 /// naming along with it are no longer named.
120 pub(crate) fn set_one(&mut self, pick: (Lane, usize)) {
121 self.picks.clear();
122 self.picks.push(pick);
123 }
124
125 /// A ctrl-click: the pick joins the selection if it was not in it and
126 /// leaves if it was -- the toggle that assembles a group by hand. The
127 /// order is the order they were picked in, and the anchor rides on it.
128 pub(crate) fn toggle(&mut self, pick: (Lane, usize)) {
129 match self.picks.iter().position(|&p| p == pick) {
130 Some(at) => {
131 self.picks.remove(at);
132 }
133 None => self.picks.push(pick),
134 }
135 }
136
137 /// The last pick: what "the selected clip" is to every action that acts on
138 /// one thing. The click order puts it under the hand, which is where the
139 /// eye is.
140 pub(crate) fn anchor(&self) -> Option<(Lane, usize)> {
141 self.picks.last().copied()
142 }
143
144 /// Moves `pick`, already one of the selection's, to the end, so it becomes
145 /// the [`Self::anchor`] while every other pick stays: a right-click inside a
146 /// selection keeps it, and the menu's one-clip items still act on the clip
147 /// the hand named.
148 pub(crate) fn promote(&mut self, pick: (Lane, usize)) {
149 if let Some(at) = self.picks.iter().position(|p| *p == pick) {
150 let pick = self.picks.remove(at);
151 self.picks.push(pick);
152 }
153 }
154
155 /// Whether `pick` is one of the selection's -- the question a right-click
156 /// asks before it decides whether the menu is about the selection or
157 /// about the clip under it.
158 pub(crate) fn contains(&self, pick: (Lane, usize)) -> bool {
159 self.picks.contains(&pick)
160 }
161
162 /// Every pick, in click order: what a manual Group names to the engine.
163 pub(crate) fn picks(&self) -> &[(Lane, usize)] {
164 &self.picks
165 }
166
167 pub(crate) fn is_empty(&self) -> bool {
168 self.picks.is_empty()
169 }
170
171 /// A pick that joins without disturbing the rest -- Select All's builder,
172 /// which names every placement there is and cannot be a `set_one`.
173 pub(crate) fn add(&mut self, pick: (Lane, usize)) {
174 if !self.picks.contains(&pick) {
175 self.picks.push(pick);
176 }
177 }
178}
179
180/// The lane stack's thumb over a track `h` px tall: `(y, height)` of the box
181/// standing for the visible share of a stack `content` px tall in a box
182/// `box_h` px tall, taken down by `scrolled` px. Full track when the whole
183/// stack is on screen, never shorter than
184/// [`SCROLL_THUMB_MIN`] when it is not, and never off the track either way.
185pub(crate) fn lanes_thumb(track: f32, content: f32, box_h: f32, scrolled: f32) -> (f32, f32) {
186 if track <= 0. || content <= 0. || box_h >= content {
187 return (0., track.max(0.));
188 }
189 let height = (track * box_h / content).clamp(SCROLL_THUMB_MIN, track);
190 let y = (scrolled / (content - box_h) * (track - height)).clamp(0., track - height);
191 (y, height)
192}
193
194impl Selection {
195 pub(crate) fn len(&self) -> usize {
196 self.picks.len()
197 }
198
199 pub(crate) fn clear(&mut self) {
200 self.picks.clear();
201 }
202}
203
204/// A hole the bed may offer as a gap: one with a placement on both sides of it. The stretch
205/// before a lane's first placement starts at frame 0 and is not a gap a hand made by moving
206/// clips apart, so it is never drawn, picked or closed -- an empty track reads as empty.
207/// `gap_at` still answers it for the engine; the bed asks this before it offers one.
208pub(crate) fn between_clips(hole: Option<(u32, u32)>) -> Option<(u32, u32)> {
209 hole.filter(|&(start, _)| start > 0)
210}
211
212/// Whether a click marks this box: any pick on it always, and any box sharing
213/// a group id with a pick -- the clip the anchor was ctrl-clicked beside, and
214/// the caption a hand pinned to a clip. A group whose only member is picked
215/// marks that member alone, which is what makes a detached half separately
216/// deletable.
217///
218/// `pick_links` are the group ids of the picks themselves, read by the caller
219/// off the session in the same order as `picks` -- the one fact this pure
220/// question cannot know.
221pub(crate) fn marked(
222 here: (Lane, usize),
223 link: Option<u32>,
224 picks: &[(Lane, usize)],
225 pick_links: &[Option<u32>],
226) -> bool {
227 picks.contains(&here) || (link.is_some() && pick_links.contains(&link))
228}
229
230/// The clip a trim is *showing*, worked out the way `Project::trim` will write
231/// it: the timeline room the edge leaves is turned into source frames by the one
232/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from
233/// that. The preview and the commit are then the same arithmetic -- a box let go
234/// of stays where the hand left it at every rate. Assigning the timeline count
235/// straight to the source field, as this used to, drew a speeded clip's tail
236/// moving at the wrong rate (it snapped on release) and drew a *head* trim
237/// moving the clip's other edge, since the length it implied was not the length
238/// the release would commit.
239///
240/// A still grows forward from source frame 0 instead: every frame of it is the
241/// same picture, so there is no earlier one for an in-point to walk back to.
242///
243/// Room too narrow to hold one source frame is the edit the engine refuses, and
244/// the box is drawn unchanged rather than as something that will not be
245/// committed.
246pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip {
247 // An edge that has not moved is not an edit, and `Project::trim` refuses it
248 // as one: the press that starts a drag must draw the clip it pressed, not a
249 // clip a rounding narrower.
250 if to
251 == match edge {
252 Edge::Start => clip.start,
253 Edge::End => clip.end(),
254 }
255 {
256 return clip;
257 }
258 match edge {
259 Edge::Start => {
260 // What survives is measured from the *end* -- the frames that stay
261 // play what they always played, which is what makes this a trim.
262 let Some(keep) = clip.fit_source(clip.end().saturating_sub(to)) else {
263 return clip;
264 };
265 match still {
266 true => Clip {
267 fade_in: 0,
268 fade_out: 0,
269 in_frame: 0,
270 out_frame: keep,
271 start: to,
272 ..clip
273 },
274 false => Clip {
275 fade_in: 0,
276 fade_out: 0,
277 in_frame: clip.out_frame - keep.min(clip.out_frame),
278 start: to,
279 ..clip
280 },
281 }
282 }
283 Edge::End => match clip.fit_source(to.saturating_sub(clip.start)) {
284 Some(keep) => Clip {
285 fade_in: 0,
286 fade_out: 0,
287 out_frame: clip.in_frame + keep,
288 ..clip
289 },
290 None => clip,
291 },
292 }
293}
294
295/// The cut odometer's own arithmetic (DESIGN.md §6): where `,` `.` land from
296/// `idx`, `stride` cuts forward or back among `len` of them. Clamped rather
297/// than wrapping -- an odometer that wraps at the last cut reads as landing
298/// back at the first, which is not "next" -- so a walk already at either end
299/// simply holds there, the way [`Player::step`]'s own ends do.
300pub(crate) fn walk_cut(idx: usize, len: usize, forward: bool, stride: usize) -> usize {
301 if len == 0 {
302 return 0;
303 }
304 let delta = stride.min(len - 1) as isize;
305 let at = if forward {
306 idx as isize + delta
307 } else {
308 idx as isize - delta
309 };
310 at.clamp(0, len as isize - 1) as usize
311}
312
313/// The no-aim trim's own arithmetic (DESIGN.md §6): `current` moved `dir`
314/// frames (usually ±1, a held key's ratchet) and clamped into the room
315/// [`engine::PlaybackSession::trim_room`] already answered -- the same wall a
316/// pointer drag is clamped to, so a keyboard trim can never draw an edge the
317/// engine would refuse.
318pub(crate) fn nudge_edge(current: u32, dir: i32, lo: u32, hi: u32) -> u32 {
319 (i64::from(current) + i64::from(dir)).clamp(i64::from(lo), i64::from(hi)) as u32
320}
321
322/// Where a pro trim's anchor (a cut's frame, a clip's start) lands when moved
323/// `by` frames, held inside the room `(lo, hi)` the engine answered
324/// ([`engine::PlaybackSession::roll_room`], [`engine::PlaybackSession::slide_room`]).
325pub(crate) fn pro_target(base: u32, by: i64, lo: u32, hi: u32) -> u32 {
326 (i64::from(base) + by).clamp(i64::from(lo), i64::from(hi)) as u32
327}
328
329/// Whether a loop-trim window ([`ActionId::LoopTrim`]) has been played out to
330/// its far edge and wants restarting at its near one: pure so the pump's own
331/// tick ([`Player::pump`]) is one `if` over a fact this decides. `None` --
332/// loop-trim off -- never restarts anything.
333pub(crate) fn should_loop_restart(frame: u32, window: Option<(u32, u32)>) -> bool {
334 window.is_some_and(|(_, hi)| frame >= hi)
335}
336
337/// Which window is actually looping, in priority order: the i/o range
338/// ([`Player::range`]) beats the subject-cut trim ([`Player::loop_trim`])
339/// beats the whole timeline -- but only once *something* is already armed
340/// (`loop_on` or `loop_trim`). A bare in/out mark with neither on is an
341/// export mark first, not a loop request, so it answers `None` here and
342/// never restarts anything on its own.
343pub(crate) fn active_loop_window(
344 loop_on: bool,
345 range: Option<(u32, u32)>,
346 loop_trim: Option<(u32, u32)>,
347) -> Option<(u32, u32)> {
348 if !loop_on && loop_trim.is_none() {
349 return None;
350 }
351 range.or(loop_trim)
352}
353
354/// How far a Play Around ([`ActionId::PlayAround`]) runs before the playhead and
355/// after it, in seconds.
356pub(crate) const PLAY_AROUND_PAD: f64 = 2.0;
357
358/// A Play Around in flight: where the playhead was when it began, and the second
359/// the run stops on. Kept on the [`Player`] until the run ends.
360#[derive(Clone, Copy, Debug, PartialEq)]
361pub(crate) struct PlayAround {
362 pub(crate) return_to: f64,
363 pub(crate) stop_at: f64,
364}
365
366/// The run a Play Around from `playhead` covers on a timeline `duration` seconds
367/// long: [`PLAY_AROUND_PAD`] before the playhead to the same after it, clamped to
368/// the timeline. `(start, stop)` in seconds.
369pub(crate) fn play_around_span(playhead: f64, duration: f64) -> (f64, f64) {
370 let start = (playhead - PLAY_AROUND_PAD).max(0.);
371 let stop = (playhead + PLAY_AROUND_PAD).min(duration.max(0.));
372 (start, stop)
373}
374
375/// How close to its stop a run must read before it counts as having reached it.
376/// The clock can stop a hair short of the timeline's end when play runs out.
377pub(crate) const PLAY_AROUND_SLACK: f64 = 0.05;
378
379/// Where a play resumes from on crossing into [`Transport::Ended`]
380/// (`Player::pump`): the active window's own near edge
381/// ([`active_loop_window`]) when one is armed, *even when its far edge is
382/// the film's own last frame* -- half of all cuts in a two-clip film sit on
383/// the final clip (DESIGN.md §6), so that coincidence is not an edge case
384/// and must not read as "reached the end, stop". Falls back to the
385/// whole-timeline loop's top, and `None` -- nothing armed -- restarts
386/// nothing, which is the halt this crossing otherwise means.
387pub(crate) fn loop_restart_frame(
388 loop_on: bool,
389 range: Option<(u32, u32)>,
390 loop_trim: Option<(u32, u32)>,
391) -> Option<u32> {
392 match active_loop_window(loop_on, range, loop_trim) {
393 Some((lo, _)) => Some(lo),
394 None => loop_on.then_some(0),
395 }
396}
397
398/// How many timeline frames a stretch of a subtitle track is worth: the one
399/// conversion between the two clocks a caption has -- microseconds for its
400/// words, frames for where it sits -- and the app-side twin of the engine's own
401/// (`Project::trim_sub_room`). Never zero: a placement of no frames is the one
402/// [`Project::place_sub`] refuses as empty, and a track shorter than a frame is
403/// still a caption somebody dragged.
404/// A fade handle's drag, turned into timeline frames: `dx` pixels at `pps`
405/// pixels per second, at `fps` frames per second -- the one conversion a
406/// fade-in or fade-out handle needs, and the app-side twin of every other
407/// pixel-to-frame door on this bed ([`Scale::time_at`]). Zero for a
408/// degenerate scale (nothing drawn to drag against), never negative on its
409/// own -- the caller adds this to the fade's length before clamping to the
410/// clip's own room, so a delta can still shrink a fade by coming back signed.
411pub(crate) fn fade_delta_frames(dx: f32, pps: f64, fps: f64) -> i64 {
412 if pps <= 0. {
413 return 0;
414 }
415 ((f64::from(dx) / pps) * fps).round() as i64
416}
417
418/// The spacing a ruler tick is drawn at, and so how its label reads
419/// (DESIGN §6.5).
420#[derive(Clone, Copy, Debug, PartialEq, Eq)]
421pub(crate) enum RulerStep {
422 /// Whole frames: a tick on a whole second reads as that second (`1s`),
423 /// the ones between read as frames past it (`+10f`).
424 Frames(u32),
425 /// Whole seconds, read as `2s`, `30s`, then `1:00`, `1:30` past a minute.
426 Seconds(u32),
427}
428
429/// Frame steps, in frames, for zoomed-in views where a whole second is still
430/// too wide to clear the pitch. Only the ones that divide the frame rate are
431/// used (`1, 5` at 25fps; `1, 2, 4, 6, 12` at 24fps; `1, 2, 5, 6, 10, 15` at
432/// 30fps), so every whole second is itself a tick and the `+Nf` labels count
433/// up to it and start over -- ten-frame ticks at 25fps would read `+20f`,
434/// `+5f`, `+15f` with the second never landing on one.
435const RULER_FRAME_STEPS: [u32; 10] = [1, 2, 4, 5, 6, 10, 12, 15, 20, 30];
436/// Second steps: the human ones -- 1 s, 2 s, 5 s, 10 s, 30 s, a minute, then
437/// 2, 5, 10 and 30 minutes and an hour. Never 15 s or 20 s, which a reader
438/// cannot count along.
439const RULER_SECOND_STEPS: [u32; 11] = [1, 2, 5, 10, 30, 60, 120, 300, 600, 1800, 3600];
440
441impl RulerStep {
442 /// The spacing in seconds at the project's frame rate.
443 pub(crate) fn secs(self, fps: f64) -> f64 {
444 match self {
445 RulerStep::Frames(n) => f64::from(n) / fps.max(1.),
446 RulerStep::Seconds(s) => f64::from(s),
447 }
448 }
449}
450
451/// The finest step whose pixel width at `pps` clears `min_px`, walking frame
452/// steps first, then the second steps up to an hour. Frame steps only appear
453/// once a whole second is wider than the pitch allows, so the far zoom never
454/// shows frame labels and the near zoom never shows minutes.
455pub(crate) fn ruler_step(pps: f64, fps: f64, min_px: f64) -> RulerStep {
456 let per_sec = (fps.ceil() as u32).max(1);
457 RULER_FRAME_STEPS
458 .iter()
459 .filter(|&&n| per_sec.is_multiple_of(n))
460 .map(|&n| RulerStep::Frames(n))
461 .chain(RULER_SECOND_STEPS.iter().map(|&s| RulerStep::Seconds(s)))
462 .find(|step| step.secs(fps) * pps >= min_px)
463 .unwrap_or(RulerStep::Seconds(3600))
464}
465
466/// A whole-second ruler label that cannot be misread as a timecode: `0s`,
467/// `2s`, `30s` under a minute, `1:00`, `1:30` past it, `1:00:00` past an
468/// hour. The transport's own `HH:MM:SS:FF` readout stays where it is; this
469/// is the ruler's shorter voice.
470pub(crate) fn ruler_seconds_label(secs: u64) -> String {
471 match secs {
472 s if s < 60 => format!("{s}s"),
473 s if s < 3600 => format!("{}:{:02}", s / 60, s % 60),
474 s => format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60),
475 }
476}
477
478/// The label of the `index`th tick at `step`: a second step reads the whole
479/// second, a frame step reads the whole second when it lands on one and
480/// `+Nf` frames past the last whole second otherwise. Indexed rather than
481/// timed so a frame tick never drifts onto the wrong frame over a long bed.
482pub(crate) fn ruler_label(step: RulerStep, index: u64, fps: f64) -> String {
483 match step {
484 RulerStep::Seconds(s) => ruler_seconds_label(index * u64::from(s)),
485 RulerStep::Frames(n) => {
486 let per_sec = (fps.ceil() as u64).max(1);
487 let frames = index * u64::from(n);
488 match frames % per_sec {
489 0 => ruler_seconds_label(frames / per_sec),
490 f => format!("+{f}f"),
491 }
492 }
493 }
494}
495
496/// Only the app's tests call this; the GUI path no longer does.
497#[cfg(test)]
498pub(crate) fn frames_of_us(us: i64, fps: f64) -> u32 {
499 match fps.is_finite() && fps > 0. {
500 true => ((us as f64) * fps / 1e6)
501 .round()
502 .clamp(1., f64::from(u32::MAX)) as u32,
503 false => 1,
504 }
505}
506
507/// The *placement* a trim is showing, the same way for a caption:
508/// [`Project::trim_sub`] moves the head or the tail and the window follows it,
509/// so the box on screen is the frames alone -- the words it will keep are the
510/// engine's arithmetic at the release, and nothing here draws them.
511///
512/// An edge that has not moved draws the placement it pressed, and one dragged
513/// past its other end keeps the one frame the engine's own walls always leave.
514pub(crate) fn trimmed_sub(sub: SubClip, edge: Edge, to: u32) -> SubClip {
515 match edge {
516 Edge::Start => {
517 let to = to.min(sub.end() - 1);
518 SubClip {
519 start: to,
520 frames: sub.end() - to,
521 ..sub
522 }
523 }
524 Edge::End => SubClip {
525 frames: to.max(sub.start + 1) - sub.start,
526 ..sub
527 },
528 }
529}
530
531/// Which index on its own lane a dragged clip is at *now*: the one it was picked
532/// up at while nothing has moved, and wherever the clip itself has slid to when
533/// an edit during the drag rippled the lane's indices -- a delete, an undo or a
534/// paste from a stroke, none of which gpui's frozen drag payload hears about.
535/// `None` when the clip is gone altogether, and then the drop is not an edit at
536/// all: moving whatever slid into its place is the one thing the hand did not
537/// ask for. A lane's clips are disjoint and sorted, so at most one of them can
538/// be the clip that was picked up. Generic over what a lane holds, because a
539/// [`SubClip`] is dragged under exactly the same rule.
540pub(crate) fn live_idx<T: PartialEq>(clips: &[T], idx: usize, clip: &T) -> Option<usize> {
541 match clips.get(idx) {
542 Some(at) if at == clip => Some(idx),
543 _ => clips.iter().position(|c| c == clip),
544 }
545}
546
547/// Which index a lane's mark is on after that lane was renumbered: the caption
548/// that starts at `start`, and `None` when it is not there any more.
549///
550/// The mark on a caption is an index like a clip's ([`Player::selected`]), and a
551/// subtitle lane both *inserts in start order* ([`engine::Project::place_sub`])
552/// and removes, so any placement or lift renumbers every caption after it and an
553/// index left as it was names a neighbour -- the caption the next Delete would
554/// take. So the mark is read off the caption's start frame before such an edit
555/// and found again by it after: captions on a lane are disjoint and in order, so
556/// a start frame names exactly one of them and is the identity an index is not.
557pub(crate) fn sub_mark(subs: &[SubClip], start: u32) -> Option<usize> {
558 subs.iter().position(|s| s.start == start)
559}
560
561/// Scales an envelope to its own loudest sample, so a quietly mastered source
562/// still draws as a shape. The fixtures peak around an eighth of full scale, and
563/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
564/// that is not.
565pub(crate) fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
566 let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
567 if loudest > 0. {
568 for (lo, hi) in &mut peaks {
569 *lo /= loudest;
570 *hi /= loudest;
571 }
572 }
573 peaks
574}
575
576/// The min/max envelope of `peaks` over the source seconds `from..to`, as
577/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
578/// -- a clip's waveform cannot paint over its neighbour -- and every column is
579/// at least a pixel tall, so silence reads as a line through the middle rather
580/// than as a polygon with no area.
581pub(crate) fn envelope(
582 peaks: &[(f32, f32)],
583 from: f64,
584 to: f64,
585 w: f32,
586 h: f32,
587) -> Vec<(f32, f32, f32)> {
588 if peaks.is_empty() || w <= 0. || h <= 0. {
589 return Vec::new();
590 }
591 let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX);
592 let mid = h / 2.;
593 (0..=cols)
594 .map(|col| {
595 let along = col as f64 / cols as f64;
596 let at = from + (to - from) * along;
597 // Casting a float to an integer saturates in Rust, so a source
598 // second past the end of the peaks clamps rather than wrapping.
599 let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
600 let (lo, hi) = peaks[bucket];
601 let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
602 let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
603 (w * along as f32, top.max(0.), bottom.min(h))
604 })
605 .collect()
606}
607
608/// Records its parent's laid-out box: gpui hands a mouse listener the window
609/// position only, and the ruler sits behind the panel's padding. Paints
610/// nothing and takes no hitbox of its own, so the click still reaches the bar.
611pub(crate) fn bounds_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
612 canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ())
613 .absolute()
614 .size_full()
615}
616
617/// [`bounds_probe`] for a box something *else* is laid out against: it also asks
618/// for one more frame whenever the height changed.
619///
620/// A measurement is read by the frame after the one that took it, and a notice
621/// arriving over a paused picture repaints exactly once -- so without this the
622/// cue would sit under that notice until something else happened to draw, which
623/// on a paused window can be never.
624pub(crate) fn height_probe(into: Rc<Cell<Pixels>>) -> impl IntoElement {
625 canvas(
626 move |bounds, window, _| {
627 // Only on a change: an unconditional request is a repaint loop.
628 if into.replace(bounds.size.height) != bounds.size.height {
629 window.request_animation_frame();
630 }
631 },
632 |_, _, _, _| (),
633 )
634 .absolute()
635 .size_full()
636}
637
638/// Where along an element a click landed, 0..1. An element that was never
639/// painted has no width, and reads as its start rather than as NaN.
640pub(crate) fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
641 if bounds.size.width <= px(0.) {
642 return 0.;
643 }
644 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
645}
646
647/// Where along an element a click landed, in pixels from its own left edge:
648/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`]
649/// measures in pixels and not in shares of a bed. Clamped to the element -- a
650/// drag that slid off the end names its end -- and an element that was never
651/// painted reads as its start.
652pub(crate) fn px_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
653 f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.))
654}
655
656/// [`px_along`] turned through a right angle, for the lane stack's scrollbar:
657/// how far down its track a press landed.
658pub(crate) fn px_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
659 f32::from(y - bounds.top()).clamp(0., f32::from(bounds.size.height).max(0.))
660}
661
662/// One turn of the wheel as a single number, positive for a turn *up*, in
663/// whatever units the device sends (a mouse counts lines, a touchpad pixels).
664/// A tilt wheel's own axis counts as the same gesture: it is the sideways
665/// scroll a mouse that has one sends, and the controls this drives have one
666/// direction each, so the two axes are one answer here.
667pub(crate) fn wheel_delta(event: &ScrollWheelEvent) -> f32 {
668 let (dx, dy) = match event.delta {
669 ScrollDelta::Lines(d) => (d.x, d.y),
670 ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)),
671 };
672 match dy == 0. {
673 true => dx,
674 false => dy,
675 }
676}
677
678/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is
679/// within `tol` frames of where its head -- or its tail, `len` frames along --
680/// would come to rest, in which case that edge wins. The snap every timeline
681/// has: clips meet exactly instead of a frame apart, and the hand does not have
682/// to aim. The nearest mark wins, and a head landing on one beats a tail at the
683/// same distance -- what was dragged is the head.
684pub(crate) fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
685 let mut best: Option<(u32, u32)> = None;
686 for &mark in marks {
687 // Head on the mark, then tail on it -- a clip dragged up against the
688 // take in front of it snaps by whichever end reaches first.
689 for start in [Some(mark), mark.checked_sub(len)] {
690 let Some(start) = start else { continue };
691 let d = start.abs_diff(raw);
692 if d <= tol && best.is_none_or(|(near, _)| d < near) {
693 best = Some((d, start));
694 }
695 }
696 }
697 best.map_or(raw, |(_, start)| start)
698}
699
700/// The edges worth landing on, off *every* lane: both ends of every clip on the
701/// timeline, less `skip` -- the clip being dragged, which does not snap to where
702/// it already is -- and less `skip_link`, the group id of whatever is being
703/// dragged: its clips travel with it, and so does any caption the id names.
704/// `skip` is a lane's place in `lanes` and an index into it; `skip_link` is
705/// read off a caption by the caller, whose drag has no clip for `skip` to
706/// name. The playhead and the head of the timeline go on the end: a clip meets
707/// the cursor and the start of the show as readily as it meets another take.
708/// `markers` are the comment markers' edges and the chapter starts, which the
709/// caller reads off the project ([`Player::snap_targets`]).
710///
711/// All lanes rather than the one being dropped on, because a cut is made across
712/// the timeline: a title on V2 lines up with the shot under it, and a sound
713/// effect lines up with the frame it belongs to.
714pub(crate) fn snap_marks(
715 lanes: &[&[Clip]],
716 skip: Option<(usize, usize)>,
717 skip_link: Option<u32>,
718 playhead: u32,
719 range: Option<(u32, u32)>,
720 markers: &[u32],
721) -> Vec<u32> {
722 let mut marks: Vec<u32> = lanes
723 .iter()
724 .enumerate()
725 .flat_map(|(lane, clips)| {
726 clips
727 .iter()
728 .enumerate()
729 .filter(move |&(idx, clip)| {
730 Some((lane, idx)) != skip && !(skip_link.is_some() && clip.link == skip_link)
731 })
732 .flat_map(|(_, clip)| [clip.start, clip.end()])
733 })
734 .collect();
735 marks.push(playhead);
736 marks.push(0);
737 // The in and out points ([`Player::range`]): a hand that has marked a
738 // stretch is working to it, and a clip meets its brackets as readily as it
739 // meets a cut.
740 if let Some((in_, out)) = range {
741 marks.push(in_);
742 marks.push(out);
743 }
744 // The comment markers' starts and ends and the chapter starts: a title lines
745 // up with the note it answers, and a chapter with a cut.
746 marks.extend_from_slice(markers);
747 marks
748}
749
750/// [`snapped`], and the mark that pulled it there -- the line the bed draws
751/// while the hand is still moving. `None` when nothing was near enough: a line
752/// standing over open bed would promise a landing that is not going to happen.
753/// The head is read before the tail, exactly as [`snapped`] prefers it.
754///
755/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
756/// draws no line at all, which is the whole point of being able to turn it off.
757pub(crate) fn snap_cue(
758 on: bool,
759 raw: u32,
760 len: u32,
761 tol: u32,
762 marks: &[u32],
763) -> (u32, Option<u32>) {
764 if !on {
765 return (raw, None);
766 }
767 let start = snapped(raw, len, tol, marks);
768 let mark = [start, start.saturating_add(len)]
769 .into_iter()
770 .find(|mark| marks.contains(mark));
771 (start, mark)
772}
773
774/// Whether the magnet is on for the gesture in flight: the switch, unless
775/// `alt` is held -- the temporary override Resolve, Premiere and Final Cut all
776/// put on that key, off for this one drag and leaving the switch where the hand
777/// left it. [`Player::snap_live`]'s whole rule, here so it can be read without
778/// a window.
779pub(crate) fn snap_live(on: bool, alt: bool) -> bool {
780 on && !alt
781}
782
783/// Where a drag lands and the mark that pulled it there: the frame under the
784/// pointer, less however far into the box the hand grabbed it (so a clip travels
785/// with the pointer rather than jumping its head under it), snapped by
786/// [`snap_cue`]. One answer, asked by the shadow drawn in flight
787/// ([`Player::preview_ghost`]), by the line ([`Player::preview_drop`]) and by
788/// the drop that commits ([`Player::move_clip`]) -- which is what makes the
789/// promise and the landing the same frame.
790pub(crate) fn landing(
791 under: u32,
792 grab: u32,
793 len: u32,
794 on: bool,
795 tol: u32,
796 marks: &[u32],
797) -> (u32, Option<u32>) {
798 snap_cue(on, under.saturating_sub(grab), len, tol, marks)
799}
800
801/// Where a clip `len` frames long, let go over *another* lane with its head
802/// asked at `at`, really comes to rest -- `None` when the engine refuses the
803/// drop outright. A mirror of [`Project::move_room`]: the release is refused
804/// only when the asked head sits *inside* a take already there (a clamp has no
805/// answer for that), or when the gap it names is narrower than the clip;
806/// otherwise the head is clamped into that gap exactly as a same-lane move is
807/// ([`gap_clamp`]). `others` is `(start, end)` of every clip already on the
808/// destination lane, less the ones travelling with this one.
809///
810/// The shadow reads this, so a landing the release *will* make is never drawn
811/// as refused -- a whole-span overlap test refuses far more than the engine
812/// does, and a shadow that lies about a refusal reads as a broken timeline.
813pub(crate) fn cross_room(at: u32, len: u32, others: &[(u32, u32)]) -> Option<u32> {
814 let (mut lo, mut hi) = (0, u32::MAX);
815 for &(other_start, other_end) in others {
816 if other_start <= at && at < other_end {
817 return None;
818 }
819 match other_end <= at {
820 true => lo = lo.max(other_end),
821 false => hi = hi.min(other_start),
822 }
823 }
824 match hi - lo < len {
825 true => None,
826 false => Some(at.clamp(lo, hi - len)),
827 }
828}
829
830/// Where a clip staying on its own lane really comes to rest: `want`, clamped
831/// into the gap it is sitting in -- the take behind it and the take in front of
832/// it are walls ([`Project::move_selection`] clamps the delta by exactly these,
833/// it does not refuse), so a clip dragged hard left past its neighbour lands
834/// flush against that neighbour's tail rather than nowhere. `now` is its head
835/// today, which is what names the gap. The shadow reads this, so the box drawn
836/// in flight is the box the release leaves behind.
837pub(crate) fn gap_clamp(now: u32, len: u32, want: u32, others: &[(u32, u32)]) -> u32 {
838 let lo = others
839 .iter()
840 .filter(|&&(_, end)| end <= now)
841 .map(|&(_, end)| end)
842 .max()
843 .unwrap_or(0);
844 let hi = others
845 .iter()
846 .filter(|&&(start, _)| start >= now.saturating_add(len))
847 .map(|&(start, _)| start)
848 .min()
849 .unwrap_or(u32::MAX);
850 want.clamp(lo, hi.saturating_sub(len).max(lo))
851}
852
853/// The lane a release lands on when the pointer is off the rows themselves:
854/// the row under it while its kind can hold what is in the hand, and otherwise
855/// the last one that could -- a picture clip carried down across A1 on its way
856/// to the empty bench below is still aiming at V1. [`Player::drag_lane`]'s
857/// whole rule.
858pub(crate) fn held_lane(prev: Option<Lane>, over: Lane, from: Lane) -> Option<Lane> {
859 match over.kind == from.kind {
860 true => Some(over),
861 false => prev,
862 }
863}
864
865/// Why this file may not go on that lane, in the words the refusal is told in --
866/// `None` when it may. A file with no picture belongs on an audio lane and
867/// nowhere else, and a still is silent, so an audio lane is the one place it
868/// cannot go. Asked twice: by the ghost tinting itself as refused on the way
869/// down, and by the insert that commits ([`Player::insert_source`]), so what is
870/// shown as impossible is exactly what is refused.
871///
872/// `has_video` is [`Player::has_video`]'s answer for `path`: the probed truth
873/// where the header has been read, and an extension's guess otherwise -- never
874/// `engine::is_audio` alone, which a song muxed into an `.mp4` lies to.
875pub(crate) fn lane_refuses(path: &Path, lane: Lane, has_video: bool) -> Option<String> {
876 let name = file_name(path);
877 let label = lane.label();
878 match lane.kind {
879 LaneKind::Video if !has_video => Some(format!("Not on {label} — {name} has no picture")),
880 LaneKind::Audio if engine::is_image(path) => {
881 Some(format!("Not on {label} — {name} is a still image"))
882 }
883 // A subtitle lane holds words and no media at all: the refusal is here
884 // rather than at the engine's door so the shadow is tinted red on the
885 // way down, like every other lane a file cannot go on.
886 LaneKind::Subtitle => Some(format!(
887 "Not on {label} — {name} is a file; a subtitle track takes captions, dragged from the \
888 Subtitles list"
889 )),
890 _ => None,
891 }
892}
893
894/// What a three-point edit needs to know, gathered from the window so the plan
895/// itself ([`plan_source_edit`]) is arithmetic and can be tested without one.
896pub(crate) struct SourceEditAsk<'a> {
897 pub(crate) fps: f64,
898 /// Every media lane, with whether it is locked.
899 pub(crate) lanes: &'a [(Lane, bool)],
900 pub(crate) playhead: u32,
901 /// The timeline's in/out marks, in frames.
902 pub(crate) range: Option<(u32, u32)>,
903 /// The item's own marks, in seconds of the file.
904 pub(crate) marks: (Option<f64>, Option<f64>),
905 /// The source's index in the project, and its length in timeline frames.
906 pub(crate) source: usize,
907 pub(crate) total: u32,
908 pub(crate) picture: bool,
909 pub(crate) sound: bool,
910 pub(crate) still: bool,
911 /// The source patch: the video lane the picture goes to and the audio lane the sound goes
912 /// to. `None` falls to the first unlocked lane of the kind, as it always did.
913 pub(crate) video_patch: Option<Lane>,
914 pub(crate) audio_patch: Option<Lane>,
915}
916
917/// The three-point edit the keys ask for: where it lands (`at`, a frame) and
918/// the `(lane, clip)` halves of the take.
919///
920/// Where: the timeline's in mark when one is set, else the playhead. How long:
921/// the source's marked in..out when it has an out mark; else the timeline's
922/// in..out length when that is set (the classic three-point: source in plus a
923/// timeline range); else to the end of the file. A still takes no marks and
924/// shows for the timeline range, else five seconds. Lanes: the first unlocked
925/// video lane for the picture and the first unlocked audio lane for the sound,
926/// whichever halves the source has.
927pub(crate) fn plan_source_edit(ask: &SourceEditAsk) -> Result<(u32, Vec<(Lane, Clip)>), String> {
928 let free = |kind: LaneKind, patch: Option<Lane>| match patch.filter(|p| ask.lanes.iter().any(|(l, _)| l == p)) {
929 Some(lane) => Some(lane),
930 None => ask.lanes.iter().find(|(l, locked)| l.kind == kind && !locked).map(|(l, _)| *l),
931 };
932 let frame = |t: f64| (t.max(0.) * ask.fps).round() as u32;
933 let (at, tl_len) = match ask.range {
934 Some((a, b)) if b > a => (a, Some(b - a)),
935 _ => (ask.playhead, None),
936 };
937 let (in_f, out_f) = if ask.still {
938 (0, tl_len.unwrap_or_else(|| (5. * ask.fps).ceil() as u32))
939 } else {
940 let in_f = ask.marks.0.map_or(0, frame);
941 let out_f = match (ask.marks.1, tl_len) {
942 (Some(t), _) => frame(t),
943 (None, Some(len)) => in_f.saturating_add(len),
944 (None, None) => ask.total,
945 };
946 (in_f, out_f.min(ask.total))
947 };
948 if out_f <= in_f {
949 return Err("The marked range is empty".into());
950 }
951 let mut items = Vec::new();
952 if ask.picture {
953 let lane = free(LaneKind::Video, ask.video_patch).ok_or("Every video track is locked")?;
954 items.push((lane, Clip::source_range(ask.source, in_f, out_f)));
955 }
956 if ask.sound {
957 let lane = free(LaneKind::Audio, ask.audio_patch).ok_or("Every audio track is locked")?;
958 items.push((lane, Clip::source_range(ask.source, in_f, out_f)));
959 }
960 if items.is_empty() {
961 return Err("That source has neither picture nor sound".into());
962 }
963 Ok((at, items))
964}
965
966/// Where down an element a pointer sits, 0..1 from the top: the vertical twin
967/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
968/// element that was never painted reads as its middle -- flat, the one answer
969/// that changes nothing -- rather than as a full boost.
970pub(crate) fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
971 if bounds.size.height <= px(0.) {
972 return 0.5;
973 }
974 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
975}
976
977#[cfg(test)]
978mod drop_landing_tests {
979 use super::*;
980
981 /// A release a few pixels' worth of frames right of an empty timeline's
982 /// head still lands on frame 0: [`snap_marks`] always offers 0
983 /// (`marks.push(0)`, above) even with no clips on the timeline yet, so
984 /// the "you must be exactly at 0.0" complaint is the tolerance, not a
985 /// missing mark.
986 #[test]
987 fn a_pull_near_the_head_of_an_empty_timeline_snaps_to_frame_0() {
988 let marks = snap_marks(&[&[]], None, None, 0, None, &[]);
989 assert!(marks.contains(&0), "an empty timeline still offers frame 0");
990 assert_eq!(snapped(4, 0, 10, &marks), 0);
991 // Outside the tolerance, the raw ask stands: this is a magnet, not a
992 // clamp to 0.
993 assert_eq!(snapped(11, 0, 10, &marks), 11);
994 }
995
996 /// A clip already on the lane offers both of its own edges as marks
997 /// ([`snap_marks`]'s `flat_map(|clip| [clip.start, clip.end()])`), and a
998 /// release close to either -- within the drop tolerance -- lands on it
999 /// rather than the raw pixel.
1000 #[test]
1001 fn a_pull_near_a_clip_edge_snaps_onto_it() {
1002 let marks = [0, 100, 200];
1003 assert_eq!(snapped(205, 0, 10, &marks), 200);
1004 }
1005
1006 /// The playhead is a mark too, so a clip let go near it lines up with
1007 /// where the timeline is parked.
1008 #[test]
1009 fn a_pull_near_the_playhead_snaps_onto_it() {
1010 let marks = snap_marks(&[&[]], None, None, 500, None, &[]);
1011 assert!(marks.contains(&500));
1012 assert_eq!(snapped(493, 0, 10, &marks), 500);
1013 }
1014
1015 /// The user's own repro: a clip dragged left through the lane-head column
1016 /// -- window x *left of the bed* -- lands on frame 0 rather than nowhere.
1017 /// Two clamps do it, and both are on the path the bench now takes for a
1018 /// drop over the head ([`Player::frame_under`]): [`px_along`] pins an x
1019 /// before the bed's left edge to 0 px, [`Scale::time_at`] pins the moment
1020 /// to 0 s, and the grab offset comes off with a saturating subtraction, so
1021 /// even a clip held by its tail cannot ask for a negative frame.
1022 #[test]
1023 fn a_drag_out_over_the_lane_head_lands_on_frame_0() {
1024 let bed = Bounds {
1025 origin: point(px(100.), px(0.)),
1026 size: size(px(900.), px(60.)),
1027 };
1028 let scale = Scale::default();
1029 // 40 px into the head column, and off the window entirely.
1030 for x in [px(60.), px(-400.)] {
1031 assert_eq!(px_along(x, bed), 0.);
1032 let under = frame_at(scale.time_at(px_along(x, bed)), 25.);
1033 assert_eq!(under, 0);
1034 // Grabbed 30 frames into the box: still frame 0, never a refusal.
1035 assert_eq!(landing(under, 30, 50, true, 10, &[0, 300]), (0, Some(0)));
1036 }
1037 }
1038
1039 /// Both edges of the clip in the hand are candidates and the nearest one
1040 /// wins: a tail 2 frames short of a neighbour's head beats a head 8 frames
1041 /// from the timeline's start.
1042 #[test]
1043 fn the_nearer_of_the_two_edges_wins() {
1044 let marks = [0, 300, 500];
1045 // len 292: the tail wants 300 (2 away), the head 0 (8 away).
1046 // The tail already sits exactly on 300, so the head is left alone.
1047 assert_eq!(snapped(8, 292, 10, &marks), 8);
1048 assert_eq!(snapped(6, 292, 10, &marks), 8, "tail meets 300, head stays");
1049 }
1050
1051 /// The threshold is a distance on *screen*: the same 10 px of aim at two
1052 /// zooms is a different number of frames, which is what makes the magnet
1053 /// feel identical zoomed in and zoomed out ([`Scale::drop_snap_frames`]).
1054 /// Outside it the drag follows the pointer exactly.
1055 #[test]
1056 fn the_threshold_is_ten_pixels_at_any_zoom() {
1057 let fps = 25.;
1058 for pps in [50., 400.] {
1059 let scale = Scale { pps, start: 0. };
1060 let tol = scale.drop_snap_frames(fps);
1061 // 10 px worth of frames, and one frame more than that is not near.
1062 let near = (DROP_SNAP_PX / pps * fps) as u32;
1063 assert_eq!(tol, near);
1064 assert_eq!(snapped(500 + tol, 0, tol, &[500]), 500);
1065 assert_eq!(
1066 snapped(500 + tol + 1, 0, tol, &[500]),
1067 500 + tol + 1,
1068 "past the window the pointer is obeyed exactly"
1069 );
1070 }
1071 }
1072
1073 /// `alt` held turns the magnet off for the gesture and nothing else: the
1074 /// same raw ask, no line, and [`Player::snap`] itself untouched.
1075 #[test]
1076 fn alt_turns_the_magnet_off_for_this_drag_only() {
1077 let on = true;
1078 assert!(snap_live(on, false));
1079 assert!(!snap_live(on, true));
1080 let marks = [0, 300];
1081 assert_eq!(
1082 snap_cue(snap_live(on, true), 297, 0, 10, &marks),
1083 (297, None)
1084 );
1085 assert_eq!(
1086 snap_cue(snap_live(on, false), 297, 0, 10, &marks),
1087 (300, Some(300))
1088 );
1089 // The switch off stays off however the modifier is held.
1090 assert!(!snap_live(false, false));
1091 }
1092
1093 /// Every target an NLE offers is on the list: frame 0, the playhead, both
1094 /// edges of every clip on *every* lane, and the in/out brackets.
1095 #[test]
1096 fn the_targets_are_zero_the_playhead_the_edges_and_the_marks() {
1097 let clip = |start: u32, frames: u32| Clip {
1098 speed_keys: Vec::new(),
1099 reversed: false,
1100 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1101 angle: Default::default(),
1102 fade_in: 0,
1103 fade_out: 0,
1104 transition_out: 0,
1105 transition_kind: Default::default(),
1106 visualizer: 0,
1107 viz_paint: 0,
1108 gain_db: 0.0,
1109 gain_keys: Vec::new(),
1110 pan: 0,
1111 pitch: 0.0,
1112 transform_keys: Vec::new(),
1113 opacity_keys: Vec::new(),
1114 color_keys: Vec::new(),
1115 effects: Vec::new(),
1116 start,
1117 in_frame: 0,
1118 out_frame: frames,
1119 source: 0,
1120 link: None,
1121 eq: None,
1122 color: None,
1123 transform: None,
1124 fit: Default::default(),
1125 speed: Default::default(),
1126 };
1127 let v1 = [clip(100, 50), clip(400, 50)];
1128 let a1 = [clip(700, 20)];
1129 let marks = snap_marks(&[&v1, &a1], None, None, 900, Some((250, 600)), &[]);
1130 for want in [0, 900, 100, 150, 400, 450, 700, 720, 250, 600] {
1131 assert!(marks.contains(&want), "{want} is not a snap target");
1132 }
1133 // And each of them actually pulls a drag onto itself.
1134 for target in [0, 250, 600, 900] {
1135 assert_eq!(snapped(target + 4, 0, 10, &marks), target);
1136 }
1137 }
1138
1139 /// A release on the empty bench below the last row, or left of the heads,
1140 /// lands on the lane the last live sample was over -- and a lane of the
1141 /// wrong kind crossed on the way down never steals it.
1142 #[test]
1143 fn the_last_lane_that_could_hold_it_keeps_the_drag() {
1144 let v1 = Lane::V1;
1145 let v2 = Lane::new(LaneKind::Video, 1);
1146 let a1 = Lane::A1;
1147 // The head column is part of the row, so the row over it is the answer.
1148 assert_eq!(held_lane(None, v1, v1), Some(v1));
1149 assert_eq!(held_lane(Some(v1), v2, v1), Some(v2));
1150 assert_eq!(
1151 held_lane(Some(v2), a1, v1),
1152 Some(v2),
1153 "audio cannot hold it"
1154 );
1155 // Nothing promised yet and nothing that can hold it: no landing.
1156 assert_eq!(held_lane(None, a1, v1), None);
1157 }
1158
1159 /// A clip dragged hard left past the take in front of it comes to rest
1160 /// flush against that take -- the walls of its own gap, which is what the
1161 /// engine clamps the drag by -- and one dragged off the head of the
1162 /// timeline rests on frame 0.
1163 #[test]
1164 fn a_drag_past_a_neighbour_rests_flush_against_it() {
1165 let others = [(0, 375), (900, 1000)];
1166 assert_eq!(gap_clamp(375, 500, 0, &others), 375, "flush with its tail");
1167 assert_eq!(gap_clamp(375, 500, 380, &others), 380, "room to spare");
1168 assert_eq!(
1169 gap_clamp(375, 500, 800, &others),
1170 400,
1171 "flush with the next"
1172 );
1173 // An empty lane clamps at the head of the timeline and nowhere else.
1174 assert_eq!(gap_clamp(500, 100, 0, &[]), 0);
1175 assert_eq!(gap_clamp(500, 100, 9_000, &[]), 9_000);
1176 }
1177
1178 /// The cross-lane shadow's rule, mirroring the engine: refused only when
1179 /// the asked head is inside a take or the gap is too narrow, and otherwise
1180 /// clamped into the gap rather than refused. The middle case is the
1181 /// verifier's repro -- an obstacle at (360, 420), a 90-frame clip asked at
1182 /// 315, which the engine lands at 270.
1183 #[test]
1184 fn a_cross_lane_landing_clamps_into_the_gap_the_engine_leaves() {
1185 let others = [(360, 420)];
1186 assert_eq!(
1187 cross_room(315, 90, &others),
1188 Some(270),
1189 "clamped, not refused"
1190 );
1191 assert_eq!(cross_room(380, 90, &others), None, "head inside the take");
1192 assert_eq!(cross_room(100, 90, &others), Some(100), "room to spare");
1193 let tight = [(0, 100), (150, 300)];
1194 assert_eq!(
1195 cross_room(120, 90, &tight),
1196 None,
1197 "the gap is 50 frames wide"
1198 );
1199 assert_eq!(
1200 cross_room(120, 50, &tight),
1201 Some(100),
1202 "and holds a 50-frame clip"
1203 );
1204 assert_eq!(
1205 cross_room(500, 90, &[]),
1206 Some(500),
1207 "an empty lane takes it as asked"
1208 );
1209 }
1210}
1211
1212#[cfg(test)]
1213mod ruler_label_tests {
1214 use super::*;
1215
1216 /// The pitch a ruler label needs, the ruler's own constant.
1217 const MIN: f64 = 80.;
1218
1219 /// The pitch a step gives at `pps`, in pixels.
1220 fn pitch(step: RulerStep, pps: f64, fps: f64) -> f64 {
1221 step.secs(fps) * pps
1222 }
1223
1224 #[test]
1225 fn the_steps_are_human_at_every_zoom_and_rate() {
1226 // 24, 25, 30 and 60 fps at the default 60px/s: a second is 60px and
1227 // misses, so two seconds (120px) is the step at every rate.
1228 for fps in [24., 25., 30., 60.] {
1229 assert_eq!(ruler_step(60., fps, MIN), RulerStep::Seconds(2), "{fps}");
1230 }
1231 // 300px/s: at 30fps ten frames is 100px; at 24fps ten does not divide
1232 // the rate, so twelve (150px); at 25fps five frames is 60px and the
1233 // next divisor is the second itself (300px); at 60fps ten frames is
1234 // only 50px, so twenty (a third of a second, 100px).
1235 assert_eq!(ruler_step(300., 30., MIN), RulerStep::Frames(10));
1236 assert_eq!(ruler_step(300., 24., MIN), RulerStep::Frames(12));
1237 assert_eq!(ruler_step(300., 25., MIN), RulerStep::Seconds(1));
1238 assert_eq!(ruler_step(300., 60., MIN), RulerStep::Frames(20));
1239 // 600px/s at 25fps: five frames is 120px, the audit's own case.
1240 assert_eq!(ruler_step(600., 25., MIN), RulerStep::Frames(5));
1241 // 2000px/s: one frame at 24fps is 83px and clears; at 30fps it is 67px
1242 // so two frames; at 60fps it is 33px so four frames (133px).
1243 assert_eq!(ruler_step(2000., 24., MIN), RulerStep::Frames(1));
1244 assert_eq!(ruler_step(2000., 30., MIN), RulerStep::Frames(2));
1245 assert_eq!(ruler_step(2000., 60., MIN), RulerStep::Frames(4));
1246 // A frame step always divides its rate, at every zoom and rate.
1247 for fps in [24., 25., 30., 60.] {
1248 for pps in [100., 200., 500., 1000., 3000., 10_000.] {
1249 if let RulerStep::Frames(n) = ruler_step(pps, fps, MIN) {
1250 assert_eq!((fps as u32) % n, 0, "{n} frames at {fps}fps, {pps}px/s");
1251 }
1252 }
1253 }
1254 // Zoomed out: 4px/s wants 30s (120px), never a 15s or 20s stop.
1255 assert_eq!(ruler_step(4., 25., MIN), RulerStep::Seconds(30));
1256 // 1px/s: a minute is 60px, so two minutes.
1257 assert_eq!(ruler_step(1., 25., MIN), RulerStep::Seconds(120));
1258 assert_eq!(ruler_step(0.1, 25., MIN), RulerStep::Seconds(1800));
1259 // A zoom no view allows still answers with the far stop.
1260 assert_eq!(ruler_step(0.001, 25., MIN), RulerStep::Seconds(3600));
1261 }
1262
1263 #[test]
1264 fn every_zoom_gives_a_pitch_of_at_least_the_minimum() {
1265 for fps in [24., 25., 29.97, 30., 60.] {
1266 let mut pps = crate::layout::PPS_MIN;
1267 while pps <= 10_000. {
1268 let step = ruler_step(pps, fps, MIN);
1269 let got = pitch(step, pps, fps);
1270 assert!(
1271 got >= MIN || step == RulerStep::Seconds(3600),
1272 "pps {pps} fps {fps}: {step:?} gives {got}px"
1273 );
1274 pps *= 1.1;
1275 }
1276 }
1277 }
1278
1279 #[test]
1280 fn second_labels_read_as_seconds_then_as_minutes() {
1281 assert_eq!(ruler_seconds_label(0), "0s");
1282 assert_eq!(ruler_seconds_label(1), "1s");
1283 assert_eq!(ruler_seconds_label(30), "30s");
1284 assert_eq!(ruler_seconds_label(59), "59s");
1285 assert_eq!(ruler_seconds_label(60), "1:00");
1286 assert_eq!(ruler_seconds_label(90), "1:30");
1287 assert_eq!(ruler_seconds_label(600), "10:00");
1288 assert_eq!(ruler_seconds_label(3600), "1:00:00");
1289 assert_eq!(ruler_seconds_label(3723), "1:02:03");
1290 // A second step walks in its own units.
1291 let labels: Vec<_> = (0..4).map(|i| ruler_label(RulerStep::Seconds(2), i, 25.)).collect();
1292 assert_eq!(labels, ["0s", "2s", "4s", "6s"]);
1293 let labels: Vec<_> = (0..4).map(|i| ruler_label(RulerStep::Seconds(30), i, 25.)).collect();
1294 assert_eq!(labels, ["0s", "30s", "1:00", "1:30"]);
1295 }
1296
1297 #[test]
1298 fn frame_labels_read_as_frames_past_the_second_and_never_as_a_timecode() {
1299 // The 2s-at-25fps clip the audit saw: five-frame ticks read 0s, +5f,
1300 // +10f, +15f, +20f, 1s, +5f -- never `00:01:00`.
1301 let labels: Vec<_> = (0..7).map(|i| ruler_label(RulerStep::Frames(5), i, 25.)).collect();
1302 assert_eq!(labels, ["0s", "+5f", "+10f", "+15f", "+20f", "1s", "+5f"]);
1303 // 24fps in twos: the twelfth tick is the whole second.
1304 assert_eq!(ruler_label(RulerStep::Frames(2), 12, 24.), "1s");
1305 assert_eq!(ruler_label(RulerStep::Frames(2), 11, 24.), "+22f");
1306 // 30fps in fives, 60fps in tens.
1307 assert_eq!(ruler_label(RulerStep::Frames(5), 7, 30.), "+5f");
1308 assert_eq!(ruler_label(RulerStep::Frames(10), 6, 60.), "1s");
1309 assert_eq!(ruler_label(RulerStep::Frames(10), 7, 60.), "+10f");
1310 // Single frames at 24fps, deep into the bed, stay on their frame.
1311 assert_eq!(ruler_label(RulerStep::Frames(1), 24 * 61 + 3, 24.), "+3f");
1312 assert_eq!(ruler_label(RulerStep::Frames(1), 24 * 61, 24.), "1:01");
1313 // A fractional rate counts frames to its ceiling, as the timecode does.
1314 assert_eq!(ruler_label(RulerStep::Frames(1), 29, 29.97), "+29f");
1315 assert_eq!(ruler_label(RulerStep::Frames(1), 30, 29.97), "1s");
1316 for label in (0..200).map(|i| ruler_label(RulerStep::Frames(5), i, 25.)) {
1317 assert!(!label.starts_with("00:"), "{label} reads like a timecode");
1318 }
1319 }
1320}
1321
1322#[cfg(test)]
1323mod between_clips_tests {
1324 use super::*;
1325
1326 /// The stretch before a lane's first placement is not a gap a hand can close, so the bed
1327 /// never draws it on an empty-looking track; a hole with a placement on each side is.
1328 #[test]
1329 fn a_hole_before_the_first_placement_is_not_a_gap() {
1330 assert_eq!(between_clips(Some((0, 30))), None);
1331 assert_eq!(between_clips(Some((30, 10))), Some((30, 10)));
1332 assert_eq!(between_clips(None), None);
1333 }
1334}