forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

transform.rs884 lines, 36.9 KiBHistoryRawDownload
1//! Per-clip position/scale/rotate/crop, applied engine-side on the placed
2//! picture so that playback and export land the same pixel from the same
3//! numbers -- [`crate::color::ColorParams`]'s twin in every respect but what
4//! it moves: a grade changes what a sample *is*, this changes where it *goes*.
5//!
6//! Plain data with no invariants of its own: out-of-range or non-finite
7//! values are clamped where the geometry is built ([`crate::scale::crop_rect`],
8//! [`crate::scale::transformed_dst_rect`]), so a deserializer can hand this
9//! over unchecked, exactly as [`ColorParams`](crate::color::ColorParams) can.
10
11/// One clip's placement on the project canvas, on top of whatever
12/// [`crate::scale::FitPolicy`] already does.
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct TransformParams {
15 /// Canvas-fraction offset from centred, positive right. `0.0` is
16 /// identity.
17 pub pos_x: f32,
18 /// Canvas-fraction offset from centred, positive down. `0.0` is identity.
19 pub pos_y: f32,
20 /// Multiplier on the fit-policy placement size. `1.0` is identity.
21 pub scale: f32,
22 /// Degrees, clockwise. Rendered at the nearest 90-degree step
23 /// ([`crate::scale::rotate_i420_90s`]); the value itself is kept exactly,
24 /// so a UI that later grows continuous rotation loses nothing already
25 /// saved. `0.0` is identity.
26 pub rotate: f32,
27 /// Fraction of the source cropped off the left, `0.0..0.5`.
28 pub crop_l: f32,
29 /// Fraction of the source cropped off the right, `0.0..0.5`.
30 pub crop_r: f32,
31 /// Fraction of the source cropped off the top, `0.0..0.5`.
32 pub crop_t: f32,
33 /// Fraction of the source cropped off the bottom, `0.0..0.5`.
34 pub crop_b: f32,
35 /// How much of the placed picture shows over what is beneath it, `0.0..=1.0`:
36 /// `1.0` is opaque and the identity. A layer is blended over the layers
37 /// below by this fraction of its own coverage; a single clip is faded toward
38 /// the black canvas it sits on. The blend is on the stored Y'CbCr code values,
39 /// exactly as a dissolve blends them: gamma-encoded video code values, not
40 /// linear light. So 50% white over black is the midpoint of the two codes
41 /// (limited range: luma 16 and 235 give 126), which the eye reads as mid grey.
42 pub opacity: f32,
43}
44
45impl Default for TransformParams {
46 fn default() -> Self {
47 Self {
48 pos_x: 0.0,
49 pos_y: 0.0,
50 scale: 1.0,
51 rotate: 0.0,
52 crop_l: 0.0,
53 crop_r: 0.0,
54 crop_t: 0.0,
55 crop_b: 0.0,
56 opacity: 1.0,
57 }
58 }
59}
60
61impl TransformParams {
62 /// Whether this is the do-nothing setting. Compared exactly, for
63 /// [`crate::color::ColorParams::is_identity`]'s reason: only a value that
64 /// is precisely identity is allowed to skip the geometry.
65 pub fn is_identity(&self) -> bool {
66 self.pos_x == 0.0
67 && self.pos_y == 0.0
68 && self.scale == 1.0
69 && self.rotate == 0.0
70 && self.crop_l == 0.0
71 && self.crop_r == 0.0
72 && self.crop_t == 0.0
73 && self.crop_b == 0.0
74 && self.opacity == 1.0
75 }
76}
77
78/// The most keys a clip's transform animation may hold
79/// ([`crate::project::Clip::transform_keys`]).
80pub const MAX_TRANSFORM_KEYS: usize = 256;
81
82/// How a key eases into the segment after it: `Linear` moves at a constant
83/// rate, `Ease` (ease in-out) starts and stops gently (smoothstep), `EaseIn`
84/// starts slowly and ends at speed (cubic), `EaseOut` starts at speed and
85/// lands gently (cubic), and `Hold` keeps the key's value until the next key
86/// and then jumps (a step). The last key has no segment after it, so its own
87/// ease is never read. One shape for every key type ([`ease_shape`]).
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89pub enum KeyEase {
90 #[default]
91 Linear,
92 Ease,
93 EaseIn,
94 EaseOut,
95 Hold,
96}
97
98impl KeyEase {
99 /// Every ease, in the order a picker lists them.
100 pub const ALL: [KeyEase; 5] = [
101 KeyEase::Linear,
102 KeyEase::EaseIn,
103 KeyEase::EaseOut,
104 KeyEase::Ease,
105 KeyEase::Hold,
106 ];
107
108 /// The name the tools and the GUI use: `linear`, `ease_in`, `ease_out`,
109 /// `ease_in_out` or `hold`.
110 pub fn name(self) -> &'static str {
111 match self {
112 KeyEase::Linear => "linear",
113 KeyEase::EaseIn => "ease_in",
114 KeyEase::EaseOut => "ease_out",
115 KeyEase::Ease => "ease_in_out",
116 KeyEase::Hold => "hold",
117 }
118 }
119
120 /// [`name`](Self::name) read back. `ease` is the older spelling of `ease_in_out`.
121 pub fn from_name(name: &str) -> Option<KeyEase> {
122 Some(match name {
123 "linear" => KeyEase::Linear,
124 "ease_in" => KeyEase::EaseIn,
125 "ease_out" => KeyEase::EaseOut,
126 "ease_in_out" | "ease" => KeyEase::Ease,
127 "hold" => KeyEase::Hold,
128 _ => return None,
129 })
130 }
131
132 /// The token a project file writes (`lin`, `in`, `out`, `ease`, `hold`).
133 pub fn token(self) -> &'static str {
134 match self {
135 KeyEase::Linear => "lin",
136 KeyEase::EaseIn => "in",
137 KeyEase::EaseOut => "out",
138 KeyEase::Ease => "ease",
139 KeyEase::Hold => "hold",
140 }
141 }
142
143 /// [`token`](Self::token) read back.
144 pub fn from_token(token: &[u8]) -> Option<KeyEase> {
145 Some(match token {
146 b"lin" => KeyEase::Linear,
147 b"in" => KeyEase::EaseIn,
148 b"out" => KeyEase::EaseOut,
149 b"ease" => KeyEase::Ease,
150 b"hold" => KeyEase::Hold,
151 _ => return None,
152 })
153 }
154
155 /// The next ease in [`ALL`](Self::ALL), wrapping: what a "cycle the easing" button does.
156 pub fn next(self) -> KeyEase {
157 let i = Self::ALL.iter().position(|e| *e == self).unwrap_or(0);
158 Self::ALL[(i + 1) % Self::ALL.len()]
159 }
160}
161
162/// How far along its segment a value is, once `ease` has shaped the plain
163/// fraction `t` (`0..=1`) of the way between two keys. `0` at `t == 0` and `1`
164/// at `t == 1` for every ease but `Hold`, which stays `0` until the segment is
165/// done. The one function every key type's interpolation goes through.
166pub fn ease_shape(ease: KeyEase, t: f32) -> f32 {
167 match ease {
168 KeyEase::Linear => t,
169 KeyEase::Ease => t * t * (3.0 - 2.0 * t),
170 KeyEase::EaseIn => t * t * t,
171 KeyEase::EaseOut => {
172 let u = 1.0 - t;
173 1.0 - u * u * u
174 }
175 KeyEase::Hold => {
176 if t >= 1.0 {
177 1.0
178 } else {
179 0.0
180 }
181 }
182 }
183}
184
185/// One point of a clip's transform animation ([`crate::project::Clip::transform_keys`]):
186/// the whole [`TransformParams`] at source frame `at`. `at` is an absolute
187/// source frame, numbered as `in_frame` is, so a trim leaves every key on the
188/// footage it was set on -- the same promise a volume point makes
189/// ([`crate::project::GainKey`]).
190#[derive(Debug, Clone, Copy, PartialEq)]
191pub struct TransformKey {
192 /// Source frame of the key.
193 pub at: u32,
194 /// The placement exactly at that frame.
195 pub params: TransformParams,
196 /// The easing of the segment that leaves this key.
197 pub ease: KeyEase,
198}
199
200/// A key of an animation: a value at source frame `at` and the ease of the
201/// segment that leaves it. The interpolation, the trim and the split are
202/// written once over this and shared by every key type.
203pub trait Keyed: Copy {
204 /// Source frame of the key.
205 fn at(&self) -> u32;
206 /// The ease of the segment leaving the key.
207 fn ease(&self) -> KeyEase;
208 /// The same value moved to frame `at`, leaving with `ease`.
209 fn placed(self, at: u32, ease: KeyEase) -> Self;
210 /// The value `t` of the way (already eased) from `a` to `b`.
211 fn mix(a: &Self, b: &Self, t: f32) -> Self;
212}
213
214/// The key an animation gives at source frame `src` (fractional), or `None`
215/// with no keys. Held before the first and after the last key; between two
216/// keys, interpolated with the earlier key's ease. Exact at a key. The
217/// returned key's frame and ease are the earlier key's.
218pub fn sample<K: Keyed>(keys: &[K], src: f64) -> Option<K> {
219 let first = keys.first()?;
220 let last = keys.last()?;
221 if src <= f64::from(first.at()) {
222 return Some(*first);
223 }
224 if src >= f64::from(last.at()) {
225 return Some(*last);
226 }
227 // The first key strictly after `src`; its predecessor starts the segment
228 // `src` is in, and both exist by the two holds above.
229 let i = keys.partition_point(|k| f64::from(k.at()) <= src);
230 let (a, b) = (&keys[i - 1], &keys[i]);
231 let t = ((src - f64::from(a.at())) / f64::from(b.at() - a.at())) as f32;
232 let t = ease_shape(a.ease(), t);
233 Some(K::mix(a, b, t).placed(a.at(), a.ease()))
234}
235
236impl Keyed for TransformKey {
237 fn at(&self) -> u32 {
238 self.at
239 }
240 fn ease(&self) -> KeyEase {
241 self.ease
242 }
243 fn placed(self, at: u32, ease: KeyEase) -> Self {
244 Self { at, ease, ..self }
245 }
246 fn mix(a: &Self, b: &Self, t: f32) -> Self {
247 Self {
248 params: lerp_params(&a.params, &b.params, t),
249 ..*a
250 }
251 }
252}
253
254/// One point of a clip's opacity animation ([`crate::project::Clip::opacity_keys`]):
255/// how much of the placed picture shows (`0..=1`) at source frame `at`.
256#[derive(Debug, Clone, Copy, PartialEq)]
257pub struct OpacityKey {
258 /// Source frame of the key.
259 pub at: u32,
260 /// Opacity exactly there, `0.0` (clear) to `1.0` (opaque).
261 pub opacity: f32,
262 /// The easing of the segment that leaves this key.
263 pub ease: KeyEase,
264}
265
266impl Keyed for OpacityKey {
267 fn at(&self) -> u32 {
268 self.at
269 }
270 fn ease(&self) -> KeyEase {
271 self.ease
272 }
273 fn placed(self, at: u32, ease: KeyEase) -> Self {
274 Self { at, ease, ..self }
275 }
276 fn mix(a: &Self, b: &Self, t: f32) -> Self {
277 Self {
278 opacity: a.opacity + (b.opacity - a.opacity) * t,
279 ..*a
280 }
281 }
282}
283
284/// Every field of `a` moved `t` of the way to `b`, `t` in `0..=1`.
285pub fn lerp_params(a: &TransformParams, b: &TransformParams, t: f32) -> TransformParams {
286 let l = |x: f32, y: f32| x + (y - x) * t;
287 TransformParams {
288 pos_x: l(a.pos_x, b.pos_x),
289 pos_y: l(a.pos_y, b.pos_y),
290 scale: l(a.scale, b.scale),
291 rotate: l(a.rotate, b.rotate),
292 crop_l: l(a.crop_l, b.crop_l),
293 crop_r: l(a.crop_r, b.crop_r),
294 crop_t: l(a.crop_t, b.crop_t),
295 crop_b: l(a.crop_b, b.crop_b),
296 opacity: l(a.opacity, b.opacity),
297 }
298}
299
300/// The placement the keys give at source frame `src` (fractional), or `None`
301/// with no keys. Held before the first and after the last key; between two
302/// keys, each field is interpolated with the earlier key's [`KeyEase`]. Exact
303/// at a key.
304pub fn keys_at(keys: &[TransformKey], src: f64) -> Option<TransformParams> {
305 sample(keys, src).map(|k| k.params)
306}
307
308/// [`keys_at`], or `base` when there are no keys: the one placement a clip
309/// shows at source frame `src`.
310pub fn evaluate(base: &TransformParams, keys: &[TransformKey], src: f64) -> TransformParams {
311 keys_at(keys, src).unwrap_or(*base)
312}
313
314/// The opacity the keys give at source frame `src`, or `base` with no keys.
315pub fn evaluate_opacity(base: f32, keys: &[OpacityKey], src: f64) -> f32 {
316 sample(keys, src).map_or(base, |k| k.opacity)
317}
318
319/// The keys that still shape the picture over source frames `lo..=hi`, after
320/// a trim left the clip showing only that window. Keys inside it stay where
321/// they are. A key before `lo` or after `hi` is dropped, and in its place
322/// there is a key at the window's edge holding the placement the whole
323/// animation gives there, so the visible part moves exactly as it did. An
324/// edge with nothing dropped gets no key: the animation already holds there.
325/// Empty in, empty out.
326pub fn keys_within<K: Keyed>(keys: &[K], lo: u32, hi: u32) -> Vec<K> {
327 if keys.is_empty() || lo > hi {
328 return Vec::new();
329 }
330 // The easing of the segment the edge sits in, as a split takes it (`split_transform_keys`).
331 let edge_key = |src: u32| {
332 sample(keys, f64::from(src)).expect("keyed, so a value").placed(
333 src,
334 keys.iter()
335 .rev()
336 .find(|k| k.at() <= src)
337 .map_or(KeyEase::Linear, |k| k.ease()),
338 )
339 };
340 let mut out = Vec::new();
341 if keys.iter().any(|k| k.at() < lo) && !keys.iter().any(|k| k.at() == lo) {
342 out.push(edge_key(lo));
343 }
344 out.extend(keys.iter().copied().filter(|k| (lo..=hi).contains(&k.at())));
345 if hi > lo && keys.iter().any(|k| k.at() > hi) && !keys.iter().any(|k| k.at() == hi) {
346 out.push(edge_key(hi));
347 }
348 out
349}
350
351/// The keys of a still image after its head moved. A still has no frame to
352/// walk an in-point back to, so its trim puts the in-point at frame 0 and
353/// the picture plays from there; the keys must not follow that frame, or the
354/// animation slides along the timeline. Instead each key keeps its *timeline*
355/// time: the clip started at `old_start` playing from `old_in`, and now starts
356/// at `new_start` with its in-point at 0 and its out-point at `new_out`, at
357/// `speed` source frames per timeline frame. Keys that fall before the new
358/// head or past the new tail are cut with [`keys_within`].
359pub fn keys_after_still_head<K: Keyed>(
360 keys: &[K],
361 old_start: u32,
362 old_in: u32,
363 new_start: u32,
364 new_out: u32,
365 speed: f64,
366) -> Vec<K> {
367 // Source frames to add to a key: the old timeline time of the key minus
368 // the new one, both measured from the new in-point at 0.
369 let moved = (f64::from(old_start) - f64::from(new_start)) * speed;
370 let shift = moved.round() as i64 - i64::from(old_in);
371 // The old source frames that now bound the window: `lo` is the new frame
372 // 0 and `hi` the new out-point, both shifted back into the old keys' frames.
373 let lo = (-shift).max(0);
374 let hi = (i64::from(new_out) - shift).max(lo);
375 keys_within(keys, lo as u32, hi as u32)
376 .into_iter()
377 .map(|k| k.placed((i64::from(k.at()) + shift) as u32, k.ease()))
378 .collect()
379}
380
381/// A place on the canvas a picture can be put in: the centre, or one of the
382/// four corners. [`corner_offset`] turns one into `pos_x`/`pos_y`.
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub enum Corner {
385 Centre,
386 TopLeft,
387 TopRight,
388 BottomLeft,
389 BottomRight,
390}
391
392impl Corner {
393 /// Every corner, centre first, in the order a picker lists them.
394 pub const ALL: [Corner; 5] = [
395 Corner::Centre,
396 Corner::TopLeft,
397 Corner::TopRight,
398 Corner::BottomLeft,
399 Corner::BottomRight,
400 ];
401
402 /// The sign of this corner on each axis: `(x, y)`, with `+1` right and down,
403 /// `-1` left and up, and `0` for the centre.
404 fn signs(self) -> (f64, f64) {
405 match self {
406 Corner::Centre => (0.0, 0.0),
407 Corner::TopLeft => (-1.0, -1.0),
408 Corner::TopRight => (1.0, -1.0),
409 Corner::BottomLeft => (-1.0, 1.0),
410 Corner::BottomRight => (1.0, 1.0),
411 }
412 }
413}
414
415/// The `pos_x`/`pos_y` that put a `src_w` x `src_h` picture in `corner` of a
416/// `canvas_w` x `canvas_h` canvas, at `scale`, with `margin` of air between the
417/// picture and the two edges it touches.
418///
419/// `margin` is a fraction of the canvas width, on both axes; the vertical margin
420/// is that same distance in pixels, so it is `margin * canvas_w / canvas_h` of
421/// the height. The picture is fitted inside the canvas the way the default
422/// [`crate::scale::FitPolicy::Fit`] fits it, then `scale` is applied to that box:
423/// a picture at least as wide (in aspect) as the canvas fills its width, a taller
424/// one fills its height. So the half sizes are `scale / 2` on the filled axis and
425/// the other follows the picture's aspect, and each offset is
426/// `0.5 - half size - margin`, signed by the corner.
427///
428/// A 16:9 picture on a 16:9 canvas at scale 0.3 with a 0.03 margin lands at
429/// `x = 0.32`, `y = -0.32` in the top-right corner. [`Corner::Centre`] is `(0, 0)`.
430pub fn corner_offset(
431 corner: Corner,
432 scale: f32,
433 margin: f32,
434 src: (u32, u32),
435 canvas: (u32, u32),
436) -> (f32, f32) {
437 let (half_w, half_h) = fitted_half(scale, src, canvas);
438 let (cw, ch) = (f64::from(canvas.0.max(1)), f64::from(canvas.1.max(1)));
439 let margin_x = f64::from(margin);
440 let margin_y = margin_x * cw / ch;
441 let (sx, sy) = corner.signs();
442 // `+ 0.0` turns the -0.0 a centred axis would otherwise carry into 0.
443 let x = sx * (0.5 - half_w - margin_x) + 0.0;
444 let y = sy * (0.5 - half_h - margin_y) + 0.0;
445 (x as f32, y as f32)
446}
447
448/// Half the width and height of a `src` picture at `scale` on a `canvas`, as
449/// fractions of the canvas width and height: the box the default fit gives,
450/// scaled. The shared measure of [`corner_offset`] and [`placed_half`].
451fn fitted_half(scale: f32, src: (u32, u32), canvas: (u32, u32)) -> (f64, f64) {
452 let (sw, sh) = (f64::from(src.0.max(1)), f64::from(src.1.max(1)));
453 let (cw, ch) = (f64::from(canvas.0.max(1)), f64::from(canvas.1.max(1)));
454 let half = f64::from(scale) / 2.0;
455 if sw * ch >= cw * sh {
456 (half, half * (sh / sw) * (cw / ch))
457 } else {
458 (half * (sw / sh) * (ch / cw), half)
459 }
460}
461
462/// The gap a corner placement keeps from the two canvas edges it touches, in
463/// pixels: the default the transform card and the `corner` op use.
464pub const CORNER_MARGIN_PX: f32 = 32.0;
465
466/// [`corner_offset`] for the picture a placement `t` shows: the picture is
467/// measured as it appears, after its crop and its quarter turn (`src` is its
468/// own pixel size), and `margin_px` is the gap in pixels. Only `scale` and the
469/// shape come from `t`; the position is what this returns.
470pub fn corner_placement(
471 corner: Corner,
472 t: &TransformParams,
473 src: (u32, u32),
474 canvas: (u32, u32),
475 margin_px: f32,
476) -> (f32, f32) {
477 let crop = crate::scale::crop_rect(src.0, src.1, t);
478 let turned = crate::scale::nearest_90_steps(t.rotate) % 2 == 1;
479 let shape = if turned { (crop.h, crop.w) } else { (crop.w, crop.h) };
480 corner_offset(corner, t.scale, margin_px / canvas.0.max(1) as f32, shape, canvas)
481}
482
483/// Half the width and height of the picture `t` shows, as fractions of the
484/// canvas: measured as [`corner_placement`] measures it (after the crop and
485/// the quarter turn), so a viewer outline matches what is drawn.
486pub fn placed_half(t: &TransformParams, src: (u32, u32), canvas: (u32, u32)) -> (f32, f32) {
487 let crop = crate::scale::crop_rect(src.0, src.1, t);
488 let turned = crate::scale::nearest_90_steps(t.rotate) % 2 == 1;
489 let shape = if turned { (crop.h, crop.w) } else { (crop.w, crop.h) };
490 let (hw, hh) = fitted_half(t.scale, shape, canvas);
491 (hw as f32, hh as f32)
492}
493
494/// The placement `new` should have when it changes only the scale of `old`:
495/// a picture that sat in a corner stays in that corner at its new size, so its
496/// position is recomputed. A custom position is kept as it is, and so is any
497/// placement that did not change scale.
498pub fn keep_corner(
499 old: &TransformParams,
500 new: TransformParams,
501 src: (u32, u32),
502 canvas: (u32, u32),
503 margin_px: f32,
504) -> TransformParams {
505 if new.scale == old.scale {
506 return new;
507 }
508 match corner_of(old, src, canvas, margin_px) {
509 Some(corner) => {
510 let (pos_x, pos_y) = corner_placement(corner, &new, src, canvas, margin_px);
511 TransformParams { pos_x, pos_y, ..new }
512 }
513 None => new,
514 }
515}
516
517/// The corner `t` already sits in, when its position is one [`corner_placement`]
518/// gives to within half a pixel on both axes (at its own scale, crop and turn).
519/// `None` when the position is custom.
520pub fn corner_of(t: &TransformParams, src: (u32, u32), canvas: (u32, u32), margin_px: f32) -> Option<Corner> {
521 let (cw, ch) = (canvas.0.max(1) as f32, canvas.1.max(1) as f32);
522 Corner::ALL.into_iter().find(|&c| {
523 let (x, y) = corner_placement(c, t, src, canvas, margin_px);
524 (t.pos_x - x).abs() * cw <= 0.5 && (t.pos_y - y).abs() * ch <= 0.5
525 })
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531
532 #[test]
533 fn default_is_identity() {
534 assert!(TransformParams::default().is_identity());
535 assert!(!TransformParams {
536 pos_x: 0.001,
537 ..TransformParams::default()
538 }
539 .is_identity());
540 }
541
542 #[test]
543 fn keys_interpolate_linearly_and_hold_outside() {
544 let at = |frame, scale| TransformKey {
545 at: frame,
546 params: TransformParams {
547 scale,
548 ..TransformParams::default()
549 },
550 ease: KeyEase::Linear,
551 };
552 let keys = [at(0, 1.0), at(100, 1.2)];
553 let mid = keys_at(&keys, 50.0).expect("keyed");
554 assert!((mid.scale - 1.1).abs() < 1e-6, "midpoint of 1.0 and 1.2");
555 assert_eq!(keys_at(&keys, 0.0).unwrap().scale, 1.0, "exact at a key");
556 assert_eq!(keys_at(&keys, 100.0).unwrap().scale, 1.2, "exact at the last");
557 assert_eq!(keys_at(&keys, -5.0).unwrap().scale, 1.0, "held before");
558 assert_eq!(keys_at(&keys, 999.0).unwrap().scale, 1.2, "held after");
559 assert!(keys_at(&[], 3.0).is_none(), "no keys is no placement");
560 assert!(evaluate(&TransformParams::default(), &[], 3.0).is_identity());
561 }
562
563 fn scaled(scale: f32) -> TransformParams {
564 TransformParams {
565 scale,
566 ..TransformParams::default()
567 }
568 }
569
570 fn scaled_key(at: u32, scale: f32, ease: KeyEase) -> TransformKey {
571 TransformKey {
572 at,
573 params: scaled(scale),
574 ease,
575 }
576 }
577
578 #[test]
579 fn a_window_keeps_inside_keys_and_edges_hold_the_interpolated_value() {
580 let keys = [
581 scaled_key(0, 1.0, KeyEase::Linear),
582 scaled_key(100, 2.0, KeyEase::Linear),
583 scaled_key(200, 1.0, KeyEase::Linear),
584 ];
585 // Window 50..=150: the key at 100 stays, and the edges get the value
586 // the animation has there (1.5 at 50, 1.5 at 150).
587 let w = keys_within(&keys, 50, 150);
588 let at: Vec<u32> = w.iter().map(|k| k.at).collect();
589 assert_eq!(at, vec![50, 100, 150]);
590 assert!((w[0].params.scale - 1.5).abs() < 1e-6);
591 assert_eq!(w[1].params.scale, 2.0, "the inside key is untouched");
592 assert!((w[2].params.scale - 1.5).abs() < 1e-6);
593 // The animation still reads the same values over the window.
594 for f in 50..=150 {
595 let before = keys_at(&keys, f64::from(f)).unwrap().scale;
596 let after = keys_at(&w, f64::from(f)).unwrap().scale;
597 assert!((before - after).abs() < 1e-6, "frame {f}");
598 }
599 }
600
601 #[test]
602 fn a_window_with_no_key_before_or_after_gets_no_edge_key() {
603 let keys = [scaled_key(100, 2.0, KeyEase::Linear), scaled_key(200, 1.0, KeyEase::Linear)];
604 // Nothing before 100: the head needs no key, the animation holds there.
605 let w = keys_within(&keys, 80, 300);
606 assert_eq!(w, keys.to_vec());
607 // A window that drops the last key adds one at its edge.
608 let w = keys_within(&keys, 0, 150);
609 assert_eq!(w.iter().map(|k| k.at).collect::<Vec<_>>(), vec![100, 150]);
610 }
611
612 #[test]
613 fn a_window_past_every_key_keeps_one_holding_key() {
614 let keys = [scaled_key(10, 1.5, KeyEase::Linear), scaled_key(20, 3.0, KeyEase::Linear)];
615 // Every key is before the window: the animation is held at 3.0 there,
616 // so one key at the window's start says so, and the clip stays keyed.
617 let w = keys_within(&keys, 50, 60);
618 assert_eq!(w.len(), 1);
619 assert_eq!(w[0].at, 50);
620 assert_eq!(w[0].params.scale, 3.0);
621 assert!(keys_within::<TransformKey>(&[], 0, 10).is_empty());
622 }
623
624 #[test]
625 fn a_still_keeps_its_keys_on_the_timeline_when_its_head_moves() {
626 // A still at 30 fps placed at timeline 1 s (frame 30), with keys at
627 // timeline 1 s, 5 s and 9 s (source 0, 120, 240). Trim the head to 2 s
628 // (frame 60): the keys at 5 s and 9 s must stay there, and the key at
629 // 1 s is replaced by one at 2 s holding the value it had there.
630 let keys = [
631 scaled_key(0, 0.3, KeyEase::Linear),
632 scaled_key(120, 0.6, KeyEase::Linear),
633 scaled_key(240, 1.0, KeyEase::Linear),
634 ];
635 let w = keys_after_still_head(&keys, 30, 0, 60, 210, 1.0);
636 let timeline = |k: &TransformKey| 60 + k.at;
637 assert_eq!(timeline(&w[0]), 60, "the boundary at the new head");
638 let at_5s: Vec<u32> = w.iter().map(|k| k.at).collect();
639 assert_eq!(at_5s, vec![0, 90, 210], "frames 90 and 210 are timeline 5 s and 9 s");
640 // The picture at each timeline frame of the visible part is unchanged.
641 for t in 60..=270u32 {
642 let before = keys_at(&keys, f64::from(t - 30)).unwrap().scale;
643 let after = keys_at(&w, f64::from(t - 60)).unwrap().scale;
644 assert!((before - after).abs() < 1e-6, "timeline frame {t}");
645 }
646 }
647
648 #[test]
649 fn a_still_trimmed_to_grow_its_head_keeps_its_keys_too() {
650 let keys = [scaled_key(0, 1.0, KeyEase::Linear), scaled_key(60, 2.0, KeyEase::Linear)];
651 // Head moved earlier by 10 frames (start 30 -> 20): keys move later.
652 let w = keys_after_still_head(&keys, 30, 0, 20, 100, 1.0);
653 assert_eq!(w.iter().map(|k| k.at).collect::<Vec<_>>(), vec![10, 70]);
654 assert_eq!(w[0].params.scale, 1.0, "the first key is still the first");
655 }
656
657 #[test]
658 fn ease_slows_the_segment_ends_and_leaves_the_midpoint() {
659 let mut keys = [
660 TransformKey {
661 at: 0,
662 params: TransformParams::default(),
663 ease: KeyEase::Ease,
664 },
665 TransformKey {
666 at: 100,
667 params: TransformParams {
668 pos_x: 0.4,
669 ..TransformParams::default()
670 },
671 ease: KeyEase::Linear,
672 },
673 ];
674 let mid = keys_at(&keys, 50.0).unwrap().pos_x;
675 assert!((mid - 0.2).abs() < 1e-6, "smoothstep is symmetric about 0.5");
676 let quarter = keys_at(&keys, 25.0).unwrap().pos_x;
677 assert!(quarter < 0.1, "an eased segment starts slower than linear");
678 keys[0].ease = KeyEase::Linear;
679 assert!((keys_at(&keys, 25.0).unwrap().pos_x - 0.1).abs() < 1e-6);
680 }
681
682 #[test]
683 fn every_ease_is_zero_at_the_start_and_one_at_the_end_except_hold() {
684 for e in [KeyEase::Linear, KeyEase::Ease, KeyEase::EaseIn, KeyEase::EaseOut] {
685 assert_eq!(ease_shape(e, 0.0), 0.0, "{e:?} start");
686 assert_eq!(ease_shape(e, 1.0), 1.0, "{e:?} end");
687 }
688 assert_eq!(ease_shape(KeyEase::Hold, 0.0), 0.0);
689 assert_eq!(ease_shape(KeyEase::Hold, 0.999), 0.0, "hold stays until the segment is done");
690 assert_eq!(ease_shape(KeyEase::Hold, 1.0), 1.0);
691 }
692
693 #[test]
694 fn the_ease_shapes_have_their_documented_curves() {
695 // Exact at the quarter and the half.
696 assert_eq!(ease_shape(KeyEase::Linear, 0.25), 0.25);
697 assert!((ease_shape(KeyEase::EaseIn, 0.25) - 0.015625).abs() < 1e-7);
698 assert!((ease_shape(KeyEase::EaseIn, 0.5) - 0.125).abs() < 1e-7);
699 assert!((ease_shape(KeyEase::EaseOut, 0.25) - 0.578125).abs() < 1e-7);
700 assert!((ease_shape(KeyEase::EaseOut, 0.5) - 0.875).abs() < 1e-7);
701 assert!((ease_shape(KeyEase::Ease, 0.25) - 0.15625).abs() < 1e-7, "smoothstep");
702 assert!((ease_shape(KeyEase::Ease, 0.5) - 0.5).abs() < 1e-7, "in-out is symmetric");
703 // In-out is symmetric about the middle; in and out mirror each other.
704 for i in 1..10 {
705 let t = i as f32 / 10.0;
706 assert!((ease_shape(KeyEase::Ease, t) + ease_shape(KeyEase::Ease, 1.0 - t) - 1.0).abs() < 1e-6);
707 assert!((ease_shape(KeyEase::EaseIn, t) + ease_shape(KeyEase::EaseOut, 1.0 - t) - 1.0).abs() < 1e-6);
708 }
709 }
710
711 #[test]
712 fn names_and_tokens_round_trip_and_cycle() {
713 for e in KeyEase::ALL {
714 assert_eq!(KeyEase::from_name(e.name()), Some(e));
715 assert_eq!(KeyEase::from_token(e.token().as_bytes()), Some(e));
716 }
717 assert_eq!(KeyEase::from_name("ease"), Some(KeyEase::Ease), "the older spelling");
718 assert_eq!(KeyEase::from_name("bounce"), None);
719 let mut e = KeyEase::Linear;
720 for _ in 0..KeyEase::ALL.len() {
721 e = e.next();
722 }
723 assert_eq!(e, KeyEase::Linear, "a full cycle comes back");
724 }
725
726 #[test]
727 fn opacity_keys_use_the_same_interpolation_with_every_ease() {
728 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
729 let mid = |ease| evaluate_opacity(1.0, &[ok(0, 0.0, ease), ok(100, 1.0, ease)], 25.0);
730 assert!((mid(KeyEase::Linear) - 0.25).abs() < 1e-6);
731 assert!((mid(KeyEase::EaseIn) - 0.015625).abs() < 1e-6);
732 assert!((mid(KeyEase::EaseOut) - 0.578125).abs() < 1e-6);
733 assert!((mid(KeyEase::Ease) - 0.15625).abs() < 1e-6);
734 assert_eq!(mid(KeyEase::Hold), 0.0, "hold keeps the first key's value");
735 let keys = [ok(0, 0.2, KeyEase::Hold), ok(100, 0.9, KeyEase::Linear)];
736 assert_eq!(evaluate_opacity(1.0, &keys, 100.0), 0.9, "the next key is exact");
737 assert_eq!(evaluate_opacity(1.0, &keys, 150.0), 0.9, "held after");
738 assert_eq!(evaluate_opacity(1.0, &keys, -3.0), 0.2, "held before");
739 assert_eq!(evaluate_opacity(0.7, &[], 5.0), 0.7, "no keys is the base");
740 }
741
742 #[test]
743 fn eased_keys_split_and_trim_through_the_shared_helpers() {
744 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
745 let keys = [ok(0, 0.0, KeyEase::EaseIn), ok(100, 1.0, KeyEase::Linear)];
746 let within = keys_within(&keys, 20, 80);
747 assert_eq!(within.iter().map(|k| k.at).collect::<Vec<_>>(), vec![20, 80]);
748 assert_eq!(within[0].ease, KeyEase::EaseIn, "an edge key keeps the segment's ease");
749 let want = evaluate_opacity(1.0, &keys, 20.0);
750 assert!((within[0].opacity - want).abs() < 1e-7);
751 }
752
753 #[test]
754 fn corner_offset_matches_the_documented_examples() {
755 // 16:9 on 16:9 at scale 0.3: half-width 0.15, half-height 0.15. The 0.03
756 // margin is 0.03 of the width on x, and the same distance in pixels down
757 // the height, 0.03 * 16 / 9 of it, so y is -(0.5 - 0.15 - 0.0533).
758 let (x, y) = corner_offset(Corner::TopRight, 0.3, 0.03, (1920, 1080), (1920, 1080));
759 assert!((x - 0.32).abs() < 1e-5, "{x}");
760 assert!((y + (0.5 - 0.15 - 0.03 * 16.0 / 9.0) as f32).abs() < 1e-5, "{y}");
761 let (x, y) = corner_offset(Corner::BottomLeft, 0.3, 0.03, (1920, 1080), (1920, 1080));
762 assert!((x + 0.32).abs() < 1e-5, "{x}");
763 assert!((y - (0.5 - 0.15 - 0.03 * 16.0 / 9.0) as f32).abs() < 1e-5, "{y}");
764 // A square logo at 0.2 on 1080x1920 with a 32 px margin (0.0296 of the width):
765 // x 0.37, y -0.427, as the MCP help states them.
766 let margin = 32.0 / 1080.0;
767 let (x, y) = corner_offset(Corner::TopRight, 0.2, margin, (1, 1), (1080, 1920));
768 assert!((x - 0.37).abs() < 5e-4, "{x}");
769 assert!((y + 0.427).abs() < 5e-4, "{y}");
770 }
771
772 #[test]
773 fn corner_offset_signs_and_centre() {
774 let m = 0.03;
775 assert_eq!(corner_offset(Corner::Centre, 0.3, m, (16, 9), (16, 9)), (0.0, 0.0));
776 let (x, y) = corner_offset(Corner::TopLeft, 0.3, m, (16, 9), (16, 9));
777 assert!(x < 0.0 && y < 0.0);
778 let (x, y) = corner_offset(Corner::BottomRight, 0.3, m, (16, 9), (16, 9));
779 assert!(x > 0.0 && y > 0.0);
780 // The same picture, mirrored, lands on the mirror image.
781 let (x, y) = corner_offset(Corner::BottomRight, 0.3, m, (16, 9), (16, 9));
782 let (mx, my) = corner_offset(Corner::TopLeft, 0.3, m, (16, 9), (16, 9));
783 assert_eq!((x, y), (-mx, -my));
784 }
785
786 #[test]
787 fn corner_offset_fits_a_taller_picture_by_its_height() {
788 // A 9:16 picture on a 16:9 canvas fills the height at scale 1, so its
789 // half-width is 0.5 * (9/16) * (9/16) and its half-height 0.5.
790 let (x, y) = corner_offset(Corner::TopRight, 1.0, 0.0, (9, 16), (16, 9));
791 let half_w = 0.5 * (9.0_f32 / 16.0) * (9.0 / 16.0);
792 assert!((x - (0.5 - half_w)).abs() < 1e-5, "{x}");
793 assert!((y + 0.0).abs() < 1e-5, "{y}");
794 }
795
796 #[test]
797 fn corner_placement_measures_the_picture_as_shown() {
798 // A 16:9 picture turned a quarter is 9:16 on screen, so its shape flips.
799 let turned = TransformParams { rotate: 90.0, scale: 1.0, ..Default::default() };
800 let plain = TransformParams { scale: 1.0, ..Default::default() };
801 let canvas = (1080, 1920);
802 let (x1, _) = corner_placement(Corner::TopRight, &turned, (1920, 1080), canvas, 0.0);
803 let (x2, _) = corner_placement(Corner::TopRight, &plain, (1080, 1920), canvas, 0.0);
804 assert!((x1 - x2).abs() < 1e-5, "a turned 16:9 is the same shape as a 9:16: {x1} {x2}");
805 // The cropped picture is what is measured, not the whole source.
806 let cropped = TransformParams { crop_l: 0.25, crop_r: 0.25, scale: 1.0, ..Default::default() };
807 let (cx, _) = corner_placement(Corner::TopRight, &cropped, (1000, 1000), (1000, 1000), 0.0);
808 assert!((cx - 0.25).abs() < 1e-4, "a half-width crop of a square fills half the width: {cx}");
809 }
810
811 #[test]
812 fn corner_of_names_only_the_placed_corner() {
813 let t = TransformParams { scale: 0.3, ..Default::default() };
814 let src = (1920, 1080);
815 let canvas = (1920, 1080);
816 assert_eq!(corner_of(&t, src, canvas, 32.0), Some(Corner::Centre), "the origin is the centre choice");
817 let (x, y) = corner_placement(Corner::BottomRight, &t, src, canvas, 32.0);
818 let placed = TransformParams { pos_x: x, pos_y: y, ..t };
819 assert_eq!(corner_of(&placed, src, canvas, 32.0), Some(Corner::BottomRight));
820 // A nudge of ten pixels is a custom position.
821 let moved = TransformParams { pos_x: x - 10.0 / 1920.0, ..placed };
822 assert_eq!(corner_of(&moved, src, canvas, 32.0), None);
823 // A different margin is a different place, too.
824 assert_eq!(corner_of(&placed, src, canvas, 16.0), None);
825 }
826
827 #[test]
828 fn corner_offset_fits_a_4_3_source_on_a_16_9_canvas_by_height() {
829 // A 4:3 picture is 0.75 as wide as the canvas's height in pixels: at
830 // scale 0.3 on 1280x720 it is 288 px wide and 216 px tall, so it fills
831 // the height (half-height 0.15) and its half-width is 0.1125 of the width.
832 // A 32 px margin then puts the centre at x = 1280/2 - 144 - 32 = 464 px and
833 // y = 720/2 - 108 - 32 = 220 px, which is 0.3625 and 0.3056 of the canvas.
834 let (x, y) = corner_offset(Corner::BottomRight, 0.3, 32.0 / 1280.0, (640, 480), (1280, 720));
835 assert!((x * 1280.0 - 464.0).abs() < 0.5, "x {x} is {} px, want 464", x * 1280.0);
836 assert!((y * 720.0 - 220.0).abs() < 0.5, "y {y} is {} px, want 220", y * 720.0);
837 // Its right and bottom gaps are both the 32 px margin.
838 let right = (0.5 - f64::from(x)) * 1280.0 - 144.0;
839 let bottom = (0.5 - f64::from(y)) * 720.0 - 108.0;
840 assert!((right - 32.0).abs() < 0.5 && (bottom - 32.0).abs() < 0.5, "gaps {right} {bottom}");
841 }
842
843 #[test]
844 fn corner_offset_margin_is_a_width_fraction_on_both_axes() {
845 // The same pixel margin on a 1000x500 canvas is 0.02 across and 0.04 down.
846 let (x, y) = corner_offset(Corner::BottomRight, 0.0, 0.02, (1, 1), (1000, 500));
847 assert!((x - 0.48).abs() < 1e-5, "{x}");
848 assert!((y - 0.46).abs() < 1e-5, "{y}");
849 }
850
851 #[test]
852 fn keep_corner_holds_the_corner_when_the_scale_changes() {
853 let src = (1920, 1080);
854 let canvas = (1920, 1080);
855 let margin = CORNER_MARGIN_PX;
856 let at_full = TransformParams {
857 scale: 1.0,
858 ..TransformParams::default()
859 };
860 let (x, y) = corner_placement(Corner::BottomRight, &at_full, src, canvas, margin);
861 let placed = TransformParams { pos_x: x, pos_y: y, ..at_full };
862 assert_eq!(corner_of(&placed, src, canvas, margin), Some(Corner::BottomRight));
863 let smaller = TransformParams { scale: 0.35, ..placed };
864 let kept = keep_corner(&placed, smaller, src, canvas, margin);
865 assert_eq!(corner_of(&kept, src, canvas, margin), Some(Corner::BottomRight));
866 assert!(kept.pos_x > 0.0 && kept.pos_y > 0.0, "still bottom right, not bottom centre");
867 // A custom position is left alone.
868 let moved = TransformParams { pos_x: 0.1, ..placed };
869 assert_eq!(keep_corner(&moved, smaller, src, canvas, margin), smaller);
870 // A scale change with no move keeps everything else.
871 let same = keep_corner(&placed, placed, src, canvas, margin);
872 assert_eq!(same, placed);
873 }
874
875 #[test]
876 fn placed_half_is_the_box_corner_placement_fits() {
877 let canvas = (1920, 1080);
878 let t = TransformParams { scale: 0.3, ..TransformParams::default() };
879 let (hw, hh) = placed_half(&t, (1920, 1080), canvas);
880 assert!((hw - 0.15).abs() < 1e-6 && (hh - 0.15).abs() < 1e-6, "{hw} {hh}");
881 let (cx, cy) = corner_placement(Corner::TopRight, &t, (1920, 1080), canvas, 0.0);
882 assert!((cx - (0.5 - hw)).abs() < 1e-6 && (cy + (0.5 - hh)).abs() < 1e-6);
883 }
884}