forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBba1e370Tahinli21 days ago1036 commits

transform.rs1151 lines, 47.5 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
11use std::borrow::Cow;
12
13/// One clip's placement on the project canvas, on top of whatever
14/// [`crate::scale::FitPolicy`] already does.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct TransformParams {
17 /// Canvas-fraction offset from centred, positive right. `0.0` is
18 /// identity.
19 pub pos_x: f32,
20 /// Canvas-fraction offset from centred, positive down. `0.0` is identity.
21 pub pos_y: f32,
22 /// Multiplier on the fit-policy placement size. `1.0` is identity.
23 pub scale: f32,
24 /// Degrees, clockwise. Rendered at the nearest 90-degree step
25 /// ([`crate::scale::rotate_i420_90s`]); the value itself is kept exactly,
26 /// so a UI that later grows continuous rotation loses nothing already
27 /// saved. `0.0` is identity.
28 pub rotate: f32,
29 /// Fraction of the source cropped off the left, `0.0..0.5`.
30 pub crop_l: f32,
31 /// Fraction of the source cropped off the right, `0.0..0.5`.
32 pub crop_r: f32,
33 /// Fraction of the source cropped off the top, `0.0..0.5`.
34 pub crop_t: f32,
35 /// Fraction of the source cropped off the bottom, `0.0..0.5`.
36 pub crop_b: f32,
37 /// How much of the placed picture shows over what is beneath it, `0.0..=1.0`:
38 /// `1.0` is opaque and the identity. A layer is blended over the layers
39 /// below by this fraction of its own coverage; a single clip is faded toward
40 /// the black canvas it sits on. The blend is on the stored Y'CbCr code values,
41 /// exactly as a dissolve blends them: gamma-encoded video code values, not
42 /// linear light. So 50% white over black is the midpoint of the two codes
43 /// (limited range: luma 16 and 235 give 126), which the eye reads as mid grey.
44 pub opacity: f32,
45}
46
47impl Default for TransformParams {
48 fn default() -> Self {
49 Self {
50 pos_x: 0.0,
51 pos_y: 0.0,
52 scale: 1.0,
53 rotate: 0.0,
54 crop_l: 0.0,
55 crop_r: 0.0,
56 crop_t: 0.0,
57 crop_b: 0.0,
58 opacity: 1.0,
59 }
60 }
61}
62
63impl TransformParams {
64 /// Whether this is the do-nothing setting. Compared exactly, for
65 /// [`crate::color::ColorParams::is_identity`]'s reason: only a value that
66 /// is precisely identity is allowed to skip the geometry.
67 pub fn is_identity(&self) -> bool {
68 self.pos_x == 0.0
69 && self.pos_y == 0.0
70 && self.scale == 1.0
71 && self.rotate == 0.0
72 && self.crop_l == 0.0
73 && self.crop_r == 0.0
74 && self.crop_t == 0.0
75 && self.crop_b == 0.0
76 && self.opacity == 1.0
77 }
78}
79
80/// The most keys a clip's transform animation may hold
81/// ([`crate::project::Clip::transform_keys`]).
82pub const MAX_TRANSFORM_KEYS: usize = 256;
83
84/// How a key eases into the segment after it: `Linear` moves at a constant
85/// rate, `Ease` (ease in-out) starts and stops gently (smoothstep), `EaseIn`
86/// starts slowly and ends at speed (cubic), `EaseOut` starts at speed and
87/// lands gently (cubic), and `Hold` keeps the key's value until the next key
88/// and then jumps (a step). The last key has no segment after it, so its own
89/// ease is never read. `Bezier` is a custom CSS-style cubic curve
90/// ([`Bezier`]). One shape for every key type ([`ease_shape`]).
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
92pub enum KeyEase {
93 #[default]
94 Linear,
95 Ease,
96 EaseIn,
97 EaseOut,
98 Hold,
99 /// A custom cubic curve from `(0, 0)` to `(1, 1)`.
100 Bezier(Bezier),
101}
102
103/// A CSS-style cubic bezier easing curve from `(0, 0)` to `(1, 1)` through
104/// two control points. Each coordinate is stored in thousandths, so the type
105/// stays `Eq` and `Hash`. Every coordinate lies in `0..=1`, which keeps the
106/// curve from overshooting: every interpolated value stays inside the range
107/// of its two keys.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub struct Bezier {
110 x1: u16,
111 y1: u16,
112 x2: u16,
113 y2: u16,
114}
115
116impl Bezier {
117 /// A curve through the control points `(x1, y1)` and `(x2, y2)`, rounded
118 /// to thousandths. `None` unless every coordinate is finite and within `0..=1`.
119 pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Option<Bezier> {
120 let q = |v: f32| -> Option<u16> {
121 if v.is_finite() && (0.0..=1.0).contains(&v) {
122 Some((v * 1000.0).round() as u16)
123 } else {
124 None
125 }
126 };
127 Some(Bezier {
128 x1: q(x1)?,
129 y1: q(y1)?,
130 x2: q(x2)?,
131 y2: q(y2)?,
132 })
133 }
134
135 /// The control coordinates `[x1, y1, x2, y2]` as fractions in `0..=1`.
136 pub fn points(self) -> [f32; 4] {
137 [self.x1, self.y1, self.x2, self.y2].map(|v| f32::from(v) / 1000.0)
138 }
139
140 /// A curve from thousandths counts, as a token holds them. `None` if any count is above 1000.
141 fn from_thousandths(x1: u16, y1: u16, x2: u16, y2: u16) -> Option<Bezier> {
142 let ok = [x1, y1, x2, y2].iter().all(|v| *v <= 1000);
143 ok.then_some(Bezier { x1, y1, x2, y2 })
144 }
145}
146
147/// A thousandths count written as a short decimal: `420` is `0.42`, `1000` is `1`.
148fn thousandths_text(v: u16) -> String {
149 let (whole, frac) = (v / 1000, v % 1000);
150 if frac == 0 {
151 whole.to_string()
152 } else {
153 format!("{whole}.{}", format!("{frac:03}").trim_end_matches('0'))
154 }
155}
156
157/// Reads `bezier(x1,y1,x2,y2)`, spaces allowed, back into a curve.
158fn bezier_from_name(name: &str) -> Option<Bezier> {
159 let inner = name.trim().strip_prefix("bezier(")?.strip_suffix(')')?;
160 let values: Option<Vec<f32>> = inner.split(',').map(|s| s.trim().parse::<f32>().ok()).collect();
161 match values?.as_slice() {
162 &[x1, y1, x2, y2] => Bezier::new(x1, y1, x2, y2),
163 _ => None,
164 }
165}
166
167/// Reads `b<x1>_<y1>_<x2>_<y2>` in thousandths back into a curve.
168fn bezier_from_token(token: &[u8]) -> Option<Bezier> {
169 let rest = token.strip_prefix(b"b")?;
170 let mut parts = rest.split(|b| *b == b'_').map(|p| {
171 std::str::from_utf8(p).ok()?.parse::<u16>().ok()
172 });
173 let (x1, y1, x2, y2) = (parts.next()??, parts.next()??, parts.next()??, parts.next()??);
174 if parts.next().is_some() {
175 return None;
176 }
177 Bezier::from_thousandths(x1, y1, x2, y2)
178}
179
180impl KeyEase {
181 /// Every preset ease, in the order a picker lists them. A custom
182 /// [`Bezier`](KeyEase::Bezier) is not one of them.
183 pub const ALL: [KeyEase; 5] = [
184 KeyEase::Linear,
185 KeyEase::EaseIn,
186 KeyEase::EaseOut,
187 KeyEase::Ease,
188 KeyEase::Hold,
189 ];
190
191 /// The name the tools and the GUI use: `linear`, `ease_in`, `ease_out`,
192 /// `ease_in_out`, `hold`, or `bezier(x1,y1,x2,y2)` for a custom curve.
193 pub fn name(self) -> Cow<'static, str> {
194 match self {
195 KeyEase::Linear => Cow::Borrowed("linear"),
196 KeyEase::EaseIn => Cow::Borrowed("ease_in"),
197 KeyEase::EaseOut => Cow::Borrowed("ease_out"),
198 KeyEase::Ease => Cow::Borrowed("ease_in_out"),
199 KeyEase::Hold => Cow::Borrowed("hold"),
200 KeyEase::Bezier(b) => {
201 let [x1, y1, x2, y2] = [b.x1, b.y1, b.x2, b.y2].map(thousandths_text);
202 Cow::Owned(format!("bezier({x1},{y1},{x2},{y2})"))
203 }
204 }
205 }
206
207 /// [`name`](Self::name) read back. `ease` is the older spelling of `ease_in_out`.
208 pub fn from_name(name: &str) -> Option<KeyEase> {
209 Some(match name {
210 "linear" => KeyEase::Linear,
211 "ease_in" => KeyEase::EaseIn,
212 "ease_out" => KeyEase::EaseOut,
213 "ease_in_out" | "ease" => KeyEase::Ease,
214 "hold" => KeyEase::Hold,
215 _ => return bezier_from_name(name).map(KeyEase::Bezier),
216 })
217 }
218
219 /// The token a project file writes (`lin`, `in`, `out`, `ease`, `hold`), or
220 /// `b<x1>_<y1>_<x2>_<y2>` in thousandths for a custom curve.
221 pub fn token(self) -> Cow<'static, str> {
222 match self {
223 KeyEase::Linear => Cow::Borrowed("lin"),
224 KeyEase::EaseIn => Cow::Borrowed("in"),
225 KeyEase::EaseOut => Cow::Borrowed("out"),
226 KeyEase::Ease => Cow::Borrowed("ease"),
227 KeyEase::Hold => Cow::Borrowed("hold"),
228 KeyEase::Bezier(b) => Cow::Owned(format!("b{}_{}_{}_{}", b.x1, b.y1, b.x2, b.y2)),
229 }
230 }
231
232 /// [`token`](Self::token) read back.
233 pub fn from_token(token: &[u8]) -> Option<KeyEase> {
234 Some(match token {
235 b"lin" => KeyEase::Linear,
236 b"in" => KeyEase::EaseIn,
237 b"out" => KeyEase::EaseOut,
238 b"ease" => KeyEase::Ease,
239 b"hold" => KeyEase::Hold,
240 _ => return bezier_from_token(token).map(KeyEase::Bezier),
241 })
242 }
243
244 /// The next preset in [`ALL`](Self::ALL), wrapping: what a "cycle the easing"
245 /// button does. A custom curve goes to `Linear`, the first preset.
246 pub fn next(self) -> KeyEase {
247 let Some(i) = Self::ALL.iter().position(|e| *e == self) else {
248 return KeyEase::Linear;
249 };
250 Self::ALL[(i + 1) % Self::ALL.len()]
251 }
252}
253
254/// How far along its segment a value is, once `ease` has shaped the plain
255/// fraction `t` (`0..=1`) of the way between two keys. `0` at `t == 0` and `1`
256/// at `t == 1` for every ease but `Hold`, which stays `0` until the segment is
257/// done. The one function every key type's interpolation goes through.
258pub fn ease_shape(ease: KeyEase, t: f32) -> f32 {
259 match ease {
260 KeyEase::Linear => t,
261 KeyEase::Ease => t * t * (3.0 - 2.0 * t),
262 KeyEase::EaseIn => t * t * t,
263 KeyEase::EaseOut => {
264 let u = 1.0 - t;
265 1.0 - u * u * u
266 }
267 KeyEase::Hold => {
268 if t >= 1.0 {
269 1.0
270 } else {
271 0.0
272 }
273 }
274 KeyEase::Bezier(b) => bezier_height(b, t),
275 }
276}
277
278/// One coordinate of the cubic from `0` to `1` whose inner control points are
279/// `p1` and `p2`, at curve parameter `s`.
280fn cubic_coord(p1: f32, p2: f32, s: f32) -> f32 {
281 let u = 1.0 - s;
282 3.0 * u * u * s * p1 + 3.0 * u * s * s * p2 + s * s * s
283}
284
285/// The slope of [`cubic_coord`] with respect to `s`.
286fn cubic_slope(p1: f32, p2: f32, s: f32) -> f32 {
287 let u = 1.0 - s;
288 3.0 * u * u * p1 + 6.0 * u * s * (p2 - p1) + 3.0 * s * s * (1.0 - p2)
289}
290
291/// The curve parameter `s` at which a cubic with horizontal inner controls
292/// `x1` and `x2` is at horizontal position `t` (`0` at `t <= 0`, `1` at
293/// `t >= 1`). A few Newton steps find it, with bisection as the fallback when
294/// the slope is too flat for Newton.
295fn curve_param(x1: f32, x2: f32, t: f32) -> f32 {
296 if t <= 0.0 {
297 return 0.0;
298 }
299 if t >= 1.0 {
300 return 1.0;
301 }
302 let mut s = t;
303 let mut found = false;
304 for _ in 0..8 {
305 let err = cubic_coord(x1, x2, s) - t;
306 if err.abs() < 1e-6 {
307 found = true;
308 break;
309 }
310 let d = cubic_slope(x1, x2, s);
311 if d.abs() < 1e-6 {
312 break;
313 }
314 s = (s - err / d).clamp(0.0, 1.0);
315 }
316 if !found {
317 let (mut lo, mut hi) = (0.0f32, 1.0f32);
318 for _ in 0..32 {
319 s = 0.5 * (lo + hi);
320 if cubic_coord(x1, x2, s) < t {
321 lo = s;
322 } else {
323 hi = s;
324 }
325 }
326 }
327 s
328}
329
330/// The height of a custom curve where its horizontal position is `t`.
331fn bezier_height(b: Bezier, t: f32) -> f32 {
332 if t <= 0.0 {
333 return 0.0;
334 }
335 if t >= 1.0 {
336 return 1.0;
337 }
338 let [x1, y1, x2, y2] = b.points();
339 cubic_coord(y1, y2, curve_param(x1, x2, t))
340}
341
342/// The eases of the two halves of a segment eased by `ease` when it is cut
343/// at fraction `t` of its way. The left half runs from the segment's start to
344/// the cut and the right half from the cut to its end, and each half moves
345/// exactly as the whole segment did over its own frames. Linear and hold are
346/// their own halves. Any other ease is split as the cubic bezier it is: de
347/// Casteljau at the parameter where its horizontal position is `t`, then each
348/// half normalised back to the unit square. Control points are rounded to
349/// thousandths by [`Bezier::new`], so each half matches the original to about
350/// `1e-3` of the segment's span. A half whose value does not change takes
351/// [`KeyEase::Linear`], since every ease moves it the same way. A `t` at or
352/// beyond an end leaves that empty half [`KeyEase::Linear`] too.
353pub fn split_ease(ease: KeyEase, t: f32) -> (KeyEase, KeyEase) {
354 let [x1, y1, x2, y2] = match ease {
355 KeyEase::Linear | KeyEase::Hold => return (ease, ease),
356 KeyEase::Ease => [1.0 / 3.0, 0.0, 2.0 / 3.0, 1.0],
357 KeyEase::EaseIn => [1.0 / 3.0, 0.0, 2.0 / 3.0, 0.0],
358 KeyEase::EaseOut => [1.0 / 3.0, 1.0, 2.0 / 3.0, 1.0],
359 KeyEase::Bezier(b) => b.points(),
360 };
361 if t <= 0.0 {
362 return (KeyEase::Linear, ease);
363 }
364 if t >= 1.0 {
365 return (ease, KeyEase::Linear);
366 }
367 // A point of the segment, de Casteljau style, between `a` and `b` at `u`.
368 let mix = |a: (f32, f32), b: (f32, f32), u: f32| (a.0 + (b.0 - a.0) * u, a.1 + (b.1 - a.1) * u);
369 let s = curve_param(x1, x2, t);
370 let q0 = mix((0.0, 0.0), (x1, y1), s);
371 let q1 = mix((x1, y1), (x2, y2), s);
372 let q2 = mix((x2, y2), (1.0, 1.0), s);
373 let r0 = mix(q0, q1, s);
374 let r1 = mix(q1, q2, s);
375 let yt = mix(r0, r1, s).1;
376 const FLAT: f32 = 1e-6;
377 let left = if yt <= FLAT {
378 KeyEase::Linear
379 } else {
380 let c = |p: (f32, f32)| (p.0 / t, p.1 / yt);
381 let (c1, c2) = (c(q0), c(r0));
382 Bezier::new(c1.0.clamp(0.0, 1.0), c1.1.clamp(0.0, 1.0), c2.0.clamp(0.0, 1.0), c2.1.clamp(0.0, 1.0))
383 .map_or(KeyEase::Linear, KeyEase::Bezier)
384 };
385 let right = if 1.0 - yt <= FLAT {
386 KeyEase::Linear
387 } else {
388 let c = |p: (f32, f32)| ((p.0 - t) / (1.0 - t), (p.1 - yt) / (1.0 - yt));
389 let (c1, c2) = (c(r1), c(q2));
390 Bezier::new(c1.0.clamp(0.0, 1.0), c1.1.clamp(0.0, 1.0), c2.0.clamp(0.0, 1.0), c2.1.clamp(0.0, 1.0))
391 .map_or(KeyEase::Linear, KeyEase::Bezier)
392 };
393 (left, right)
394}
395
396/// One point of a clip's transform animation ([`crate::project::Clip::transform_keys`]):
397/// the whole [`TransformParams`] at source frame `at`. `at` is an absolute
398/// source frame, numbered as `in_frame` is, so a trim leaves every key on the
399/// footage it was set on -- the same promise a volume point makes
400/// ([`crate::project::GainKey`]).
401#[derive(Debug, Clone, Copy, PartialEq)]
402pub struct TransformKey {
403 /// Source frame of the key.
404 pub at: u32,
405 /// The placement exactly at that frame.
406 pub params: TransformParams,
407 /// The easing of the segment that leaves this key.
408 pub ease: KeyEase,
409}
410
411/// A key of an animation: a value at source frame `at` and the ease of the
412/// segment that leaves it. The interpolation, the trim and the split are
413/// written once over this and shared by every key type.
414pub trait Keyed: Copy {
415 /// Source frame of the key.
416 fn at(&self) -> u32;
417 /// The ease of the segment leaving the key.
418 fn ease(&self) -> KeyEase;
419 /// The same value moved to frame `at`, leaving with `ease`.
420 fn placed(self, at: u32, ease: KeyEase) -> Self;
421 /// The value `t` of the way (already eased) from `a` to `b`.
422 fn mix(a: &Self, b: &Self, t: f32) -> Self;
423}
424
425/// The key an animation gives at source frame `src` (fractional), or `None`
426/// with no keys. Held before the first and after the last key; between two
427/// keys, interpolated with the earlier key's ease. Exact at a key. The
428/// returned key's frame and ease are the earlier key's.
429pub fn sample<K: Keyed>(keys: &[K], src: f64) -> Option<K> {
430 let first = keys.first()?;
431 let last = keys.last()?;
432 if src <= f64::from(first.at()) {
433 return Some(*first);
434 }
435 if src >= f64::from(last.at()) {
436 return Some(*last);
437 }
438 // The first key strictly after `src`; its predecessor starts the segment
439 // `src` is in, and both exist by the two holds above.
440 let i = keys.partition_point(|k| f64::from(k.at()) <= src);
441 let (a, b) = (&keys[i - 1], &keys[i]);
442 let t = ((src - f64::from(a.at())) / f64::from(b.at() - a.at())) as f32;
443 let t = ease_shape(a.ease(), t);
444 Some(K::mix(a, b, t).placed(a.at(), a.ease()))
445}
446
447impl Keyed for TransformKey {
448 fn at(&self) -> u32 {
449 self.at
450 }
451 fn ease(&self) -> KeyEase {
452 self.ease
453 }
454 fn placed(self, at: u32, ease: KeyEase) -> Self {
455 Self { at, ease, ..self }
456 }
457 fn mix(a: &Self, b: &Self, t: f32) -> Self {
458 Self {
459 params: lerp_params(&a.params, &b.params, t),
460 ..*a
461 }
462 }
463}
464
465/// One point of a clip's opacity animation ([`crate::project::Clip::opacity_keys`]):
466/// how much of the placed picture shows (`0..=1`) at source frame `at`.
467#[derive(Debug, Clone, Copy, PartialEq)]
468pub struct OpacityKey {
469 /// Source frame of the key.
470 pub at: u32,
471 /// Opacity exactly there, `0.0` (clear) to `1.0` (opaque).
472 pub opacity: f32,
473 /// The easing of the segment that leaves this key.
474 pub ease: KeyEase,
475}
476
477impl Keyed for OpacityKey {
478 fn at(&self) -> u32 {
479 self.at
480 }
481 fn ease(&self) -> KeyEase {
482 self.ease
483 }
484 fn placed(self, at: u32, ease: KeyEase) -> Self {
485 Self { at, ease, ..self }
486 }
487 fn mix(a: &Self, b: &Self, t: f32) -> Self {
488 Self {
489 opacity: a.opacity + (b.opacity - a.opacity) * t,
490 ..*a
491 }
492 }
493}
494
495/// Every field of `a` moved `t` of the way to `b`, `t` in `0..=1`.
496pub fn lerp_params(a: &TransformParams, b: &TransformParams, t: f32) -> TransformParams {
497 let l = |x: f32, y: f32| x + (y - x) * t;
498 TransformParams {
499 pos_x: l(a.pos_x, b.pos_x),
500 pos_y: l(a.pos_y, b.pos_y),
501 scale: l(a.scale, b.scale),
502 rotate: l(a.rotate, b.rotate),
503 crop_l: l(a.crop_l, b.crop_l),
504 crop_r: l(a.crop_r, b.crop_r),
505 crop_t: l(a.crop_t, b.crop_t),
506 crop_b: l(a.crop_b, b.crop_b),
507 opacity: l(a.opacity, b.opacity),
508 }
509}
510
511/// The placement the keys give at source frame `src` (fractional), or `None`
512/// with no keys. Held before the first and after the last key; between two
513/// keys, each field is interpolated with the earlier key's [`KeyEase`]. Exact
514/// at a key.
515pub fn keys_at(keys: &[TransformKey], src: f64) -> Option<TransformParams> {
516 sample(keys, src).map(|k| k.params)
517}
518
519/// [`keys_at`], or `base` when there are no keys: the one placement a clip
520/// shows at source frame `src`.
521pub fn evaluate(base: &TransformParams, keys: &[TransformKey], src: f64) -> TransformParams {
522 keys_at(keys, src).unwrap_or(*base)
523}
524
525/// The opacity the keys give at source frame `src`, or `base` with no keys.
526pub fn evaluate_opacity(base: f32, keys: &[OpacityKey], src: f64) -> f32 {
527 sample(keys, src).map_or(base, |k| k.opacity)
528}
529
530/// The keys that still shape the picture over source frames `lo..=hi`, after
531/// a trim left the clip showing only that window. Keys inside it stay where
532/// they are. A key before `lo` or after `hi` is dropped, and in its place
533/// there is a key at the window's edge holding the placement the whole
534/// animation gives there, so the visible part moves exactly as it did. An
535/// edge with nothing dropped gets no key: the animation already holds there.
536/// An edge key cuts the eased segment it sits in, so the kept part of that
537/// segment keeps its exact shape (see [`with_cut_key`]). Empty in, empty out.
538pub fn keys_within<K: Keyed>(keys: &[K], lo: u32, hi: u32) -> Vec<K> {
539 if keys.is_empty() || lo > hi {
540 return Vec::new();
541 }
542 let mut list = keys.to_vec();
543 if keys.iter().any(|k| k.at() < lo) && !keys.iter().any(|k| k.at() == lo) {
544 list = with_cut_key(&list, lo);
545 }
546 if hi > lo && keys.iter().any(|k| k.at() > hi) && !keys.iter().any(|k| k.at() == hi) {
547 list = with_cut_key(&list, hi);
548 }
549 list.into_iter().filter(|k| (lo..=hi).contains(&k.at())).collect()
550}
551
552/// `keys` with a key at source frame `cut` holding the value the animation
553/// gives there, so a cut through the animation loses nothing. Cut inside an
554/// eased segment, the key takes the right half of that segment's ease and the
555/// earlier key takes the left half ([`split_ease`]), so each side keeps the
556/// exact shape the whole segment had. Cut outside the segments, the key takes
557/// the ease of the key before it, as a plain hold would. `keys` unchanged if a
558/// key already sits at `cut`. Empty in, empty out.
559pub fn with_cut_key<K: Keyed>(keys: &[K], cut: u32) -> Vec<K> {
560 let Some(at) = sample(keys, f64::from(cut)) else {
561 return Vec::new();
562 };
563 let i = keys.partition_point(|k| k.at() < cut);
564 if keys.get(i).is_some_and(|k| k.at() == cut) {
565 return keys.to_vec();
566 }
567 let mut out = keys.to_vec();
568 let ease = if i > 0 && i < keys.len() {
569 let (a, b) = (keys[i - 1], keys[i]);
570 let t = ((f64::from(cut) - f64::from(a.at())) / f64::from(b.at() - a.at())) as f32;
571 let (left, right) = split_ease(a.ease(), t);
572 out[i - 1] = a.placed(a.at(), left);
573 right
574 } else if i > 0 {
575 keys[i - 1].ease()
576 } else {
577 KeyEase::Linear
578 };
579 out.insert(i, at.placed(cut, ease));
580 out
581}
582
583/// The keys of a still image after its head moved. A still has no frame to
584/// walk an in-point back to, so its trim puts the in-point at frame 0 and
585/// the picture plays from there; the keys must not follow that frame, or the
586/// animation slides along the timeline. Instead each key keeps its *timeline*
587/// time: the clip started at `old_start` playing from `old_in`, and now starts
588/// at `new_start` with its in-point at 0 and its out-point at `new_out`, at
589/// `speed` source frames per timeline frame. Keys that fall before the new
590/// head or past the new tail are cut with [`keys_within`].
591pub fn keys_after_still_head<K: Keyed>(
592 keys: &[K],
593 old_start: u32,
594 old_in: u32,
595 new_start: u32,
596 new_out: u32,
597 speed: f64,
598) -> Vec<K> {
599 // Source frames to add to a key: the old timeline time of the key minus
600 // the new one, both measured from the new in-point at 0.
601 let moved = (f64::from(old_start) - f64::from(new_start)) * speed;
602 let shift = moved.round() as i64 - i64::from(old_in);
603 // The old source frames that now bound the window: `lo` is the new frame
604 // 0 and `hi` the new out-point, both shifted back into the old keys' frames.
605 let lo = (-shift).max(0);
606 let hi = (i64::from(new_out) - shift).max(lo);
607 keys_within(keys, lo as u32, hi as u32)
608 .into_iter()
609 .map(|k| k.placed((i64::from(k.at()) + shift) as u32, k.ease()))
610 .collect()
611}
612
613/// A place on the canvas a picture can be put in: the centre, or one of the
614/// four corners. [`corner_offset`] turns one into `pos_x`/`pos_y`.
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
616pub enum Corner {
617 Centre,
618 TopLeft,
619 TopRight,
620 BottomLeft,
621 BottomRight,
622}
623
624impl Corner {
625 /// Every corner, centre first, in the order a picker lists them.
626 pub const ALL: [Corner; 5] = [
627 Corner::Centre,
628 Corner::TopLeft,
629 Corner::TopRight,
630 Corner::BottomLeft,
631 Corner::BottomRight,
632 ];
633
634 /// The sign of this corner on each axis: `(x, y)`, with `+1` right and down,
635 /// `-1` left and up, and `0` for the centre.
636 fn signs(self) -> (f64, f64) {
637 match self {
638 Corner::Centre => (0.0, 0.0),
639 Corner::TopLeft => (-1.0, -1.0),
640 Corner::TopRight => (1.0, -1.0),
641 Corner::BottomLeft => (-1.0, 1.0),
642 Corner::BottomRight => (1.0, 1.0),
643 }
644 }
645}
646
647/// The `pos_x`/`pos_y` that put a `src_w` x `src_h` picture in `corner` of a
648/// `canvas_w` x `canvas_h` canvas, at `scale`, with `margin` of air between the
649/// picture and the two edges it touches.
650///
651/// `margin` is a fraction of the canvas width, on both axes; the vertical margin
652/// is that same distance in pixels, so it is `margin * canvas_w / canvas_h` of
653/// the height. The picture is fitted inside the canvas the way the default
654/// [`crate::scale::FitPolicy::Fit`] fits it, then `scale` is applied to that box:
655/// a picture at least as wide (in aspect) as the canvas fills its width, a taller
656/// one fills its height. So the half sizes are `scale / 2` on the filled axis and
657/// the other follows the picture's aspect, and each offset is
658/// `0.5 - half size - margin`, signed by the corner.
659///
660/// A 16:9 picture on a 16:9 canvas at scale 0.3 with a 0.03 margin lands at
661/// `x = 0.32`, `y = -0.32` in the top-right corner. [`Corner::Centre`] is `(0, 0)`.
662pub fn corner_offset(
663 corner: Corner,
664 scale: f32,
665 margin: f32,
666 src: (u32, u32),
667 canvas: (u32, u32),
668) -> (f32, f32) {
669 let (half_w, half_h) = fitted_half(scale, src, canvas);
670 let (cw, ch) = (f64::from(canvas.0.max(1)), f64::from(canvas.1.max(1)));
671 let margin_x = f64::from(margin);
672 let margin_y = margin_x * cw / ch;
673 let (sx, sy) = corner.signs();
674 // `+ 0.0` turns the -0.0 a centred axis would otherwise carry into 0.
675 let x = sx * (0.5 - half_w - margin_x) + 0.0;
676 let y = sy * (0.5 - half_h - margin_y) + 0.0;
677 (x as f32, y as f32)
678}
679
680/// Half the width and height of a `src` picture at `scale` on a `canvas`, as
681/// fractions of the canvas width and height: the box the default fit gives,
682/// scaled. The shared measure of [`corner_offset`] and [`placed_half`].
683fn fitted_half(scale: f32, src: (u32, u32), canvas: (u32, u32)) -> (f64, f64) {
684 let (sw, sh) = (f64::from(src.0.max(1)), f64::from(src.1.max(1)));
685 let (cw, ch) = (f64::from(canvas.0.max(1)), f64::from(canvas.1.max(1)));
686 let half = f64::from(scale) / 2.0;
687 if sw * ch >= cw * sh {
688 (half, half * (sh / sw) * (cw / ch))
689 } else {
690 (half * (sw / sh) * (ch / cw), half)
691 }
692}
693
694/// The gap a corner placement keeps from the two canvas edges it touches, in
695/// pixels: the default the transform card and the `corner` op use.
696pub const CORNER_MARGIN_PX: f32 = 32.0;
697
698/// [`corner_offset`] for the picture a placement `t` shows: the picture is
699/// measured as it appears, after its crop and its quarter turn (`src` is its
700/// own pixel size), and `margin_px` is the gap in pixels. Only `scale` and the
701/// shape come from `t`; the position is what this returns.
702pub fn corner_placement(
703 corner: Corner,
704 t: &TransformParams,
705 src: (u32, u32),
706 canvas: (u32, u32),
707 margin_px: f32,
708) -> (f32, f32) {
709 let crop = crate::scale::crop_rect(src.0, src.1, t);
710 let turned = crate::scale::nearest_90_steps(t.rotate) % 2 == 1;
711 let shape = if turned { (crop.h, crop.w) } else { (crop.w, crop.h) };
712 corner_offset(corner, t.scale, margin_px / canvas.0.max(1) as f32, shape, canvas)
713}
714
715/// Half the width and height of the picture `t` shows, as fractions of the
716/// canvas: measured as [`corner_placement`] measures it (after the crop and
717/// the quarter turn), so a viewer outline matches what is drawn.
718pub fn placed_half(t: &TransformParams, src: (u32, u32), canvas: (u32, u32)) -> (f32, f32) {
719 let crop = crate::scale::crop_rect(src.0, src.1, t);
720 let turned = crate::scale::nearest_90_steps(t.rotate) % 2 == 1;
721 let shape = if turned { (crop.h, crop.w) } else { (crop.w, crop.h) };
722 let (hw, hh) = fitted_half(t.scale, shape, canvas);
723 (hw as f32, hh as f32)
724}
725
726/// The placement `new` should have when it changes only the scale of `old`:
727/// a picture that sat in a corner stays in that corner at its new size, so its
728/// position is recomputed. A custom position is kept as it is, and so is any
729/// placement that did not change scale.
730pub fn keep_corner(
731 old: &TransformParams,
732 new: TransformParams,
733 src: (u32, u32),
734 canvas: (u32, u32),
735 margin_px: f32,
736) -> TransformParams {
737 if new.scale == old.scale {
738 return new;
739 }
740 match corner_of(old, src, canvas, margin_px) {
741 Some(corner) => {
742 let (pos_x, pos_y) = corner_placement(corner, &new, src, canvas, margin_px);
743 TransformParams { pos_x, pos_y, ..new }
744 }
745 None => new,
746 }
747}
748
749/// The corner `t` already sits in, when its position is one [`corner_placement`]
750/// gives to within half a pixel on both axes (at its own scale, crop and turn).
751/// `None` when the position is custom.
752pub fn corner_of(t: &TransformParams, src: (u32, u32), canvas: (u32, u32), margin_px: f32) -> Option<Corner> {
753 let (cw, ch) = (canvas.0.max(1) as f32, canvas.1.max(1) as f32);
754 Corner::ALL.into_iter().find(|&c| {
755 let (x, y) = corner_placement(c, t, src, canvas, margin_px);
756 (t.pos_x - x).abs() * cw <= 0.5 && (t.pos_y - y).abs() * ch <= 0.5
757 })
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763
764 #[test]
765 fn bezier_round_trips_and_eases_monotonically() {
766 let b = Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
767 let ease = KeyEase::Bezier(b);
768 assert_eq!(ease.name(), "bezier(0.42,0,0.58,1)");
769 assert_eq!(ease.token(), "b420_0_580_1000");
770 assert_eq!(KeyEase::from_name("bezier( 0.42, 0,0.58 ,1)"), Some(ease));
771 assert_eq!(KeyEase::from_token(b"b420_0_580_1000"), Some(ease));
772 assert_eq!(KeyEase::from_token(b"b420_0_580"), None);
773 assert_eq!(Bezier::new(0.5, 1.5, 0.0, 0.0), None);
774 assert!((ease_shape(ease, 0.5) - 0.5).abs() < 1e-3);
775 let samples: Vec<f32> = (0..=10).map(|i| ease_shape(ease, i as f32 / 10.0)).collect();
776 assert!(samples.windows(2).all(|w| w[0] <= w[1]));
777 assert_eq!(ease_shape(ease, 0.0), 0.0);
778 assert_eq!(ease_shape(ease, 1.0), 1.0);
779 }
780
781 #[test]
782 fn default_is_identity() {
783 assert!(TransformParams::default().is_identity());
784 assert!(!TransformParams {
785 pos_x: 0.001,
786 ..TransformParams::default()
787 }
788 .is_identity());
789 }
790
791 #[test]
792 fn keys_interpolate_linearly_and_hold_outside() {
793 let at = |frame, scale| TransformKey {
794 at: frame,
795 params: TransformParams {
796 scale,
797 ..TransformParams::default()
798 },
799 ease: KeyEase::Linear,
800 };
801 let keys = [at(0, 1.0), at(100, 1.2)];
802 let mid = keys_at(&keys, 50.0).expect("keyed");
803 assert!((mid.scale - 1.1).abs() < 1e-6, "midpoint of 1.0 and 1.2");
804 assert_eq!(keys_at(&keys, 0.0).unwrap().scale, 1.0, "exact at a key");
805 assert_eq!(keys_at(&keys, 100.0).unwrap().scale, 1.2, "exact at the last");
806 assert_eq!(keys_at(&keys, -5.0).unwrap().scale, 1.0, "held before");
807 assert_eq!(keys_at(&keys, 999.0).unwrap().scale, 1.2, "held after");
808 assert!(keys_at(&[], 3.0).is_none(), "no keys is no placement");
809 assert!(evaluate(&TransformParams::default(), &[], 3.0).is_identity());
810 }
811
812 fn scaled(scale: f32) -> TransformParams {
813 TransformParams {
814 scale,
815 ..TransformParams::default()
816 }
817 }
818
819 fn scaled_key(at: u32, scale: f32, ease: KeyEase) -> TransformKey {
820 TransformKey {
821 at,
822 params: scaled(scale),
823 ease,
824 }
825 }
826
827 #[test]
828 fn a_window_keeps_inside_keys_and_edges_hold_the_interpolated_value() {
829 let keys = [
830 scaled_key(0, 1.0, KeyEase::Linear),
831 scaled_key(100, 2.0, KeyEase::Linear),
832 scaled_key(200, 1.0, KeyEase::Linear),
833 ];
834 // Window 50..=150: the key at 100 stays, and the edges get the value
835 // the animation has there (1.5 at 50, 1.5 at 150).
836 let w = keys_within(&keys, 50, 150);
837 let at: Vec<u32> = w.iter().map(|k| k.at).collect();
838 assert_eq!(at, vec![50, 100, 150]);
839 assert!((w[0].params.scale - 1.5).abs() < 1e-6);
840 assert_eq!(w[1].params.scale, 2.0, "the inside key is untouched");
841 assert!((w[2].params.scale - 1.5).abs() < 1e-6);
842 // The animation still reads the same values over the window.
843 for f in 50..=150 {
844 let before = keys_at(&keys, f64::from(f)).unwrap().scale;
845 let after = keys_at(&w, f64::from(f)).unwrap().scale;
846 assert!((before - after).abs() < 1e-6, "frame {f}");
847 }
848 }
849
850 #[test]
851 fn a_window_with_no_key_before_or_after_gets_no_edge_key() {
852 let keys = [scaled_key(100, 2.0, KeyEase::Linear), scaled_key(200, 1.0, KeyEase::Linear)];
853 // Nothing before 100: the head needs no key, the animation holds there.
854 let w = keys_within(&keys, 80, 300);
855 assert_eq!(w, keys.to_vec());
856 // A window that drops the last key adds one at its edge.
857 let w = keys_within(&keys, 0, 150);
858 assert_eq!(w.iter().map(|k| k.at).collect::<Vec<_>>(), vec![100, 150]);
859 }
860
861 #[test]
862 fn a_window_past_every_key_keeps_one_holding_key() {
863 let keys = [scaled_key(10, 1.5, KeyEase::Linear), scaled_key(20, 3.0, KeyEase::Linear)];
864 // Every key is before the window: the animation is held at 3.0 there,
865 // so one key at the window's start says so, and the clip stays keyed.
866 let w = keys_within(&keys, 50, 60);
867 assert_eq!(w.len(), 1);
868 assert_eq!(w[0].at, 50);
869 assert_eq!(w[0].params.scale, 3.0);
870 assert!(keys_within::<TransformKey>(&[], 0, 10).is_empty());
871 }
872
873 #[test]
874 fn a_still_keeps_its_keys_on_the_timeline_when_its_head_moves() {
875 // A still at 30 fps placed at timeline 1 s (frame 30), with keys at
876 // timeline 1 s, 5 s and 9 s (source 0, 120, 240). Trim the head to 2 s
877 // (frame 60): the keys at 5 s and 9 s must stay there, and the key at
878 // 1 s is replaced by one at 2 s holding the value it had there.
879 let keys = [
880 scaled_key(0, 0.3, KeyEase::Linear),
881 scaled_key(120, 0.6, KeyEase::Linear),
882 scaled_key(240, 1.0, KeyEase::Linear),
883 ];
884 let w = keys_after_still_head(&keys, 30, 0, 60, 210, 1.0);
885 let timeline = |k: &TransformKey| 60 + k.at;
886 assert_eq!(timeline(&w[0]), 60, "the boundary at the new head");
887 let at_5s: Vec<u32> = w.iter().map(|k| k.at).collect();
888 assert_eq!(at_5s, vec![0, 90, 210], "frames 90 and 210 are timeline 5 s and 9 s");
889 // The picture at each timeline frame of the visible part is unchanged.
890 for t in 60..=270u32 {
891 let before = keys_at(&keys, f64::from(t - 30)).unwrap().scale;
892 let after = keys_at(&w, f64::from(t - 60)).unwrap().scale;
893 assert!((before - after).abs() < 1e-6, "timeline frame {t}");
894 }
895 }
896
897 #[test]
898 fn a_still_trimmed_to_grow_its_head_keeps_its_keys_too() {
899 let keys = [scaled_key(0, 1.0, KeyEase::Linear), scaled_key(60, 2.0, KeyEase::Linear)];
900 // Head moved earlier by 10 frames (start 30 -> 20): keys move later.
901 let w = keys_after_still_head(&keys, 30, 0, 20, 100, 1.0);
902 assert_eq!(w.iter().map(|k| k.at).collect::<Vec<_>>(), vec![10, 70]);
903 assert_eq!(w[0].params.scale, 1.0, "the first key is still the first");
904 }
905
906 #[test]
907 fn ease_slows_the_segment_ends_and_leaves_the_midpoint() {
908 let mut keys = [
909 TransformKey {
910 at: 0,
911 params: TransformParams::default(),
912 ease: KeyEase::Ease,
913 },
914 TransformKey {
915 at: 100,
916 params: TransformParams {
917 pos_x: 0.4,
918 ..TransformParams::default()
919 },
920 ease: KeyEase::Linear,
921 },
922 ];
923 let mid = keys_at(&keys, 50.0).unwrap().pos_x;
924 assert!((mid - 0.2).abs() < 1e-6, "smoothstep is symmetric about 0.5");
925 let quarter = keys_at(&keys, 25.0).unwrap().pos_x;
926 assert!(quarter < 0.1, "an eased segment starts slower than linear");
927 keys[0].ease = KeyEase::Linear;
928 assert!((keys_at(&keys, 25.0).unwrap().pos_x - 0.1).abs() < 1e-6);
929 }
930
931 #[test]
932 fn every_ease_is_zero_at_the_start_and_one_at_the_end_except_hold() {
933 for e in [KeyEase::Linear, KeyEase::Ease, KeyEase::EaseIn, KeyEase::EaseOut] {
934 assert_eq!(ease_shape(e, 0.0), 0.0, "{e:?} start");
935 assert_eq!(ease_shape(e, 1.0), 1.0, "{e:?} end");
936 }
937 assert_eq!(ease_shape(KeyEase::Hold, 0.0), 0.0);
938 assert_eq!(ease_shape(KeyEase::Hold, 0.999), 0.0, "hold stays until the segment is done");
939 assert_eq!(ease_shape(KeyEase::Hold, 1.0), 1.0);
940 }
941
942 #[test]
943 fn the_ease_shapes_have_their_documented_curves() {
944 // Exact at the quarter and the half.
945 assert_eq!(ease_shape(KeyEase::Linear, 0.25), 0.25);
946 assert!((ease_shape(KeyEase::EaseIn, 0.25) - 0.015625).abs() < 1e-7);
947 assert!((ease_shape(KeyEase::EaseIn, 0.5) - 0.125).abs() < 1e-7);
948 assert!((ease_shape(KeyEase::EaseOut, 0.25) - 0.578125).abs() < 1e-7);
949 assert!((ease_shape(KeyEase::EaseOut, 0.5) - 0.875).abs() < 1e-7);
950 assert!((ease_shape(KeyEase::Ease, 0.25) - 0.15625).abs() < 1e-7, "smoothstep");
951 assert!((ease_shape(KeyEase::Ease, 0.5) - 0.5).abs() < 1e-7, "in-out is symmetric");
952 // In-out is symmetric about the middle; in and out mirror each other.
953 for i in 1..10 {
954 let t = i as f32 / 10.0;
955 assert!((ease_shape(KeyEase::Ease, t) + ease_shape(KeyEase::Ease, 1.0 - t) - 1.0).abs() < 1e-6);
956 assert!((ease_shape(KeyEase::EaseIn, t) + ease_shape(KeyEase::EaseOut, 1.0 - t) - 1.0).abs() < 1e-6);
957 }
958 }
959
960 #[test]
961 fn names_and_tokens_round_trip_and_cycle() {
962 for e in KeyEase::ALL {
963 assert_eq!(KeyEase::from_name(&e.name()), Some(e));
964 assert_eq!(KeyEase::from_token(e.token().as_bytes()), Some(e));
965 }
966 assert_eq!(KeyEase::from_name("ease"), Some(KeyEase::Ease), "the older spelling");
967 assert_eq!(KeyEase::from_name("bounce"), None);
968 let mut e = KeyEase::Linear;
969 for _ in 0..KeyEase::ALL.len() {
970 e = e.next();
971 }
972 assert_eq!(e, KeyEase::Linear, "a full cycle comes back");
973 }
974
975 #[test]
976 fn opacity_keys_use_the_same_interpolation_with_every_ease() {
977 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
978 let mid = |ease| evaluate_opacity(1.0, &[ok(0, 0.0, ease), ok(100, 1.0, ease)], 25.0);
979 assert!((mid(KeyEase::Linear) - 0.25).abs() < 1e-6);
980 assert!((mid(KeyEase::EaseIn) - 0.015625).abs() < 1e-6);
981 assert!((mid(KeyEase::EaseOut) - 0.578125).abs() < 1e-6);
982 assert!((mid(KeyEase::Ease) - 0.15625).abs() < 1e-6);
983 assert_eq!(mid(KeyEase::Hold), 0.0, "hold keeps the first key's value");
984 let keys = [ok(0, 0.2, KeyEase::Hold), ok(100, 0.9, KeyEase::Linear)];
985 assert_eq!(evaluate_opacity(1.0, &keys, 100.0), 0.9, "the next key is exact");
986 assert_eq!(evaluate_opacity(1.0, &keys, 150.0), 0.9, "held after");
987 assert_eq!(evaluate_opacity(1.0, &keys, -3.0), 0.2, "held before");
988 assert_eq!(evaluate_opacity(0.7, &[], 5.0), 0.7, "no keys is the base");
989 }
990
991 #[test]
992 fn eased_keys_split_and_trim_through_the_shared_helpers() {
993 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
994 let keys = [ok(0, 0.0, KeyEase::EaseIn), ok(100, 1.0, KeyEase::Linear)];
995 let within = keys_within(&keys, 20, 80);
996 assert_eq!(within.iter().map(|k| k.at).collect::<Vec<_>>(), vec![20, 80]);
997 assert!(
998 matches!(within[0].ease, KeyEase::Bezier(_)),
999 "an edge key takes the right half of the cut segment's ease"
1000 );
1001 let want = evaluate_opacity(1.0, &keys, 20.0);
1002 assert!((within[0].opacity - want).abs() < 1e-7);
1003 }
1004
1005 #[test]
1006 fn a_cut_through_an_ease_in_keeps_the_motion() {
1007 use crate::project::split_transform_keys;
1008 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
1009 // An ease-in from 0 to 100 over frames 0..100, cut at frame 40.
1010 let keys = [ok(0, 0.0, KeyEase::EaseIn), ok(100, 100.0, KeyEase::Linear)];
1011 let (left, right) = split_transform_keys(&keys, 40);
1012 for f in [20.0, 40.0, 70.0] {
1013 let half = if f <= 40.0 { &left } else { &right };
1014 let got = sample(half, f).expect("keyed").opacity;
1015 let want = sample(&keys, f).expect("keyed").opacity;
1016 assert!((got - want).abs() < 0.5, "frame {f}: {got} against {want}");
1017 }
1018 }
1019
1020 #[test]
1021 fn corner_offset_matches_the_documented_examples() {
1022 // 16:9 on 16:9 at scale 0.3: half-width 0.15, half-height 0.15. The 0.03
1023 // margin is 0.03 of the width on x, and the same distance in pixels down
1024 // the height, 0.03 * 16 / 9 of it, so y is -(0.5 - 0.15 - 0.0533).
1025 let (x, y) = corner_offset(Corner::TopRight, 0.3, 0.03, (1920, 1080), (1920, 1080));
1026 assert!((x - 0.32).abs() < 1e-5, "{x}");
1027 assert!((y + (0.5 - 0.15 - 0.03 * 16.0 / 9.0) as f32).abs() < 1e-5, "{y}");
1028 let (x, y) = corner_offset(Corner::BottomLeft, 0.3, 0.03, (1920, 1080), (1920, 1080));
1029 assert!((x + 0.32).abs() < 1e-5, "{x}");
1030 assert!((y - (0.5 - 0.15 - 0.03 * 16.0 / 9.0) as f32).abs() < 1e-5, "{y}");
1031 // A square logo at 0.2 on 1080x1920 with a 32 px margin (0.0296 of the width):
1032 // x 0.37, y -0.427, as the MCP help states them.
1033 let margin = 32.0 / 1080.0;
1034 let (x, y) = corner_offset(Corner::TopRight, 0.2, margin, (1, 1), (1080, 1920));
1035 assert!((x - 0.37).abs() < 5e-4, "{x}");
1036 assert!((y + 0.427).abs() < 5e-4, "{y}");
1037 }
1038
1039 #[test]
1040 fn corner_offset_signs_and_centre() {
1041 let m = 0.03;
1042 assert_eq!(corner_offset(Corner::Centre, 0.3, m, (16, 9), (16, 9)), (0.0, 0.0));
1043 let (x, y) = corner_offset(Corner::TopLeft, 0.3, m, (16, 9), (16, 9));
1044 assert!(x < 0.0 && y < 0.0);
1045 let (x, y) = corner_offset(Corner::BottomRight, 0.3, m, (16, 9), (16, 9));
1046 assert!(x > 0.0 && y > 0.0);
1047 // The same picture, mirrored, lands on the mirror image.
1048 let (x, y) = corner_offset(Corner::BottomRight, 0.3, m, (16, 9), (16, 9));
1049 let (mx, my) = corner_offset(Corner::TopLeft, 0.3, m, (16, 9), (16, 9));
1050 assert_eq!((x, y), (-mx, -my));
1051 }
1052
1053 #[test]
1054 fn corner_offset_fits_a_taller_picture_by_its_height() {
1055 // A 9:16 picture on a 16:9 canvas fills the height at scale 1, so its
1056 // half-width is 0.5 * (9/16) * (9/16) and its half-height 0.5.
1057 let (x, y) = corner_offset(Corner::TopRight, 1.0, 0.0, (9, 16), (16, 9));
1058 let half_w = 0.5 * (9.0_f32 / 16.0) * (9.0 / 16.0);
1059 assert!((x - (0.5 - half_w)).abs() < 1e-5, "{x}");
1060 assert!((y + 0.0).abs() < 1e-5, "{y}");
1061 }
1062
1063 #[test]
1064 fn corner_placement_measures_the_picture_as_shown() {
1065 // A 16:9 picture turned a quarter is 9:16 on screen, so its shape flips.
1066 let turned = TransformParams { rotate: 90.0, scale: 1.0, ..Default::default() };
1067 let plain = TransformParams { scale: 1.0, ..Default::default() };
1068 let canvas = (1080, 1920);
1069 let (x1, _) = corner_placement(Corner::TopRight, &turned, (1920, 1080), canvas, 0.0);
1070 let (x2, _) = corner_placement(Corner::TopRight, &plain, (1080, 1920), canvas, 0.0);
1071 assert!((x1 - x2).abs() < 1e-5, "a turned 16:9 is the same shape as a 9:16: {x1} {x2}");
1072 // The cropped picture is what is measured, not the whole source.
1073 let cropped = TransformParams { crop_l: 0.25, crop_r: 0.25, scale: 1.0, ..Default::default() };
1074 let (cx, _) = corner_placement(Corner::TopRight, &cropped, (1000, 1000), (1000, 1000), 0.0);
1075 assert!((cx - 0.25).abs() < 1e-4, "a half-width crop of a square fills half the width: {cx}");
1076 }
1077
1078 #[test]
1079 fn corner_of_names_only_the_placed_corner() {
1080 let t = TransformParams { scale: 0.3, ..Default::default() };
1081 let src = (1920, 1080);
1082 let canvas = (1920, 1080);
1083 assert_eq!(corner_of(&t, src, canvas, 32.0), Some(Corner::Centre), "the origin is the centre choice");
1084 let (x, y) = corner_placement(Corner::BottomRight, &t, src, canvas, 32.0);
1085 let placed = TransformParams { pos_x: x, pos_y: y, ..t };
1086 assert_eq!(corner_of(&placed, src, canvas, 32.0), Some(Corner::BottomRight));
1087 // A nudge of ten pixels is a custom position.
1088 let moved = TransformParams { pos_x: x - 10.0 / 1920.0, ..placed };
1089 assert_eq!(corner_of(&moved, src, canvas, 32.0), None);
1090 // A different margin is a different place, too.
1091 assert_eq!(corner_of(&placed, src, canvas, 16.0), None);
1092 }
1093
1094 #[test]
1095 fn corner_offset_fits_a_4_3_source_on_a_16_9_canvas_by_height() {
1096 // A 4:3 picture is 0.75 as wide as the canvas's height in pixels: at
1097 // scale 0.3 on 1280x720 it is 288 px wide and 216 px tall, so it fills
1098 // the height (half-height 0.15) and its half-width is 0.1125 of the width.
1099 // A 32 px margin then puts the centre at x = 1280/2 - 144 - 32 = 464 px and
1100 // y = 720/2 - 108 - 32 = 220 px, which is 0.3625 and 0.3056 of the canvas.
1101 let (x, y) = corner_offset(Corner::BottomRight, 0.3, 32.0 / 1280.0, (640, 480), (1280, 720));
1102 assert!((x * 1280.0 - 464.0).abs() < 0.5, "x {x} is {} px, want 464", x * 1280.0);
1103 assert!((y * 720.0 - 220.0).abs() < 0.5, "y {y} is {} px, want 220", y * 720.0);
1104 // Its right and bottom gaps are both the 32 px margin.
1105 let right = (0.5 - f64::from(x)) * 1280.0 - 144.0;
1106 let bottom = (0.5 - f64::from(y)) * 720.0 - 108.0;
1107 assert!((right - 32.0).abs() < 0.5 && (bottom - 32.0).abs() < 0.5, "gaps {right} {bottom}");
1108 }
1109
1110 #[test]
1111 fn corner_offset_margin_is_a_width_fraction_on_both_axes() {
1112 // The same pixel margin on a 1000x500 canvas is 0.02 across and 0.04 down.
1113 let (x, y) = corner_offset(Corner::BottomRight, 0.0, 0.02, (1, 1), (1000, 500));
1114 assert!((x - 0.48).abs() < 1e-5, "{x}");
1115 assert!((y - 0.46).abs() < 1e-5, "{y}");
1116 }
1117
1118 #[test]
1119 fn keep_corner_holds_the_corner_when_the_scale_changes() {
1120 let src = (1920, 1080);
1121 let canvas = (1920, 1080);
1122 let margin = CORNER_MARGIN_PX;
1123 let at_full = TransformParams {
1124 scale: 1.0,
1125 ..TransformParams::default()
1126 };
1127 let (x, y) = corner_placement(Corner::BottomRight, &at_full, src, canvas, margin);
1128 let placed = TransformParams { pos_x: x, pos_y: y, ..at_full };
1129 assert_eq!(corner_of(&placed, src, canvas, margin), Some(Corner::BottomRight));
1130 let smaller = TransformParams { scale: 0.35, ..placed };
1131 let kept = keep_corner(&placed, smaller, src, canvas, margin);
1132 assert_eq!(corner_of(&kept, src, canvas, margin), Some(Corner::BottomRight));
1133 assert!(kept.pos_x > 0.0 && kept.pos_y > 0.0, "still bottom right, not bottom centre");
1134 // A custom position is left alone.
1135 let moved = TransformParams { pos_x: 0.1, ..placed };
1136 assert_eq!(keep_corner(&moved, smaller, src, canvas, margin), smaller);
1137 // A scale change with no move keeps everything else.
1138 let same = keep_corner(&placed, placed, src, canvas, margin);
1139 assert_eq!(same, placed);
1140 }
1141
1142 #[test]
1143 fn placed_half_is_the_box_corner_placement_fits() {
1144 let canvas = (1920, 1080);
1145 let t = TransformParams { scale: 0.3, ..TransformParams::default() };
1146 let (hw, hh) = placed_half(&t, (1920, 1080), canvas);
1147 assert!((hw - 0.15).abs() < 1e-6 && (hh - 0.15).abs() < 1e-6, "{hw} {hh}");
1148 let (cx, cy) = corner_placement(Corner::TopRight, &t, (1920, 1080), canvas, 0.0);
1149 assert!((cx - (0.5 - hw)).abs() < 1e-6 && (cy + (0.5 - hh)).abs() < 1e-6);
1150 }
1151}