forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc327308Tahinli25 days ago1014 commits

transform.rs1043 lines, 42.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
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/// The height of a custom curve where its horizontal position is `t`. The
279/// curve's parameter is found by a few Newton steps, with bisection as the
280/// fallback when the slope is too flat for Newton.
281fn bezier_height(b: Bezier, t: f32) -> f32 {
282 if t <= 0.0 {
283 return 0.0;
284 }
285 if t >= 1.0 {
286 return 1.0;
287 }
288 let [x1, y1, x2, y2] = b.points();
289 // One coordinate of the cubic from 0 to 1 with control points `p1` and `p2`, at parameter `s`.
290 let coord = |p1: f32, p2: f32, s: f32| {
291 let u = 1.0 - s;
292 3.0 * u * u * s * p1 + 3.0 * u * s * s * p2 + s * s * s
293 };
294 // The slope of `coord` with respect to `s`.
295 let slope = |p1: f32, p2: f32, s: f32| {
296 let u = 1.0 - s;
297 3.0 * u * u * p1 + 6.0 * u * s * (p2 - p1) + 3.0 * s * s * (1.0 - p2)
298 };
299 let mut s = t;
300 let mut found = false;
301 for _ in 0..8 {
302 let err = coord(x1, x2, s) - t;
303 if err.abs() < 1e-6 {
304 found = true;
305 break;
306 }
307 let d = slope(x1, x2, s);
308 if d.abs() < 1e-6 {
309 break;
310 }
311 s = (s - err / d).clamp(0.0, 1.0);
312 }
313 if !found {
314 let (mut lo, mut hi) = (0.0f32, 1.0f32);
315 for _ in 0..32 {
316 s = 0.5 * (lo + hi);
317 if coord(x1, x2, s) < t {
318 lo = s;
319 } else {
320 hi = s;
321 }
322 }
323 }
324 coord(y1, y2, s)
325}
326
327/// One point of a clip's transform animation ([`crate::project::Clip::transform_keys`]):
328/// the whole [`TransformParams`] at source frame `at`. `at` is an absolute
329/// source frame, numbered as `in_frame` is, so a trim leaves every key on the
330/// footage it was set on -- the same promise a volume point makes
331/// ([`crate::project::GainKey`]).
332#[derive(Debug, Clone, Copy, PartialEq)]
333pub struct TransformKey {
334 /// Source frame of the key.
335 pub at: u32,
336 /// The placement exactly at that frame.
337 pub params: TransformParams,
338 /// The easing of the segment that leaves this key.
339 pub ease: KeyEase,
340}
341
342/// A key of an animation: a value at source frame `at` and the ease of the
343/// segment that leaves it. The interpolation, the trim and the split are
344/// written once over this and shared by every key type.
345pub trait Keyed: Copy {
346 /// Source frame of the key.
347 fn at(&self) -> u32;
348 /// The ease of the segment leaving the key.
349 fn ease(&self) -> KeyEase;
350 /// The same value moved to frame `at`, leaving with `ease`.
351 fn placed(self, at: u32, ease: KeyEase) -> Self;
352 /// The value `t` of the way (already eased) from `a` to `b`.
353 fn mix(a: &Self, b: &Self, t: f32) -> Self;
354}
355
356/// The key an animation gives at source frame `src` (fractional), or `None`
357/// with no keys. Held before the first and after the last key; between two
358/// keys, interpolated with the earlier key's ease. Exact at a key. The
359/// returned key's frame and ease are the earlier key's.
360pub fn sample<K: Keyed>(keys: &[K], src: f64) -> Option<K> {
361 let first = keys.first()?;
362 let last = keys.last()?;
363 if src <= f64::from(first.at()) {
364 return Some(*first);
365 }
366 if src >= f64::from(last.at()) {
367 return Some(*last);
368 }
369 // The first key strictly after `src`; its predecessor starts the segment
370 // `src` is in, and both exist by the two holds above.
371 let i = keys.partition_point(|k| f64::from(k.at()) <= src);
372 let (a, b) = (&keys[i - 1], &keys[i]);
373 let t = ((src - f64::from(a.at())) / f64::from(b.at() - a.at())) as f32;
374 let t = ease_shape(a.ease(), t);
375 Some(K::mix(a, b, t).placed(a.at(), a.ease()))
376}
377
378impl Keyed for TransformKey {
379 fn at(&self) -> u32 {
380 self.at
381 }
382 fn ease(&self) -> KeyEase {
383 self.ease
384 }
385 fn placed(self, at: u32, ease: KeyEase) -> Self {
386 Self { at, ease, ..self }
387 }
388 fn mix(a: &Self, b: &Self, t: f32) -> Self {
389 Self {
390 params: lerp_params(&a.params, &b.params, t),
391 ..*a
392 }
393 }
394}
395
396/// One point of a clip's opacity animation ([`crate::project::Clip::opacity_keys`]):
397/// how much of the placed picture shows (`0..=1`) at source frame `at`.
398#[derive(Debug, Clone, Copy, PartialEq)]
399pub struct OpacityKey {
400 /// Source frame of the key.
401 pub at: u32,
402 /// Opacity exactly there, `0.0` (clear) to `1.0` (opaque).
403 pub opacity: f32,
404 /// The easing of the segment that leaves this key.
405 pub ease: KeyEase,
406}
407
408impl Keyed for OpacityKey {
409 fn at(&self) -> u32 {
410 self.at
411 }
412 fn ease(&self) -> KeyEase {
413 self.ease
414 }
415 fn placed(self, at: u32, ease: KeyEase) -> Self {
416 Self { at, ease, ..self }
417 }
418 fn mix(a: &Self, b: &Self, t: f32) -> Self {
419 Self {
420 opacity: a.opacity + (b.opacity - a.opacity) * t,
421 ..*a
422 }
423 }
424}
425
426/// Every field of `a` moved `t` of the way to `b`, `t` in `0..=1`.
427pub fn lerp_params(a: &TransformParams, b: &TransformParams, t: f32) -> TransformParams {
428 let l = |x: f32, y: f32| x + (y - x) * t;
429 TransformParams {
430 pos_x: l(a.pos_x, b.pos_x),
431 pos_y: l(a.pos_y, b.pos_y),
432 scale: l(a.scale, b.scale),
433 rotate: l(a.rotate, b.rotate),
434 crop_l: l(a.crop_l, b.crop_l),
435 crop_r: l(a.crop_r, b.crop_r),
436 crop_t: l(a.crop_t, b.crop_t),
437 crop_b: l(a.crop_b, b.crop_b),
438 opacity: l(a.opacity, b.opacity),
439 }
440}
441
442/// The placement the keys give at source frame `src` (fractional), or `None`
443/// with no keys. Held before the first and after the last key; between two
444/// keys, each field is interpolated with the earlier key's [`KeyEase`]. Exact
445/// at a key.
446pub fn keys_at(keys: &[TransformKey], src: f64) -> Option<TransformParams> {
447 sample(keys, src).map(|k| k.params)
448}
449
450/// [`keys_at`], or `base` when there are no keys: the one placement a clip
451/// shows at source frame `src`.
452pub fn evaluate(base: &TransformParams, keys: &[TransformKey], src: f64) -> TransformParams {
453 keys_at(keys, src).unwrap_or(*base)
454}
455
456/// The opacity the keys give at source frame `src`, or `base` with no keys.
457pub fn evaluate_opacity(base: f32, keys: &[OpacityKey], src: f64) -> f32 {
458 sample(keys, src).map_or(base, |k| k.opacity)
459}
460
461/// The keys that still shape the picture over source frames `lo..=hi`, after
462/// a trim left the clip showing only that window. Keys inside it stay where
463/// they are. A key before `lo` or after `hi` is dropped, and in its place
464/// there is a key at the window's edge holding the placement the whole
465/// animation gives there, so the visible part moves exactly as it did. An
466/// edge with nothing dropped gets no key: the animation already holds there.
467/// Empty in, empty out.
468pub fn keys_within<K: Keyed>(keys: &[K], lo: u32, hi: u32) -> Vec<K> {
469 if keys.is_empty() || lo > hi {
470 return Vec::new();
471 }
472 // The easing of the segment the edge sits in, as a split takes it (`split_transform_keys`).
473 let edge_key = |src: u32| {
474 sample(keys, f64::from(src)).expect("keyed, so a value").placed(
475 src,
476 keys.iter()
477 .rev()
478 .find(|k| k.at() <= src)
479 .map_or(KeyEase::Linear, |k| k.ease()),
480 )
481 };
482 let mut out = Vec::new();
483 if keys.iter().any(|k| k.at() < lo) && !keys.iter().any(|k| k.at() == lo) {
484 out.push(edge_key(lo));
485 }
486 out.extend(keys.iter().copied().filter(|k| (lo..=hi).contains(&k.at())));
487 if hi > lo && keys.iter().any(|k| k.at() > hi) && !keys.iter().any(|k| k.at() == hi) {
488 out.push(edge_key(hi));
489 }
490 out
491}
492
493/// The keys of a still image after its head moved. A still has no frame to
494/// walk an in-point back to, so its trim puts the in-point at frame 0 and
495/// the picture plays from there; the keys must not follow that frame, or the
496/// animation slides along the timeline. Instead each key keeps its *timeline*
497/// time: the clip started at `old_start` playing from `old_in`, and now starts
498/// at `new_start` with its in-point at 0 and its out-point at `new_out`, at
499/// `speed` source frames per timeline frame. Keys that fall before the new
500/// head or past the new tail are cut with [`keys_within`].
501pub fn keys_after_still_head<K: Keyed>(
502 keys: &[K],
503 old_start: u32,
504 old_in: u32,
505 new_start: u32,
506 new_out: u32,
507 speed: f64,
508) -> Vec<K> {
509 // Source frames to add to a key: the old timeline time of the key minus
510 // the new one, both measured from the new in-point at 0.
511 let moved = (f64::from(old_start) - f64::from(new_start)) * speed;
512 let shift = moved.round() as i64 - i64::from(old_in);
513 // The old source frames that now bound the window: `lo` is the new frame
514 // 0 and `hi` the new out-point, both shifted back into the old keys' frames.
515 let lo = (-shift).max(0);
516 let hi = (i64::from(new_out) - shift).max(lo);
517 keys_within(keys, lo as u32, hi as u32)
518 .into_iter()
519 .map(|k| k.placed((i64::from(k.at()) + shift) as u32, k.ease()))
520 .collect()
521}
522
523/// A place on the canvas a picture can be put in: the centre, or one of the
524/// four corners. [`corner_offset`] turns one into `pos_x`/`pos_y`.
525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526pub enum Corner {
527 Centre,
528 TopLeft,
529 TopRight,
530 BottomLeft,
531 BottomRight,
532}
533
534impl Corner {
535 /// Every corner, centre first, in the order a picker lists them.
536 pub const ALL: [Corner; 5] = [
537 Corner::Centre,
538 Corner::TopLeft,
539 Corner::TopRight,
540 Corner::BottomLeft,
541 Corner::BottomRight,
542 ];
543
544 /// The sign of this corner on each axis: `(x, y)`, with `+1` right and down,
545 /// `-1` left and up, and `0` for the centre.
546 fn signs(self) -> (f64, f64) {
547 match self {
548 Corner::Centre => (0.0, 0.0),
549 Corner::TopLeft => (-1.0, -1.0),
550 Corner::TopRight => (1.0, -1.0),
551 Corner::BottomLeft => (-1.0, 1.0),
552 Corner::BottomRight => (1.0, 1.0),
553 }
554 }
555}
556
557/// The `pos_x`/`pos_y` that put a `src_w` x `src_h` picture in `corner` of a
558/// `canvas_w` x `canvas_h` canvas, at `scale`, with `margin` of air between the
559/// picture and the two edges it touches.
560///
561/// `margin` is a fraction of the canvas width, on both axes; the vertical margin
562/// is that same distance in pixels, so it is `margin * canvas_w / canvas_h` of
563/// the height. The picture is fitted inside the canvas the way the default
564/// [`crate::scale::FitPolicy::Fit`] fits it, then `scale` is applied to that box:
565/// a picture at least as wide (in aspect) as the canvas fills its width, a taller
566/// one fills its height. So the half sizes are `scale / 2` on the filled axis and
567/// the other follows the picture's aspect, and each offset is
568/// `0.5 - half size - margin`, signed by the corner.
569///
570/// A 16:9 picture on a 16:9 canvas at scale 0.3 with a 0.03 margin lands at
571/// `x = 0.32`, `y = -0.32` in the top-right corner. [`Corner::Centre`] is `(0, 0)`.
572pub fn corner_offset(
573 corner: Corner,
574 scale: f32,
575 margin: f32,
576 src: (u32, u32),
577 canvas: (u32, u32),
578) -> (f32, f32) {
579 let (half_w, half_h) = fitted_half(scale, src, canvas);
580 let (cw, ch) = (f64::from(canvas.0.max(1)), f64::from(canvas.1.max(1)));
581 let margin_x = f64::from(margin);
582 let margin_y = margin_x * cw / ch;
583 let (sx, sy) = corner.signs();
584 // `+ 0.0` turns the -0.0 a centred axis would otherwise carry into 0.
585 let x = sx * (0.5 - half_w - margin_x) + 0.0;
586 let y = sy * (0.5 - half_h - margin_y) + 0.0;
587 (x as f32, y as f32)
588}
589
590/// Half the width and height of a `src` picture at `scale` on a `canvas`, as
591/// fractions of the canvas width and height: the box the default fit gives,
592/// scaled. The shared measure of [`corner_offset`] and [`placed_half`].
593fn fitted_half(scale: f32, src: (u32, u32), canvas: (u32, u32)) -> (f64, f64) {
594 let (sw, sh) = (f64::from(src.0.max(1)), f64::from(src.1.max(1)));
595 let (cw, ch) = (f64::from(canvas.0.max(1)), f64::from(canvas.1.max(1)));
596 let half = f64::from(scale) / 2.0;
597 if sw * ch >= cw * sh {
598 (half, half * (sh / sw) * (cw / ch))
599 } else {
600 (half * (sw / sh) * (ch / cw), half)
601 }
602}
603
604/// The gap a corner placement keeps from the two canvas edges it touches, in
605/// pixels: the default the transform card and the `corner` op use.
606pub const CORNER_MARGIN_PX: f32 = 32.0;
607
608/// [`corner_offset`] for the picture a placement `t` shows: the picture is
609/// measured as it appears, after its crop and its quarter turn (`src` is its
610/// own pixel size), and `margin_px` is the gap in pixels. Only `scale` and the
611/// shape come from `t`; the position is what this returns.
612pub fn corner_placement(
613 corner: Corner,
614 t: &TransformParams,
615 src: (u32, u32),
616 canvas: (u32, u32),
617 margin_px: f32,
618) -> (f32, f32) {
619 let crop = crate::scale::crop_rect(src.0, src.1, t);
620 let turned = crate::scale::nearest_90_steps(t.rotate) % 2 == 1;
621 let shape = if turned { (crop.h, crop.w) } else { (crop.w, crop.h) };
622 corner_offset(corner, t.scale, margin_px / canvas.0.max(1) as f32, shape, canvas)
623}
624
625/// Half the width and height of the picture `t` shows, as fractions of the
626/// canvas: measured as [`corner_placement`] measures it (after the crop and
627/// the quarter turn), so a viewer outline matches what is drawn.
628pub fn placed_half(t: &TransformParams, src: (u32, u32), canvas: (u32, u32)) -> (f32, f32) {
629 let crop = crate::scale::crop_rect(src.0, src.1, t);
630 let turned = crate::scale::nearest_90_steps(t.rotate) % 2 == 1;
631 let shape = if turned { (crop.h, crop.w) } else { (crop.w, crop.h) };
632 let (hw, hh) = fitted_half(t.scale, shape, canvas);
633 (hw as f32, hh as f32)
634}
635
636/// The placement `new` should have when it changes only the scale of `old`:
637/// a picture that sat in a corner stays in that corner at its new size, so its
638/// position is recomputed. A custom position is kept as it is, and so is any
639/// placement that did not change scale.
640pub fn keep_corner(
641 old: &TransformParams,
642 new: TransformParams,
643 src: (u32, u32),
644 canvas: (u32, u32),
645 margin_px: f32,
646) -> TransformParams {
647 if new.scale == old.scale {
648 return new;
649 }
650 match corner_of(old, src, canvas, margin_px) {
651 Some(corner) => {
652 let (pos_x, pos_y) = corner_placement(corner, &new, src, canvas, margin_px);
653 TransformParams { pos_x, pos_y, ..new }
654 }
655 None => new,
656 }
657}
658
659/// The corner `t` already sits in, when its position is one [`corner_placement`]
660/// gives to within half a pixel on both axes (at its own scale, crop and turn).
661/// `None` when the position is custom.
662pub fn corner_of(t: &TransformParams, src: (u32, u32), canvas: (u32, u32), margin_px: f32) -> Option<Corner> {
663 let (cw, ch) = (canvas.0.max(1) as f32, canvas.1.max(1) as f32);
664 Corner::ALL.into_iter().find(|&c| {
665 let (x, y) = corner_placement(c, t, src, canvas, margin_px);
666 (t.pos_x - x).abs() * cw <= 0.5 && (t.pos_y - y).abs() * ch <= 0.5
667 })
668}
669
670#[cfg(test)]
671mod tests {
672 use super::*;
673
674 #[test]
675 fn bezier_round_trips_and_eases_monotonically() {
676 let b = Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
677 let ease = KeyEase::Bezier(b);
678 assert_eq!(ease.name(), "bezier(0.42,0,0.58,1)");
679 assert_eq!(ease.token(), "b420_0_580_1000");
680 assert_eq!(KeyEase::from_name("bezier( 0.42, 0,0.58 ,1)"), Some(ease));
681 assert_eq!(KeyEase::from_token(b"b420_0_580_1000"), Some(ease));
682 assert_eq!(KeyEase::from_token(b"b420_0_580"), None);
683 assert_eq!(Bezier::new(0.5, 1.5, 0.0, 0.0), None);
684 assert!((ease_shape(ease, 0.5) - 0.5).abs() < 1e-3);
685 let samples: Vec<f32> = (0..=10).map(|i| ease_shape(ease, i as f32 / 10.0)).collect();
686 assert!(samples.windows(2).all(|w| w[0] <= w[1]));
687 assert_eq!(ease_shape(ease, 0.0), 0.0);
688 assert_eq!(ease_shape(ease, 1.0), 1.0);
689 }
690
691 #[test]
692 fn default_is_identity() {
693 assert!(TransformParams::default().is_identity());
694 assert!(!TransformParams {
695 pos_x: 0.001,
696 ..TransformParams::default()
697 }
698 .is_identity());
699 }
700
701 #[test]
702 fn keys_interpolate_linearly_and_hold_outside() {
703 let at = |frame, scale| TransformKey {
704 at: frame,
705 params: TransformParams {
706 scale,
707 ..TransformParams::default()
708 },
709 ease: KeyEase::Linear,
710 };
711 let keys = [at(0, 1.0), at(100, 1.2)];
712 let mid = keys_at(&keys, 50.0).expect("keyed");
713 assert!((mid.scale - 1.1).abs() < 1e-6, "midpoint of 1.0 and 1.2");
714 assert_eq!(keys_at(&keys, 0.0).unwrap().scale, 1.0, "exact at a key");
715 assert_eq!(keys_at(&keys, 100.0).unwrap().scale, 1.2, "exact at the last");
716 assert_eq!(keys_at(&keys, -5.0).unwrap().scale, 1.0, "held before");
717 assert_eq!(keys_at(&keys, 999.0).unwrap().scale, 1.2, "held after");
718 assert!(keys_at(&[], 3.0).is_none(), "no keys is no placement");
719 assert!(evaluate(&TransformParams::default(), &[], 3.0).is_identity());
720 }
721
722 fn scaled(scale: f32) -> TransformParams {
723 TransformParams {
724 scale,
725 ..TransformParams::default()
726 }
727 }
728
729 fn scaled_key(at: u32, scale: f32, ease: KeyEase) -> TransformKey {
730 TransformKey {
731 at,
732 params: scaled(scale),
733 ease,
734 }
735 }
736
737 #[test]
738 fn a_window_keeps_inside_keys_and_edges_hold_the_interpolated_value() {
739 let keys = [
740 scaled_key(0, 1.0, KeyEase::Linear),
741 scaled_key(100, 2.0, KeyEase::Linear),
742 scaled_key(200, 1.0, KeyEase::Linear),
743 ];
744 // Window 50..=150: the key at 100 stays, and the edges get the value
745 // the animation has there (1.5 at 50, 1.5 at 150).
746 let w = keys_within(&keys, 50, 150);
747 let at: Vec<u32> = w.iter().map(|k| k.at).collect();
748 assert_eq!(at, vec![50, 100, 150]);
749 assert!((w[0].params.scale - 1.5).abs() < 1e-6);
750 assert_eq!(w[1].params.scale, 2.0, "the inside key is untouched");
751 assert!((w[2].params.scale - 1.5).abs() < 1e-6);
752 // The animation still reads the same values over the window.
753 for f in 50..=150 {
754 let before = keys_at(&keys, f64::from(f)).unwrap().scale;
755 let after = keys_at(&w, f64::from(f)).unwrap().scale;
756 assert!((before - after).abs() < 1e-6, "frame {f}");
757 }
758 }
759
760 #[test]
761 fn a_window_with_no_key_before_or_after_gets_no_edge_key() {
762 let keys = [scaled_key(100, 2.0, KeyEase::Linear), scaled_key(200, 1.0, KeyEase::Linear)];
763 // Nothing before 100: the head needs no key, the animation holds there.
764 let w = keys_within(&keys, 80, 300);
765 assert_eq!(w, keys.to_vec());
766 // A window that drops the last key adds one at its edge.
767 let w = keys_within(&keys, 0, 150);
768 assert_eq!(w.iter().map(|k| k.at).collect::<Vec<_>>(), vec![100, 150]);
769 }
770
771 #[test]
772 fn a_window_past_every_key_keeps_one_holding_key() {
773 let keys = [scaled_key(10, 1.5, KeyEase::Linear), scaled_key(20, 3.0, KeyEase::Linear)];
774 // Every key is before the window: the animation is held at 3.0 there,
775 // so one key at the window's start says so, and the clip stays keyed.
776 let w = keys_within(&keys, 50, 60);
777 assert_eq!(w.len(), 1);
778 assert_eq!(w[0].at, 50);
779 assert_eq!(w[0].params.scale, 3.0);
780 assert!(keys_within::<TransformKey>(&[], 0, 10).is_empty());
781 }
782
783 #[test]
784 fn a_still_keeps_its_keys_on_the_timeline_when_its_head_moves() {
785 // A still at 30 fps placed at timeline 1 s (frame 30), with keys at
786 // timeline 1 s, 5 s and 9 s (source 0, 120, 240). Trim the head to 2 s
787 // (frame 60): the keys at 5 s and 9 s must stay there, and the key at
788 // 1 s is replaced by one at 2 s holding the value it had there.
789 let keys = [
790 scaled_key(0, 0.3, KeyEase::Linear),
791 scaled_key(120, 0.6, KeyEase::Linear),
792 scaled_key(240, 1.0, KeyEase::Linear),
793 ];
794 let w = keys_after_still_head(&keys, 30, 0, 60, 210, 1.0);
795 let timeline = |k: &TransformKey| 60 + k.at;
796 assert_eq!(timeline(&w[0]), 60, "the boundary at the new head");
797 let at_5s: Vec<u32> = w.iter().map(|k| k.at).collect();
798 assert_eq!(at_5s, vec![0, 90, 210], "frames 90 and 210 are timeline 5 s and 9 s");
799 // The picture at each timeline frame of the visible part is unchanged.
800 for t in 60..=270u32 {
801 let before = keys_at(&keys, f64::from(t - 30)).unwrap().scale;
802 let after = keys_at(&w, f64::from(t - 60)).unwrap().scale;
803 assert!((before - after).abs() < 1e-6, "timeline frame {t}");
804 }
805 }
806
807 #[test]
808 fn a_still_trimmed_to_grow_its_head_keeps_its_keys_too() {
809 let keys = [scaled_key(0, 1.0, KeyEase::Linear), scaled_key(60, 2.0, KeyEase::Linear)];
810 // Head moved earlier by 10 frames (start 30 -> 20): keys move later.
811 let w = keys_after_still_head(&keys, 30, 0, 20, 100, 1.0);
812 assert_eq!(w.iter().map(|k| k.at).collect::<Vec<_>>(), vec![10, 70]);
813 assert_eq!(w[0].params.scale, 1.0, "the first key is still the first");
814 }
815
816 #[test]
817 fn ease_slows_the_segment_ends_and_leaves_the_midpoint() {
818 let mut keys = [
819 TransformKey {
820 at: 0,
821 params: TransformParams::default(),
822 ease: KeyEase::Ease,
823 },
824 TransformKey {
825 at: 100,
826 params: TransformParams {
827 pos_x: 0.4,
828 ..TransformParams::default()
829 },
830 ease: KeyEase::Linear,
831 },
832 ];
833 let mid = keys_at(&keys, 50.0).unwrap().pos_x;
834 assert!((mid - 0.2).abs() < 1e-6, "smoothstep is symmetric about 0.5");
835 let quarter = keys_at(&keys, 25.0).unwrap().pos_x;
836 assert!(quarter < 0.1, "an eased segment starts slower than linear");
837 keys[0].ease = KeyEase::Linear;
838 assert!((keys_at(&keys, 25.0).unwrap().pos_x - 0.1).abs() < 1e-6);
839 }
840
841 #[test]
842 fn every_ease_is_zero_at_the_start_and_one_at_the_end_except_hold() {
843 for e in [KeyEase::Linear, KeyEase::Ease, KeyEase::EaseIn, KeyEase::EaseOut] {
844 assert_eq!(ease_shape(e, 0.0), 0.0, "{e:?} start");
845 assert_eq!(ease_shape(e, 1.0), 1.0, "{e:?} end");
846 }
847 assert_eq!(ease_shape(KeyEase::Hold, 0.0), 0.0);
848 assert_eq!(ease_shape(KeyEase::Hold, 0.999), 0.0, "hold stays until the segment is done");
849 assert_eq!(ease_shape(KeyEase::Hold, 1.0), 1.0);
850 }
851
852 #[test]
853 fn the_ease_shapes_have_their_documented_curves() {
854 // Exact at the quarter and the half.
855 assert_eq!(ease_shape(KeyEase::Linear, 0.25), 0.25);
856 assert!((ease_shape(KeyEase::EaseIn, 0.25) - 0.015625).abs() < 1e-7);
857 assert!((ease_shape(KeyEase::EaseIn, 0.5) - 0.125).abs() < 1e-7);
858 assert!((ease_shape(KeyEase::EaseOut, 0.25) - 0.578125).abs() < 1e-7);
859 assert!((ease_shape(KeyEase::EaseOut, 0.5) - 0.875).abs() < 1e-7);
860 assert!((ease_shape(KeyEase::Ease, 0.25) - 0.15625).abs() < 1e-7, "smoothstep");
861 assert!((ease_shape(KeyEase::Ease, 0.5) - 0.5).abs() < 1e-7, "in-out is symmetric");
862 // In-out is symmetric about the middle; in and out mirror each other.
863 for i in 1..10 {
864 let t = i as f32 / 10.0;
865 assert!((ease_shape(KeyEase::Ease, t) + ease_shape(KeyEase::Ease, 1.0 - t) - 1.0).abs() < 1e-6);
866 assert!((ease_shape(KeyEase::EaseIn, t) + ease_shape(KeyEase::EaseOut, 1.0 - t) - 1.0).abs() < 1e-6);
867 }
868 }
869
870 #[test]
871 fn names_and_tokens_round_trip_and_cycle() {
872 for e in KeyEase::ALL {
873 assert_eq!(KeyEase::from_name(&e.name()), Some(e));
874 assert_eq!(KeyEase::from_token(e.token().as_bytes()), Some(e));
875 }
876 assert_eq!(KeyEase::from_name("ease"), Some(KeyEase::Ease), "the older spelling");
877 assert_eq!(KeyEase::from_name("bounce"), None);
878 let mut e = KeyEase::Linear;
879 for _ in 0..KeyEase::ALL.len() {
880 e = e.next();
881 }
882 assert_eq!(e, KeyEase::Linear, "a full cycle comes back");
883 }
884
885 #[test]
886 fn opacity_keys_use_the_same_interpolation_with_every_ease() {
887 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
888 let mid = |ease| evaluate_opacity(1.0, &[ok(0, 0.0, ease), ok(100, 1.0, ease)], 25.0);
889 assert!((mid(KeyEase::Linear) - 0.25).abs() < 1e-6);
890 assert!((mid(KeyEase::EaseIn) - 0.015625).abs() < 1e-6);
891 assert!((mid(KeyEase::EaseOut) - 0.578125).abs() < 1e-6);
892 assert!((mid(KeyEase::Ease) - 0.15625).abs() < 1e-6);
893 assert_eq!(mid(KeyEase::Hold), 0.0, "hold keeps the first key's value");
894 let keys = [ok(0, 0.2, KeyEase::Hold), ok(100, 0.9, KeyEase::Linear)];
895 assert_eq!(evaluate_opacity(1.0, &keys, 100.0), 0.9, "the next key is exact");
896 assert_eq!(evaluate_opacity(1.0, &keys, 150.0), 0.9, "held after");
897 assert_eq!(evaluate_opacity(1.0, &keys, -3.0), 0.2, "held before");
898 assert_eq!(evaluate_opacity(0.7, &[], 5.0), 0.7, "no keys is the base");
899 }
900
901 #[test]
902 fn eased_keys_split_and_trim_through_the_shared_helpers() {
903 let ok = |at, opacity, ease| OpacityKey { at, opacity, ease };
904 let keys = [ok(0, 0.0, KeyEase::EaseIn), ok(100, 1.0, KeyEase::Linear)];
905 let within = keys_within(&keys, 20, 80);
906 assert_eq!(within.iter().map(|k| k.at).collect::<Vec<_>>(), vec![20, 80]);
907 assert_eq!(within[0].ease, KeyEase::EaseIn, "an edge key keeps the segment's ease");
908 let want = evaluate_opacity(1.0, &keys, 20.0);
909 assert!((within[0].opacity - want).abs() < 1e-7);
910 }
911
912 #[test]
913 fn corner_offset_matches_the_documented_examples() {
914 // 16:9 on 16:9 at scale 0.3: half-width 0.15, half-height 0.15. The 0.03
915 // margin is 0.03 of the width on x, and the same distance in pixels down
916 // the height, 0.03 * 16 / 9 of it, so y is -(0.5 - 0.15 - 0.0533).
917 let (x, y) = corner_offset(Corner::TopRight, 0.3, 0.03, (1920, 1080), (1920, 1080));
918 assert!((x - 0.32).abs() < 1e-5, "{x}");
919 assert!((y + (0.5 - 0.15 - 0.03 * 16.0 / 9.0) as f32).abs() < 1e-5, "{y}");
920 let (x, y) = corner_offset(Corner::BottomLeft, 0.3, 0.03, (1920, 1080), (1920, 1080));
921 assert!((x + 0.32).abs() < 1e-5, "{x}");
922 assert!((y - (0.5 - 0.15 - 0.03 * 16.0 / 9.0) as f32).abs() < 1e-5, "{y}");
923 // A square logo at 0.2 on 1080x1920 with a 32 px margin (0.0296 of the width):
924 // x 0.37, y -0.427, as the MCP help states them.
925 let margin = 32.0 / 1080.0;
926 let (x, y) = corner_offset(Corner::TopRight, 0.2, margin, (1, 1), (1080, 1920));
927 assert!((x - 0.37).abs() < 5e-4, "{x}");
928 assert!((y + 0.427).abs() < 5e-4, "{y}");
929 }
930
931 #[test]
932 fn corner_offset_signs_and_centre() {
933 let m = 0.03;
934 assert_eq!(corner_offset(Corner::Centre, 0.3, m, (16, 9), (16, 9)), (0.0, 0.0));
935 let (x, y) = corner_offset(Corner::TopLeft, 0.3, m, (16, 9), (16, 9));
936 assert!(x < 0.0 && y < 0.0);
937 let (x, y) = corner_offset(Corner::BottomRight, 0.3, m, (16, 9), (16, 9));
938 assert!(x > 0.0 && y > 0.0);
939 // The same picture, mirrored, lands on the mirror image.
940 let (x, y) = corner_offset(Corner::BottomRight, 0.3, m, (16, 9), (16, 9));
941 let (mx, my) = corner_offset(Corner::TopLeft, 0.3, m, (16, 9), (16, 9));
942 assert_eq!((x, y), (-mx, -my));
943 }
944
945 #[test]
946 fn corner_offset_fits_a_taller_picture_by_its_height() {
947 // A 9:16 picture on a 16:9 canvas fills the height at scale 1, so its
948 // half-width is 0.5 * (9/16) * (9/16) and its half-height 0.5.
949 let (x, y) = corner_offset(Corner::TopRight, 1.0, 0.0, (9, 16), (16, 9));
950 let half_w = 0.5 * (9.0_f32 / 16.0) * (9.0 / 16.0);
951 assert!((x - (0.5 - half_w)).abs() < 1e-5, "{x}");
952 assert!((y + 0.0).abs() < 1e-5, "{y}");
953 }
954
955 #[test]
956 fn corner_placement_measures_the_picture_as_shown() {
957 // A 16:9 picture turned a quarter is 9:16 on screen, so its shape flips.
958 let turned = TransformParams { rotate: 90.0, scale: 1.0, ..Default::default() };
959 let plain = TransformParams { scale: 1.0, ..Default::default() };
960 let canvas = (1080, 1920);
961 let (x1, _) = corner_placement(Corner::TopRight, &turned, (1920, 1080), canvas, 0.0);
962 let (x2, _) = corner_placement(Corner::TopRight, &plain, (1080, 1920), canvas, 0.0);
963 assert!((x1 - x2).abs() < 1e-5, "a turned 16:9 is the same shape as a 9:16: {x1} {x2}");
964 // The cropped picture is what is measured, not the whole source.
965 let cropped = TransformParams { crop_l: 0.25, crop_r: 0.25, scale: 1.0, ..Default::default() };
966 let (cx, _) = corner_placement(Corner::TopRight, &cropped, (1000, 1000), (1000, 1000), 0.0);
967 assert!((cx - 0.25).abs() < 1e-4, "a half-width crop of a square fills half the width: {cx}");
968 }
969
970 #[test]
971 fn corner_of_names_only_the_placed_corner() {
972 let t = TransformParams { scale: 0.3, ..Default::default() };
973 let src = (1920, 1080);
974 let canvas = (1920, 1080);
975 assert_eq!(corner_of(&t, src, canvas, 32.0), Some(Corner::Centre), "the origin is the centre choice");
976 let (x, y) = corner_placement(Corner::BottomRight, &t, src, canvas, 32.0);
977 let placed = TransformParams { pos_x: x, pos_y: y, ..t };
978 assert_eq!(corner_of(&placed, src, canvas, 32.0), Some(Corner::BottomRight));
979 // A nudge of ten pixels is a custom position.
980 let moved = TransformParams { pos_x: x - 10.0 / 1920.0, ..placed };
981 assert_eq!(corner_of(&moved, src, canvas, 32.0), None);
982 // A different margin is a different place, too.
983 assert_eq!(corner_of(&placed, src, canvas, 16.0), None);
984 }
985
986 #[test]
987 fn corner_offset_fits_a_4_3_source_on_a_16_9_canvas_by_height() {
988 // A 4:3 picture is 0.75 as wide as the canvas's height in pixels: at
989 // scale 0.3 on 1280x720 it is 288 px wide and 216 px tall, so it fills
990 // the height (half-height 0.15) and its half-width is 0.1125 of the width.
991 // A 32 px margin then puts the centre at x = 1280/2 - 144 - 32 = 464 px and
992 // y = 720/2 - 108 - 32 = 220 px, which is 0.3625 and 0.3056 of the canvas.
993 let (x, y) = corner_offset(Corner::BottomRight, 0.3, 32.0 / 1280.0, (640, 480), (1280, 720));
994 assert!((x * 1280.0 - 464.0).abs() < 0.5, "x {x} is {} px, want 464", x * 1280.0);
995 assert!((y * 720.0 - 220.0).abs() < 0.5, "y {y} is {} px, want 220", y * 720.0);
996 // Its right and bottom gaps are both the 32 px margin.
997 let right = (0.5 - f64::from(x)) * 1280.0 - 144.0;
998 let bottom = (0.5 - f64::from(y)) * 720.0 - 108.0;
999 assert!((right - 32.0).abs() < 0.5 && (bottom - 32.0).abs() < 0.5, "gaps {right} {bottom}");
1000 }
1001
1002 #[test]
1003 fn corner_offset_margin_is_a_width_fraction_on_both_axes() {
1004 // The same pixel margin on a 1000x500 canvas is 0.02 across and 0.04 down.
1005 let (x, y) = corner_offset(Corner::BottomRight, 0.0, 0.02, (1, 1), (1000, 500));
1006 assert!((x - 0.48).abs() < 1e-5, "{x}");
1007 assert!((y - 0.46).abs() < 1e-5, "{y}");
1008 }
1009
1010 #[test]
1011 fn keep_corner_holds_the_corner_when_the_scale_changes() {
1012 let src = (1920, 1080);
1013 let canvas = (1920, 1080);
1014 let margin = CORNER_MARGIN_PX;
1015 let at_full = TransformParams {
1016 scale: 1.0,
1017 ..TransformParams::default()
1018 };
1019 let (x, y) = corner_placement(Corner::BottomRight, &at_full, src, canvas, margin);
1020 let placed = TransformParams { pos_x: x, pos_y: y, ..at_full };
1021 assert_eq!(corner_of(&placed, src, canvas, margin), Some(Corner::BottomRight));
1022 let smaller = TransformParams { scale: 0.35, ..placed };
1023 let kept = keep_corner(&placed, smaller, src, canvas, margin);
1024 assert_eq!(corner_of(&kept, src, canvas, margin), Some(Corner::BottomRight));
1025 assert!(kept.pos_x > 0.0 && kept.pos_y > 0.0, "still bottom right, not bottom centre");
1026 // A custom position is left alone.
1027 let moved = TransformParams { pos_x: 0.1, ..placed };
1028 assert_eq!(keep_corner(&moved, smaller, src, canvas, margin), smaller);
1029 // A scale change with no move keeps everything else.
1030 let same = keep_corner(&placed, placed, src, canvas, margin);
1031 assert_eq!(same, placed);
1032 }
1033
1034 #[test]
1035 fn placed_half_is_the_box_corner_placement_fits() {
1036 let canvas = (1920, 1080);
1037 let t = TransformParams { scale: 0.3, ..TransformParams::default() };
1038 let (hw, hh) = placed_half(&t, (1920, 1080), canvas);
1039 assert!((hw - 0.15).abs() < 1e-6 && (hh - 0.15).abs() < 1e-6, "{hw} {hh}");
1040 let (cx, cy) = corner_placement(Corner::TopRight, &t, (1920, 1080), canvas, 0.0);
1041 assert!((cx - (0.5 - hw)).abs() < 1e-6 && (cy + (0.5 - hh)).abs() < 1e-6);
1042 }
1043}