forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

transitions.rs526 lines, 18.7 KiBHistoryRawDownload
1//! Transition kinds: how a clip's tail ([`crate::Clip::transition_out`]) is
2//! drawn into the clip after it.
3//!
4//! The kind changes the picture only. The sound under the overlap is the
5//! crossfade it always was. Preview ([`crate::PlaybackSession`]) and export both
6//! come here: [`blend_planes`] for I420 at 8 or 10 bits, [`blend_bgra`] for the
7//! preview's screen pictures, and both read the same [`Geo::mix`], so the two
8//! cannot disagree about a kind.
9//!
10//! `t` is the share of the transition done, from just above 0 (A) to just below
11//! 1 (B), as [`crate::export::dissolve_weight`] ramps it. A direction names the
12//! way things *move*: `wipe-left` moves its edge leftward, so B shows from the
13//! right edge and at the midpoint the left half is still A and the right half is
14//! B; `slide-left` brings B in from the right over A; `push-left` pushes A out to
15//! the left with B behind it.
16
17use crate::scale::{Sample, chroma_dims};
18
19/// Where a wipe, slide or push moves.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Dir {
22 Left,
23 Right,
24 Up,
25 Down,
26}
27
28impl Dir {
29 pub const ALL: [Dir; 4] = [Dir::Left, Dir::Right, Dir::Up, Dir::Down];
30
31 pub fn name(self) -> &'static str {
32 match self {
33 Dir::Left => "left",
34 Dir::Right => "right",
35 Dir::Up => "up",
36 Dir::Down => "down",
37 }
38 }
39
40 pub fn parse(s: &str) -> Option<Dir> {
41 Dir::ALL.into_iter().find(|d| d.name() == s)
42 }
43}
44
45/// What a transition looks like. [`TransitionKind::Dissolve`] is the default
46/// and what every project before the library meant.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum TransitionKind {
49 #[default]
50 Dissolve,
51 DipBlack,
52 DipWhite,
53 Wipe(Dir),
54 Slide(Dir),
55 Push(Dir),
56 Zoom,
57}
58
59impl TransitionKind {
60 /// One of each shape (a direction shape with `Left`), for pickers.
61 pub const SHAPES: [TransitionKind; 7] = [
62 TransitionKind::Dissolve,
63 TransitionKind::DipBlack,
64 TransitionKind::DipWhite,
65 TransitionKind::Wipe(Dir::Left),
66 TransitionKind::Slide(Dir::Left),
67 TransitionKind::Push(Dir::Left),
68 TransitionKind::Zoom,
69 ];
70
71 /// The shape's name without a direction: `dissolve`, `dip-black`,
72 /// `dip-white`, `wipe`, `slide`, `push`, `zoom`.
73 pub fn shape_name(self) -> &'static str {
74 match self {
75 TransitionKind::Dissolve => "dissolve",
76 TransitionKind::DipBlack => "dip-black",
77 TransitionKind::DipWhite => "dip-white",
78 TransitionKind::Wipe(_) => "wipe",
79 TransitionKind::Slide(_) => "slide",
80 TransitionKind::Push(_) => "push",
81 TransitionKind::Zoom => "zoom",
82 }
83 }
84
85 pub fn dir(self) -> Option<Dir> {
86 match self {
87 TransitionKind::Wipe(d) | TransitionKind::Slide(d) | TransitionKind::Push(d) => Some(d),
88 _ => None,
89 }
90 }
91
92 /// The shape with direction `dir`; a shape without a direction is unchanged.
93 pub fn with_dir(self, dir: Dir) -> TransitionKind {
94 match self {
95 TransitionKind::Wipe(_) => TransitionKind::Wipe(dir),
96 TransitionKind::Slide(_) => TransitionKind::Slide(dir),
97 TransitionKind::Push(_) => TransitionKind::Push(dir),
98 other => other,
99 }
100 }
101
102 /// The shape named `shape` (see [`Self::shape_name`]) moving `dir`
103 /// (`Left` when not given).
104 pub fn from_parts(shape: &str, dir: Option<Dir>) -> Option<TransitionKind> {
105 let d = dir.unwrap_or(Dir::Left);
106 Some(match shape {
107 "dissolve" => TransitionKind::Dissolve,
108 "dip-black" => TransitionKind::DipBlack,
109 "dip-white" => TransitionKind::DipWhite,
110 "wipe" => TransitionKind::Wipe(d),
111 "slide" => TransitionKind::Slide(d),
112 "push" => TransitionKind::Push(d),
113 "zoom" => TransitionKind::Zoom,
114 _ => return None,
115 })
116 }
117
118 /// The full name, as the project file writes it: `wipe-left`, `dip-black`.
119 pub fn name(self) -> String {
120 match self.dir() {
121 Some(d) => format!("{}-{}", self.shape_name(), d.name()),
122 None => self.shape_name().to_string(),
123 }
124 }
125
126 pub fn parse(s: &str) -> Option<TransitionKind> {
127 if let Some((shape, dir)) = s.rsplit_once('-')
128 && let Some(d) = Dir::parse(dir)
129 {
130 return TransitionKind::from_parts(shape, Some(d)).filter(|k| k.dir().is_some());
131 }
132 TransitionKind::from_parts(s, None).filter(|k| k.dir().is_none())
133 }
134
135 /// The shape's name for a card: `Dissolve`, `Dip to black`, `Wipe`.
136 pub fn title(self) -> &'static str {
137 match self {
138 TransitionKind::Dissolve => "Dissolve",
139 TransitionKind::DipBlack => "Dip to black",
140 TransitionKind::DipWhite => "Dip to white",
141 TransitionKind::Wipe(_) => "Wipe",
142 TransitionKind::Slide(_) => "Slide",
143 TransitionKind::Push(_) => "Push",
144 TransitionKind::Zoom => "Zoom",
145 }
146 }
147
148 /// A number that differs for every kind and direction, for telling two
149 /// kinds apart without comparing them (the GUI's before/after check).
150 pub fn ordinal(self) -> u32 {
151 let shape = TransitionKind::SHAPES
152 .iter()
153 .position(|k| k.shape_name() == self.shape_name())
154 .unwrap_or(0) as u32;
155 let dir = self.dir().and_then(|d| Dir::ALL.iter().position(|&x| x == d)).unwrap_or(0) as u32;
156 shape * 4 + dir
157 }
158
159 /// The words the timeline shows on the overlap: `Dissolve`, `Dip to black`,
160 /// `Wipe left`.
161 pub fn label(self) -> String {
162 match self.dir() {
163 Some(d) => format!("{} {}", self.title(), d.name()),
164 None => self.title().to_string(),
165 }
166 }
167}
168
169/// The kind of the transition the clip on screen at timeline `frame` owes its
170/// successor (the one [`crate::export::dissolve_window`] found).
171pub(crate) fn kind_at(project: &crate::Project, frame: u32) -> TransitionKind {
172 project
173 .composite_clip_at(frame)
174 .and_then(|(lane, idx)| project.lane(lane).get(idx))
175 .map_or_else(TransitionKind::default, |c| c.transition_kind)
176}
177
178/// The softness of a wipe's edge, as a share of the picture's width or height.
179const SOFT: f32 = 0.1;
180/// The cross-zoom's scale: A grows from 1 to `ZOOM_A`, B shrinks from `ZOOM_B` to 1.
181const ZOOM_A: f32 = 1.25;
182const ZOOM_B: f32 = 1.2;
183
184/// What one output pixel is made of: `wa` of A at (`ax`, `ay`), `wb` of B at
185/// (`bx`, `by`) and `wd` of the dip colour. The weights sum to 1.
186struct Mix {
187 ax: usize,
188 ay: usize,
189 bx: usize,
190 by: usize,
191 wa: f32,
192 wb: f32,
193 wd: f32,
194}
195
196/// One plane's geometry. A slide or push shifts by an even number of luma
197/// pixels, so a plane with `sub` times fewer pixels moves by exactly its share.
198struct Geo {
199 kind: TransitionKind,
200 t: f32,
201 w: usize,
202 h: usize,
203 /// Luma pixels per plane pixel: 1, or 2 for chroma.
204 sub: usize,
205 luma_w: usize,
206 luma_h: usize,
207}
208
209impl Geo {
210 fn new(kind: TransitionKind, t: f32, luma_w: usize, luma_h: usize, sub: usize) -> Geo {
211 let (w, h) = if sub == 2 {
212 chroma_dims(luma_w, luma_h)
213 } else {
214 (luma_w, luma_h)
215 };
216 Geo {
217 kind,
218 t: t.clamp(0.0, 1.0),
219 w,
220 h,
221 sub,
222 luma_w,
223 luma_h,
224 }
225 }
226
227 /// The shift along an axis of `luma_n` luma pixels, in this plane's pixels.
228 fn shift(&self, luma_n: usize, n: usize) -> usize {
229 let luma = ((self.t * luma_n as f32 / 2.0).round() as usize * 2).min(luma_n);
230 (luma / self.sub).min(n)
231 }
232
233 fn mix(&self, x: usize, y: usize) -> Mix {
234 let same = |wa: f32, wb: f32, wd: f32| Mix {
235 ax: x,
236 ay: y,
237 bx: x,
238 by: y,
239 wa,
240 wb,
241 wd,
242 };
243 let t = self.t;
244 match self.kind {
245 TransitionKind::Dissolve => same(1.0 - t, t, 0.0),
246 TransitionKind::DipBlack | TransitionKind::DipWhite => {
247 if t < 0.5 {
248 same(1.0 - 2.0 * t, 0.0, 2.0 * t)
249 } else {
250 same(0.0, 2.0 * t - 1.0, 2.0 - 2.0 * t)
251 }
252 }
253 TransitionKind::Zoom => {
254 let sa = 1.0 + (ZOOM_A - 1.0) * t;
255 let sb = ZOOM_B + (1.0 - ZOOM_B) * t;
256 let at = |s: f32, p: usize, n: usize| -> usize {
257 let c = n as f32 / 2.0;
258 ((c + ((p as f32 + 0.5) - c) / s).floor().max(0.0) as usize).min(n - 1)
259 };
260 Mix {
261 ax: at(sa, x, self.w),
262 ay: at(sa, y, self.h),
263 bx: at(sb, x, self.w),
264 by: at(sb, y, self.h),
265 wa: 1.0 - t,
266 wb: t,
267 wd: 0.0,
268 }
269 }
270 TransitionKind::Wipe(d) | TransitionKind::Slide(d) | TransitionKind::Push(d) => {
271 let horizontal = matches!(d, Dir::Left | Dir::Right);
272 let (c, n, luma_n) = if horizontal {
273 (x, self.w, self.luma_w)
274 } else {
275 (y, self.h, self.luma_h)
276 };
277 // Work as if moving toward increasing c': a leftward or upward
278 // move has its axis flipped, and is flipped back at the end.
279 let flip = matches!(d, Dir::Left | Dir::Up);
280 let cp = if flip { n - 1 - c } else { c };
281 let back = |v: usize| if flip { n - 1 - v } else { v };
282 // (a, b, wb): the position each side reads, and B's weight.
283 let (a, b, wb) = match self.kind {
284 TransitionKind::Wipe(_) => {
285 let front = t * (1.0 + SOFT);
286 let u = (cp as f32 + 0.5) / n as f32;
287 (cp, cp, ((front - u) / SOFT).clamp(0.0, 1.0))
288 }
289 TransitionKind::Slide(_) => {
290 let s = self.shift(luma_n, n);
291 if cp < s {
292 (cp, cp + n - s, 1.0)
293 } else {
294 (cp, cp, 0.0)
295 }
296 }
297 _ => {
298 let s = self.shift(luma_n, n);
299 if cp < s {
300 (0, cp + n - s, 1.0)
301 } else {
302 (cp - s, 0, 0.0)
303 }
304 }
305 };
306 let (a, b) = (back(a.min(n - 1)), back(b.min(n - 1)));
307 let (ax, ay, bx, by) = if horizontal { (a, y, b, y) } else { (x, a, x, b) };
308 Mix {
309 ax,
310 ay,
311 bx,
312 by,
313 wa: 1.0 - wb,
314 wb,
315 wd: 0.0,
316 }
317 }
318 }
319 }
320}
321
322/// The dip colour's code for a luma or chroma plane of sample type `T`.
323fn dip_code<T: Sample>(kind: TransitionKind, luma: bool) -> f32 {
324 match (kind, luma) {
325 (TransitionKind::DipWhite, true) => (235 * (T::MAX + 1) / 256) as f32,
326 (_, true) => T::BLACK.code() as f32,
327 (_, false) => T::NEUTRAL.code() as f32,
328 }
329}
330
331fn plane<T: Sample>(geo: &Geo, a: &[T], b: &[T], dip: f32) -> Vec<T> {
332 assert_eq!(a.len(), geo.w * geo.h, "transition: plane size");
333 assert_eq!(b.len(), a.len(), "transition: mismatched plane sizes");
334 let mut out = Vec::with_capacity(a.len());
335 for y in 0..geo.h {
336 for x in 0..geo.w {
337 let m = geo.mix(x, y);
338 let v = m.wa * a[m.ay * geo.w + m.ax].code() as f32
339 + m.wb * b[m.by * geo.w + m.bx].code() as f32
340 + m.wd * dip;
341 out.push(T::from_f32(v));
342 }
343 }
344 out
345}
346
347/// `a` and `b` (two `width` x `height` I420 pictures at `T`'s depth) mixed
348/// `t` of the way from A to B in the way `kind` draws it.
349pub fn blend_planes<T: Sample>(
350 kind: TransitionKind,
351 a: (&[T], &[T], &[T]),
352 b: (&[T], &[T], &[T]),
353 t: f32,
354 width: usize,
355 height: usize,
356) -> (Vec<T>, Vec<T>, Vec<T>) {
357 if kind == TransitionKind::Dissolve {
358 return crate::scale::blend_i420(a, b, t);
359 }
360 let luma = Geo::new(kind, t, width, height, 1);
361 let chroma = Geo::new(kind, t, width, height, 2);
362 (
363 plane(&luma, a.0, b.0, dip_code::<T>(kind, true)),
364 plane(&chroma, a.1, b.1, dip_code::<T>(kind, false)),
365 plane(&chroma, a.2, b.2, dip_code::<T>(kind, false)),
366 )
367}
368
369/// [`blend_planes`] for two BGRA pictures.
370pub fn blend_bgra(kind: TransitionKind, a: &[u8], b: &[u8], t: f32, width: usize, height: usize) -> Vec<u8> {
371 assert_eq!(a.len(), b.len(), "blend_bgra: mismatched frame sizes");
372 assert_eq!(a.len(), width * height * 4, "blend_bgra: frame size");
373 let geo = Geo::new(kind, t, width, height, 1);
374 let dip = if kind == TransitionKind::DipWhite { 255.0 } else { 0.0 };
375 let mut out = Vec::with_capacity(a.len());
376 for y in 0..height {
377 for x in 0..width {
378 let m = geo.mix(x, y);
379 let (ai, bi) = ((m.ay * width + m.ax) * 4, (m.by * width + m.bx) * 4);
380 for c in 0..4 {
381 // Alpha is 255 on both sides and in the dip.
382 let d = if c == 3 { 255.0 } else { dip };
383 let v = m.wa * f32::from(a[ai + c]) + m.wb * f32::from(b[bi + c]) + m.wd * d;
384 out.push(v.round().clamp(0.0, 255.0) as u8);
385 }
386 }
387 }
388 out
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 const W: usize = 32;
396 const H: usize = 16;
397
398 /// A solid I420 picture of luma `y`.
399 fn solid(y: u8) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
400 let (cw, ch) = chroma_dims(W, H);
401 (vec![y; W * H], vec![128; cw * ch], vec![128; cw * ch])
402 }
403
404 fn run(kind: TransitionKind, t: f32) -> Vec<u8> {
405 let (a, b) = (solid(50), solid(200));
406 blend_planes(kind, (&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), t, W, H).0
407 }
408
409 fn at(p: &[u8], x: usize, y: usize) -> u8 {
410 p[y * W + x]
411 }
412
413 #[test]
414 fn names_round_trip() {
415 for shape in TransitionKind::SHAPES {
416 let kinds: Vec<_> = match shape.dir() {
417 Some(_) => Dir::ALL.iter().map(|&d| shape.with_dir(d)).collect(),
418 None => vec![shape],
419 };
420 for k in kinds {
421 assert_eq!(TransitionKind::parse(&k.name()), Some(k), "{}", k.name());
422 }
423 }
424 assert_eq!(TransitionKind::parse("wipe"), None);
425 assert_eq!(TransitionKind::parse("zoom-left"), None);
426 assert_eq!(TransitionKind::parse("nonsense"), None);
427 }
428
429 #[test]
430 fn timeline_labels_are_plain_words() {
431 assert_eq!(TransitionKind::Dissolve.label(), "Dissolve");
432 assert_eq!(TransitionKind::DipBlack.label(), "Dip to black");
433 assert_eq!(TransitionKind::DipWhite.label(), "Dip to white");
434 assert_eq!(TransitionKind::Wipe(Dir::Left).label(), "Wipe left");
435 assert_eq!(TransitionKind::Slide(Dir::Up).label(), "Slide up");
436 assert_eq!(TransitionKind::Push(Dir::Down).label(), "Push down");
437 assert_eq!(TransitionKind::Zoom.label(), "Zoom");
438 }
439
440 #[test]
441 fn dissolve_is_the_plain_lerp() {
442 assert!(run(TransitionKind::Dissolve, 0.5).iter().all(|&v| v == 125));
443 }
444
445 #[test]
446 fn wipe_left_shows_a_on_the_left_and_b_on_the_right_at_the_midpoint() {
447 let p = run(TransitionKind::Wipe(Dir::Left), 0.5);
448 assert_eq!(at(&p, 2, 3), 50);
449 assert_eq!(at(&p, W - 3, 3), 200);
450 let q = run(TransitionKind::Wipe(Dir::Right), 0.5);
451 assert_eq!((at(&q, 2, 3), at(&q, W - 3, 3)), (200, 50));
452 let u = run(TransitionKind::Wipe(Dir::Up), 0.5);
453 assert_eq!((at(&u, 3, 1), at(&u, 3, H - 2)), (50, 200));
454 let d = run(TransitionKind::Wipe(Dir::Down), 0.5);
455 assert_eq!((at(&d, 3, 1), at(&d, 3, H - 2)), (200, 50));
456 }
457
458 #[test]
459 fn a_wipe_has_a_soft_edge_between_the_two() {
460 let p = run(TransitionKind::Wipe(Dir::Left), 0.5);
461 let mid = at(&p, W / 2, 0);
462 assert!(mid > 50 && mid < 200, "{mid}");
463 let wide: Vec<u8> = (0..W).map(|x| at(&p, x, 0)).collect();
464 assert!(wide.windows(2).all(|w| w[0] <= w[1]), "monotone: {wide:?}");
465 }
466
467 #[test]
468 fn slide_left_brings_b_in_from_the_right_over_a() {
469 let p = run(TransitionKind::Slide(Dir::Left), 0.5);
470 assert_eq!((at(&p, 2, 3), at(&p, W - 3, 3)), (50, 200));
471 let p = run(TransitionKind::Slide(Dir::Down), 0.5);
472 assert_eq!((at(&p, 3, 1), at(&p, 3, H - 2)), (200, 50));
473 }
474
475 #[test]
476 fn push_moves_a_out_with_b_behind_it() {
477 // Texture A so the shift shows: a ramp across, B flat.
478 let (cw, ch) = chroma_dims(W, H);
479 let ramp: Vec<u8> = (0..W * H).map(|i| (i % W) as u8 * 4).collect();
480 let a = (ramp.clone(), vec![128; cw * ch], vec![128; cw * ch]);
481 let b = solid(200);
482 let push = |d| {
483 blend_planes(
484 TransitionKind::Push(d),
485 (&a.0, &a.1, &a.2),
486 (&b.0, &b.1, &b.2),
487 0.5,
488 W,
489 H,
490 )
491 .0
492 };
493 // A shifted left by 16: output x shows A's x + 16, then B.
494 let p = push(Dir::Left);
495 assert_eq!((at(&p, 0, 0), at(&p, 15, 0), at(&p, 16, 0)), (ramp[16], ramp[31], 200));
496 let p = push(Dir::Right);
497 assert_eq!((at(&p, 16, 0), at(&p, 31, 0), at(&p, 15, 0)), (ramp[0], ramp[15], 200));
498 }
499
500 #[test]
501 fn dips_go_through_their_colour_at_the_midpoint_at_both_depths() {
502 assert!(run(TransitionKind::DipBlack, 0.5).iter().all(|&v| v == 16));
503 assert!(run(TransitionKind::DipWhite, 0.5).iter().all(|&v| v == 235));
504 let (cw, ch) = chroma_dims(W, H);
505 let a = (vec![300u16; W * H], vec![512u16; cw * ch], vec![512u16; cw * ch]);
506 let w = blend_planes(TransitionKind::DipWhite, (&a.0, &a.1, &a.2), (&a.0, &a.1, &a.2), 0.5, W, H);
507 assert!(w.0.iter().all(|&v| v == 940));
508 assert!(w.1.iter().all(|&v| v == 512));
509 }
510
511 #[test]
512 fn zoom_is_a_fade_with_a_scale() {
513 let p = run(TransitionKind::Zoom, 0.5);
514 assert!(p.iter().all(|&v| v == 125), "solids stay a plain mix");
515 }
516
517 #[test]
518 fn bgra_matches_the_planes_geometry() {
519 let (a, b) = (vec![10u8; W * H * 4], vec![250u8; W * H * 4]);
520 let p = blend_bgra(TransitionKind::Wipe(Dir::Left), &a, &b, 0.5, W, H);
521 assert_eq!(p[(3 * W + 2) * 4], 10);
522 assert_eq!(p[(3 * W + W - 3) * 4], 250);
523 let d = blend_bgra(TransitionKind::DipBlack, &a, &b, 0.5, W, H);
524 assert_eq!(&d[..4], &[0, 0, 0, 255]);
525 }
526}