forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

effects.rs1197 lines, 46.0 KiBHistoryRawDownload
1//! A clip's effects stack ([`crate::project::Clip::effects`]): an ordered list of
2//! picture effects, drawn on the clip's picture as it lands on the frame, before
3//! that picture is laid over the lanes beneath it.
4//!
5//! Two sorts of effect share the one list:
6//!
7//! * the *filters* -- blur, sharpen, vignette, glow and camera shake -- rewrite
8//! the clip's own samples, in list order;
9//! * the *compositing* ones -- the colour key and the two masks -- each multiply
10//! into the clip's coverage (where the clip shows over what is beneath), and a
11//! blend effect picks how it is laid there ([`BlendMode`]). The last enabled
12//! blend in the list wins.
13//!
14//! Everything works on the I420 planes every path already holds, at 8 bits or at
15//! 10 bits in `u16` ([`Sample`]), so playback and the two export depths draw the
16//! same picture from the same numbers. Distances (a blur's radius, a shake's
17//! reach) are pixels *of a 1080-line frame* and scale with the frame's height, so
18//! a preview at a smaller size shows the effect at the size the export will.
19//!
20//! The parameters are static (one value for the whole clip), except the two masks'
21//! position, size and soft edge, which take keys ([`MaskKey`]) at source frames and
22//! are read at the frame shown ([`Effect::posed`]). A pixelate is a filter; a mask
23//! placed right after it limits it to that mask's shape, and that mask then does
24//! not cut the clip's coverage. An empty list, and a list whose every effect is
25//! switched off, is no effect at all -- not a sample is touched and no path changes
26//! ([`active`]).
27
28use std::borrow::Cow;
29
30use crate::colorspace::Matrix;
31use crate::scale::{Sample, chroma_dims};
32use crate::transform::{KeyEase, Keyed, sample};
33
34/// The most effects one clip's stack may hold.
35pub const MAX_EFFECTS: usize = 16;
36/// The most parameters any one effect has.
37pub const MAX_PARAMS: usize = 6;
38
39/// Which effect an [`Effect`] is.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub enum EffectKind {
42 Blur,
43 Sharpen,
44 Vignette,
45 Glow,
46 Shake,
47 ChromaKey,
48 Blend,
49 RectMask,
50 EllipseMask,
51 Pixelate,
52}
53
54impl EffectKind {
55 pub const ALL: [EffectKind; 10] = [
56 EffectKind::Blur,
57 EffectKind::Sharpen,
58 EffectKind::Vignette,
59 EffectKind::Glow,
60 EffectKind::Shake,
61 EffectKind::ChromaKey,
62 EffectKind::Blend,
63 EffectKind::RectMask,
64 EffectKind::EllipseMask,
65 EffectKind::Pixelate,
66 ];
67
68 /// The name the project file and the MCP ops spell it with.
69 pub fn name(self) -> &'static str {
70 match self {
71 EffectKind::Blur => "blur",
72 EffectKind::Sharpen => "sharpen",
73 EffectKind::Vignette => "vignette",
74 EffectKind::Glow => "glow",
75 EffectKind::Shake => "shake",
76 EffectKind::ChromaKey => "chroma_key",
77 EffectKind::Blend => "blend",
78 EffectKind::RectMask => "rect_mask",
79 EffectKind::EllipseMask => "ellipse_mask",
80 EffectKind::Pixelate => "pixelate",
81 }
82 }
83
84 pub fn from_name(name: &str) -> Option<EffectKind> {
85 EffectKind::ALL.into_iter().find(|k| k.name() == name)
86 }
87
88 /// The plain words a person sees for it.
89 pub fn label(self) -> &'static str {
90 match self {
91 EffectKind::Blur => "Blur",
92 EffectKind::Sharpen => "Sharpen",
93 EffectKind::Vignette => "Vignette",
94 EffectKind::Glow => "Glow",
95 EffectKind::Shake => "Camera shake",
96 EffectKind::ChromaKey => "Green screen",
97 EffectKind::Blend => "Blend with lanes below",
98 EffectKind::RectMask => "Rectangle mask",
99 EffectKind::EllipseMask => "Ellipse mask",
100 EffectKind::Pixelate => "Pixelate",
101 }
102 }
103
104 /// Its parameters, in the order [`Effect::values`] holds them.
105 pub fn params(self) -> &'static [ParamSpec] {
106 const fn p(name: &'static str, label: &'static str, min: f32, max: f32, default: f32, step: f32) -> ParamSpec {
107 ParamSpec { name, label, min, max, default, step }
108 }
109 const BLUR: [ParamSpec; 1] = [p("radius", "Radius", 0.0, 100.0, 10.0, 0.5)];
110 const SHARPEN: [ParamSpec; 1] = [p("amount", "Amount", 0.0, 3.0, 1.0, 0.05)];
111 const VIGNETTE: [ParamSpec; 2] = [
112 p("amount", "Amount", 0.0, 1.0, 0.5, 0.01),
113 p("softness", "Softness", 0.0, 1.0, 0.5, 0.01),
114 ];
115 const GLOW: [ParamSpec; 2] = [
116 p("amount", "Amount", 0.0, 2.0, 0.6, 0.01),
117 p("threshold", "Brightness it starts at", 0.0, 1.0, 0.7, 0.01),
118 ];
119 const SHAKE: [ParamSpec; 3] = [
120 p("amount", "Amount", 0.0, 100.0, 12.0, 0.5),
121 p("speed", "Speed", 0.1, 20.0, 4.0, 0.1),
122 p("seed", "Pattern", 0.0, 9999.0, 1.0, 1.0),
123 ];
124 const KEY: [ParamSpec; 6] = [
125 p("red", "Key red", 0.0, 255.0, 0.0, 1.0),
126 p("green", "Key green", 0.0, 255.0, 255.0, 1.0),
127 p("blue", "Key blue", 0.0, 255.0, 0.0, 1.0),
128 p("tolerance", "Tolerance", 0.0, 1.0, 0.3, 0.01),
129 p("softness", "Edge softness", 0.0, 1.0, 0.1, 0.01),
130 p("spill", "Remove colour spill", 0.0, 1.0, 0.5, 0.01),
131 ];
132 const BLEND: [ParamSpec; 1] = [p("mode", "Mode", 0.0, 6.0, 0.0, 1.0)];
133 const PIXELATE: [ParamSpec; 1] = [p("size", "Block size", 2.0, 200.0, 16.0, 1.0)];
134 const MASK: [ParamSpec; 6] = [
135 p("x", "Centre across", 0.0, 1.0, 0.5, 0.01),
136 p("y", "Centre down", 0.0, 1.0, 0.5, 0.01),
137 p("width", "Width", 0.0, 1.0, 0.5, 0.01),
138 p("height", "Height", 0.0, 1.0, 0.5, 0.01),
139 p("feather", "Soft edge", 0.0, 0.5, 0.05, 0.005),
140 p("invert", "Invert", 0.0, 1.0, 0.0, 1.0),
141 ];
142 match self {
143 EffectKind::Blur => &BLUR,
144 EffectKind::Sharpen => &SHARPEN,
145 EffectKind::Vignette => &VIGNETTE,
146 EffectKind::Glow => &GLOW,
147 EffectKind::Shake => &SHAKE,
148 EffectKind::ChromaKey => &KEY,
149 EffectKind::Blend => &BLEND,
150 EffectKind::Pixelate => &PIXELATE,
151 EffectKind::RectMask | EffectKind::EllipseMask => &MASK,
152 }
153 }
154}
155
156/// One parameter of an effect: its name in the file and the MCP ops, its plain
157/// label, its range and default, and the step a slider moves it by. A `step` of 1
158/// over a 0..1 range is a switch.
159#[derive(Clone, Copy, Debug, PartialEq)]
160pub struct ParamSpec {
161 pub name: &'static str,
162 pub label: &'static str,
163 pub min: f32,
164 pub max: f32,
165 pub default: f32,
166 pub step: f32,
167}
168
169/// How a clip is laid over the lanes beneath it. Defined on RGB, as every
170/// editor defines them, and worked per pixel through the output's matrix.
171#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
172pub enum BlendMode {
173 #[default]
174 Normal,
175 Multiply,
176 Screen,
177 Overlay,
178 Add,
179 Darken,
180 Lighten,
181}
182
183impl BlendMode {
184 pub const ALL: [BlendMode; 7] = [
185 BlendMode::Normal,
186 BlendMode::Multiply,
187 BlendMode::Screen,
188 BlendMode::Overlay,
189 BlendMode::Add,
190 BlendMode::Darken,
191 BlendMode::Lighten,
192 ];
193
194 pub fn name(self) -> &'static str {
195 match self {
196 BlendMode::Normal => "normal",
197 BlendMode::Multiply => "multiply",
198 BlendMode::Screen => "screen",
199 BlendMode::Overlay => "overlay",
200 BlendMode::Add => "add",
201 BlendMode::Darken => "darken",
202 BlendMode::Lighten => "lighten",
203 }
204 }
205
206 pub fn from_name(name: &str) -> Option<BlendMode> {
207 BlendMode::ALL.into_iter().find(|m| m.name() == name)
208 }
209
210 /// The mode a blend effect's `mode` value names (its index in [`BlendMode::ALL`]).
211 pub fn from_value(v: f32) -> BlendMode {
212 BlendMode::ALL[(v.round().clamp(0.0, 6.0)) as usize]
213 }
214
215 fn mix(self, b: f32, t: f32) -> f32 {
216 match self {
217 BlendMode::Normal => t,
218 BlendMode::Multiply => b * t,
219 BlendMode::Screen => 1.0 - (1.0 - b) * (1.0 - t),
220 BlendMode::Overlay => match b < 0.5 {
221 true => 2.0 * b * t,
222 false => 1.0 - 2.0 * (1.0 - b) * (1.0 - t),
223 },
224 BlendMode::Add => (b + t).min(1.0),
225 BlendMode::Darken => b.min(t),
226 BlendMode::Lighten => b.max(t),
227 }
228 }
229}
230
231/// One point of a mask's animation ([`Effect::keys`]): the shape's centre, size and
232/// soft edge at source frame `at`, with the ease of the segment that leaves it. The
233/// fields are the mask's [`EffectKind::params`] in order, so [`Effect::posed`] reads
234/// them like the static values.
235#[derive(Clone, Copy, Debug, PartialEq)]
236pub struct MaskKey {
237 /// Source frame of the key.
238 pub at: u32,
239 pub x: f32,
240 pub y: f32,
241 pub width: f32,
242 pub height: f32,
243 pub feather: f32,
244 /// The easing of the segment that leaves this key.
245 pub ease: KeyEase,
246}
247
248impl Keyed for MaskKey {
249 fn at(&self) -> u32 {
250 self.at
251 }
252 fn ease(&self) -> KeyEase {
253 self.ease
254 }
255 fn placed(self, at: u32, ease: KeyEase) -> Self {
256 Self { at, ease, ..self }
257 }
258 fn mix(a: &Self, b: &Self, t: f32) -> Self {
259 let l = |x: f32, y: f32| x + (y - x) * t;
260 Self {
261 x: l(a.x, b.x),
262 y: l(a.y, b.y),
263 width: l(a.width, b.width),
264 height: l(a.height, b.height),
265 feather: l(a.feather, b.feather),
266 ..*a
267 }
268 }
269}
270
271/// One effect of a stack: what it is, whether it is switched on, and its
272/// parameters in [`EffectKind::params`] order (the unused tail is zero). A mask
273/// may carry [`MaskKey`]s, which replace its position, size and soft edge.
274#[derive(Clone, Debug, PartialEq)]
275pub struct Effect {
276 pub kind: EffectKind,
277 pub on: bool,
278 pub values: [f32; MAX_PARAMS],
279 /// The mask's animation, sorted by [`MaskKey::at`] with no two alike. Empty is
280 /// the static values. Only a rect or ellipse mask has keys.
281 pub keys: Vec<MaskKey>,
282}
283
284impl Effect {
285 /// A switched-on effect of `kind` at its defaults.
286 pub fn new(kind: EffectKind) -> Effect {
287 let mut values = [0.0; MAX_PARAMS];
288 for (v, spec) in values.iter_mut().zip(kind.params()) {
289 *v = spec.default;
290 }
291 Effect { kind, on: true, values, keys: Vec::new() }
292 }
293
294 /// The effect as it draws at source frame `src`: a keyed mask with its
295 /// position, size and soft edge interpolated from its keys; anything else as it
296 /// is, borrowed.
297 pub fn posed(&self, src: f64) -> Cow<'_, Effect> {
298 match sample(&self.keys, src) {
299 None => Cow::Borrowed(self),
300 Some(k) => {
301 let mut e = self.clone();
302 e.values[..5].copy_from_slice(&[k.x, k.y, k.width, k.height, k.feather]);
303 Cow::Owned(e)
304 }
305 }
306 }
307
308 /// The value of the parameter called `name`, if the effect has one.
309 pub fn get(&self, name: &str) -> Option<f32> {
310 let at = self.kind.params().iter().position(|p| p.name == name)?;
311 Some(self.values[at])
312 }
313
314 /// Sets the parameter called `name`, clamped into its range. An error names
315 /// the parameters the effect does have.
316 pub fn set(&mut self, name: &str, value: f32) -> Result<(), String> {
317 let specs = self.kind.params();
318 let Some(at) = specs.iter().position(|p| p.name == name) else {
319 let names: Vec<&str> = specs.iter().map(|p| p.name).collect();
320 return Err(format!(
321 "{} has no parameter {name:?}; it has {}",
322 self.kind.name(),
323 names.join(", ")
324 ));
325 };
326 if !value.is_finite() {
327 return Err(format!("{name} must be a finite number"));
328 }
329 self.values[at] = value.clamp(specs[at].min, specs[at].max);
330 Ok(())
331 }
332
333 /// Every value clamped into its range and the unused tail zeroed: what a
334 /// setter stores, so a stack read back from anywhere draws in range.
335 pub fn clamped(mut self) -> Effect {
336 let specs = self.kind.params();
337 for (i, v) in self.values.iter_mut().enumerate() {
338 *v = match specs.get(i) {
339 Some(s) if v.is_finite() => v.clamp(s.min, s.max),
340 Some(s) => s.default,
341 None => 0.0,
342 };
343 }
344 self
345 }
346
347 fn v(&self, i: usize) -> f32 {
348 self.values[i]
349 }
350}
351
352/// Whether the stack does anything: one effect at least is switched on. A clip
353/// whose stack is not active is drawn exactly as a clip with none.
354pub fn active(effects: &[Effect]) -> bool {
355 effects.iter().any(|e| e.on)
356}
357
358/// Whether the stack changes from frame to frame on the same picture (a camera
359/// shake): such a clip is drawn again every frame even when its source holds.
360pub fn animated(effects: &[Effect]) -> bool {
361 effects.iter().any(|e| e.on && (e.kind == EffectKind::Shake || !e.keys.is_empty()))
362}
363
364/// Reusable sample buffers for [`apply`], kept by the caller across frames so a
365/// frame allocates nothing per pixel and, after the first, nothing at all for the
366/// filters.
367#[derive(Default)]
368pub struct Scratch<T> {
369 a: Vec<T>,
370 b: Vec<T>,
371}
372
373/// What a stack asks of the compositor, once its filters are drawn: the clip's
374/// coverage from its keys and masks (`None` where it has neither, which is full
375/// coverage), and the mode it is laid down with.
376#[derive(Clone, Debug, Default, PartialEq)]
377pub struct Composite {
378 pub alpha: Option<Vec<u8>>,
379 pub mode: BlendMode,
380}
381
382impl Composite {
383 /// Whether the clip is laid down any other way than an opaque normal one.
384 pub fn composites(&self) -> bool {
385 self.alpha.is_some() || self.mode != BlendMode::Normal
386 }
387}
388
389/// Draws the stack on a `w` x `h` I420 picture in place, in list order, and
390/// returns how the result is to be laid over what is beneath it. `secs` is the
391/// timeline time of the frame (what a shake follows), `src` the source frame it
392/// plays (what the mask keys follow) and `matrix` the one the samples are coded
393/// against (what a key colour and a blend are converted through).
394#[allow(clippy::too_many_arguments)]
395pub fn apply<T: Sample>(
396 effects: &[Effect],
397 planes: (&mut [T], &mut [T], &mut [T]),
398 w: usize,
399 h: usize,
400 secs: f64,
401 src: f64,
402 matrix: Matrix,
403 scratch: &mut Scratch<T>,
404) -> Composite {
405 let (y, u, v) = planes;
406 let mut out = Composite::default();
407 let px = h as f32 / 1080.0;
408 let (cw, ch) = chroma_dims(w, h);
409 // A pixelate is limited by the first mask after it, which then only shapes it
410 // and does not cut the clip: `limit[i]` is that mask's index for pixelate `i`,
411 // `shaping[j]` marks the mask.
412 let mut limit = vec![None; effects.len()];
413 let mut shaping = vec![false; effects.len()];
414 let mut pending = None;
415 for (i, e) in effects.iter().enumerate().filter(|(_, e)| e.on) {
416 match e.kind {
417 EffectKind::Pixelate => pending = Some(i),
418 EffectKind::RectMask | EffectKind::EllipseMask => {
419 if let Some(p) = pending.take() {
420 limit[p] = Some(i);
421 shaping[i] = true;
422 }
423 }
424 _ => {}
425 }
426 }
427 for (i, e) in effects.iter().enumerate().filter(|(_, e)| e.on) {
428 match e.kind {
429 EffectKind::Pixelate => {
430 let block = (e.v(0) * px).round().max(1.0) as usize;
431 let cover = limit[i].map(|j| {
432 let mut m = vec![255u8; w * h];
433 mask(&effects[j].posed(src), w, h, &mut m);
434 m
435 });
436 pixelate(y, w, h, block, 1, w, cover.as_deref());
437 pixelate(u, cw, ch, (block / 2).max(1), 2, w, cover.as_deref());
438 pixelate(v, cw, ch, (block / 2).max(1), 2, w, cover.as_deref());
439 }
440 EffectKind::Blur => {
441 let r = e.v(0) * px;
442 gauss(y, w, h, r, &mut scratch.a);
443 gauss(u, cw, ch, r / 2.0, &mut scratch.a);
444 gauss(v, cw, ch, r / 2.0, &mut scratch.a);
445 }
446 EffectKind::Sharpen => sharpen(y, w, h, e.v(0), (2.0 * px).max(1.0), scratch),
447 EffectKind::Vignette => vignette(y, u, v, w, h, e.v(0), e.v(1)),
448 EffectKind::Glow => glow(y, w, h, e.v(0), e.v(1), 20.0 * px, scratch),
449 EffectKind::Shake => {
450 let (dx, dy) = shake_offset(e.v(0) * px, e.v(1), e.v(2) as u32, secs);
451 shift(y, w, h, dx, dy, &mut scratch.a);
452 shift(u, cw, ch, dx / 2, dy / 2, &mut scratch.a);
453 shift(v, cw, ch, dx / 2, dy / 2, &mut scratch.a);
454 }
455 EffectKind::ChromaKey => {
456 let alpha = out.alpha.get_or_insert_with(|| vec![255; w * h]);
457 chroma_key(e, u, v, w, h, matrix, alpha);
458 }
459 EffectKind::Blend => out.mode = BlendMode::from_value(e.v(0)),
460 EffectKind::RectMask | EffectKind::EllipseMask => {
461 if !shaping[i] {
462 let alpha = out.alpha.get_or_insert_with(|| vec![255; w * h]);
463 mask(&e.posed(src), w, h, alpha);
464 }
465 }
466 }
467 }
468 out
469}
470
471/// The 8-bit-scale value of a sample, and back: the 10-bit codes are four times
472/// the 8-bit ones, so the per-pixel arithmetic is written once on the 8-bit scale.
473fn depth<T: Sample>() -> f32 {
474 (T::MAX + 1) as f32 / 256.0
475}
476
477/// The integer Gaussian kernel for a blur of `radius` pixels: taps `-r..=r`, the
478/// radius three standard deviations, weights summing to exactly `1 << SHIFT`.
479const SHIFT: u32 = 14;
480fn kernel(radius: f32) -> Vec<u32> {
481 let r = radius.ceil() as usize;
482 let sigma = (radius / 3.0).max(0.3);
483 let raw: Vec<f32> = (0..=2 * r)
484 .map(|i| {
485 let d = i as f32 - r as f32;
486 (-d * d / (2.0 * sigma * sigma)).exp()
487 })
488 .collect();
489 let total: f32 = raw.iter().sum();
490 let mut k: Vec<u32> = raw
491 .iter()
492 .map(|w| (w / total * (1u32 << SHIFT) as f32).round() as u32)
493 .collect();
494 let sum: u32 = k.iter().sum();
495 // The rounding's leftover goes to the centre tap, so a flat field stays flat.
496 k[r] = (k[r] + (1 << SHIFT)).saturating_sub(sum);
497 k
498}
499
500/// Runs `f` over the rows of `out` (each `w` long), split across the machine's
501/// cores. `f` is handed the row's index and a per-thread accumulator row.
502fn par_rows<T: Send>(out: &mut [T], w: usize, f: impl Fn(usize, &mut [T], &mut Vec<u32>) + Sync) {
503 let h = out.len() / w.max(1);
504 if h == 0 {
505 return;
506 }
507 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
508 let threads = cores.min(h.div_ceil(32)).max(1);
509 let per = h.div_ceil(threads);
510 if threads == 1 {
511 let mut acc = Vec::new();
512 for (row, line) in out.chunks_mut(w).enumerate() {
513 f(row, line, &mut acc);
514 }
515 return;
516 }
517 let f = &f;
518 std::thread::scope(|s| {
519 for (chunk, lines) in out.chunks_mut(per * w).enumerate() {
520 s.spawn(move || {
521 let mut acc = Vec::new();
522 for (i, line) in lines.chunks_mut(w).enumerate() {
523 f(chunk * per + i, line, &mut acc);
524 }
525 });
526 }
527 });
528}
529
530/// A separable Gaussian blur of one plane in place: a horizontal pass into
531/// `tmp`, a vertical one back. Edges repeat their last sample.
532fn gauss<T: Sample>(plane: &mut [T], w: usize, h: usize, radius: f32, tmp: &mut Vec<T>) {
533 if radius < 0.5 || w == 0 || h == 0 {
534 return;
535 }
536 let k = kernel(radius);
537 let r = k.len() / 2;
538 let half = 1u32 << (SHIFT - 1);
539 tmp.clear();
540 tmp.resize(w * h, T::default());
541 {
542 let src = &*plane;
543 let k = &k;
544 par_rows(tmp, w, |row, line, _| {
545 let s = &src[row * w..row * w + w];
546 for (x, out) in line.iter_mut().enumerate() {
547 let mut acc = 0u32;
548 if x >= r && x + r < w {
549 for (j, &kw) in k.iter().enumerate() {
550 acc += kw * s[x - r + j].code();
551 }
552 } else {
553 for (j, &kw) in k.iter().enumerate() {
554 acc += kw * s[(x + j).saturating_sub(r).min(w - 1)].code();
555 }
556 }
557 *out = T::from_code((acc + half) >> SHIFT);
558 }
559 });
560 }
561 let src = &*tmp;
562 let k = &k;
563 par_rows(plane, w, |row, line, acc| {
564 acc.clear();
565 acc.resize(w, 0);
566 for (j, &kw) in k.iter().enumerate() {
567 let sy = (row + j).saturating_sub(r).min(h - 1);
568 for (a, s) in acc.iter_mut().zip(&src[sy * w..sy * w + w]) {
569 *a += kw * s.code();
570 }
571 }
572 for (out, a) in line.iter_mut().zip(acc.iter()) {
573 *out = T::from_code((a + half) >> SHIFT);
574 }
575 });
576}
577
578/// An unsharp mask on luma: each sample pushed away from its blurred
579/// neighbourhood by `amount`.
580fn sharpen<T: Sample>(y: &mut [T], w: usize, h: usize, amount: f32, radius: f32, s: &mut Scratch<T>) {
581 if amount <= 0.0 {
582 return;
583 }
584 s.b.clear();
585 s.b.extend_from_slice(y);
586 gauss(&mut s.b, w, h, radius, &mut s.a);
587 for (p, &b) in y.iter_mut().zip(&s.b) {
588 let (o, b) = (p.code() as f32, b.code() as f32);
589 *p = T::from_f32(o + amount * (o - b));
590 }
591}
592
593/// Darkens toward the corners: 1 at the centre, `1 - amount` at a corner, the
594/// fall-off starting further in the softer it is. Chroma fades toward neutral
595/// with its luma, so a dark corner is black rather than a dark tint.
596fn vignette<T: Sample>(y: &mut [T], u: &mut [T], v: &mut [T], w: usize, h: usize, amount: f32, softness: f32) {
597 if amount <= 0.0 {
598 return;
599 }
600 let lo = (1.0 - softness.clamp(0.0, 1.0)) * 0.85;
601 let factor = |fx: f32, fy: f32| {
602 let nx = fx / w as f32 * 2.0 - 1.0;
603 let ny = fy / h as f32 * 2.0 - 1.0;
604 let d = ((nx * nx + ny * ny) * 0.5).sqrt();
605 1.0 - amount * smoothstep(lo, 1.0, d)
606 };
607 let black = T::BLACK.code() as f32;
608 let neutral = T::NEUTRAL.code() as f32;
609 for row in 0..h {
610 for col in 0..w {
611 let f = factor(col as f32 + 0.5, row as f32 + 0.5);
612 let p = &mut y[row * w + col];
613 *p = T::from_f32(black + (p.code() as f32 - black) * f);
614 }
615 }
616 let (cw, ch) = chroma_dims(w, h);
617 for row in 0..ch {
618 for col in 0..cw {
619 let f = factor(col as f32 * 2.0 + 1.0, row as f32 * 2.0 + 1.0);
620 let i = row * cw + col;
621 u[i] = T::from_f32(neutral + (u[i].code() as f32 - neutral) * f);
622 v[i] = T::from_f32(neutral + (v[i].code() as f32 - neutral) * f);
623 }
624 }
625}
626
627/// A bloom on luma: what is brighter than `threshold` (0 black, 1 white) is
628/// blurred wide and added back at `amount`.
629fn glow<T: Sample>(y: &mut [T], w: usize, h: usize, amount: f32, threshold: f32, radius: f32, s: &mut Scratch<T>) {
630 if amount <= 0.0 {
631 return;
632 }
633 let d = depth::<T>();
634 let thr = ((16.0 + threshold.clamp(0.0, 1.0) * 219.0) * d) as u32;
635 s.b.clear();
636 s.b.extend(y.iter().map(|p| T::from_code(p.code().saturating_sub(thr))));
637 gauss(&mut s.b, w, h, radius, &mut s.a);
638 for (p, &b) in y.iter_mut().zip(&s.b) {
639 *p = T::from_f32(p.code() as f32 + amount * b.code() as f32);
640 }
641}
642
643/// The camera shake's offset at `secs`, in even whole pixels (so the chroma
644/// planes move exactly half as far): smooth value noise, two octaves, one
645/// independent wobble per axis, the same for the same seed every time.
646pub fn shake_offset(reach: f32, speed: f32, seed: u32, secs: f64) -> (i32, i32) {
647 let t = secs * f64::from(speed.max(0.0));
648 let n = |salt: u32| {
649 let a = noise(seed.wrapping_mul(2).wrapping_add(salt), t);
650 let b = noise(seed.wrapping_mul(2).wrapping_add(salt) ^ 0x5bd1_e995, t * 2.0 + 17.0);
651 (a + 0.5 * b) / 1.5
652 };
653 let even = |v: f32| (v * reach / 2.0).round() as i32 * 2;
654 (even(n(0)), even(n(1)))
655}
656
657fn noise(seed: u32, t: f64) -> f32 {
658 let hash = |i: i64| {
659 let mut x = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ u64::from(seed).wrapping_mul(0xBF58_476D_1CE4_E5B9);
660 x ^= x >> 31;
661 x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
662 x ^= x >> 29;
663 (x >> 40) as f32 / (1u64 << 23) as f32 - 1.0
664 };
665 let i = t.floor();
666 let f = (t - i) as f32;
667 let s = f * f * (3.0 - 2.0 * f);
668 let (a, b) = (hash(i as i64), hash(i as i64 + 1));
669 a + (b - a) * s
670}
671
672/// The plane moved by `(dx, dy)` pixels, its edges repeated into what is
673/// uncovered.
674fn shift<T: Sample>(plane: &mut [T], w: usize, h: usize, dx: i32, dy: i32, tmp: &mut Vec<T>) {
675 if (dx == 0 && dy == 0) || w == 0 || h == 0 {
676 return;
677 }
678 tmp.clear();
679 tmp.extend_from_slice(plane);
680 let clamp = |v: i64, n: usize| v.clamp(0, n as i64 - 1) as usize;
681 for row in 0..h {
682 let sy = clamp(row as i64 - i64::from(dy), h);
683 let src = &tmp[sy * w..sy * w + w];
684 for (col, p) in plane[row * w..row * w + w].iter_mut().enumerate() {
685 *p = src[clamp(col as i64 - i64::from(dx), w)];
686 }
687 }
688}
689
690/// Luma and chroma weights of a matrix: `(kr, kb)`.
691fn weights(matrix: Matrix) -> (f32, f32) {
692 match matrix {
693 Matrix::Bt601 => (0.299, 0.114),
694 Matrix::Bt709 => (0.2126, 0.0722),
695 Matrix::Bt2020Ncl => (0.2627, 0.0593),
696 }
697}
698
699/// Limited-range 8-bit-scale YUV to RGB in 0..=1.
700fn to_rgb(y: f32, u: f32, v: f32, (kr, kb): (f32, f32)) -> [f32; 3] {
701 let yn = (y - 16.0) / 219.0;
702 let (cb, cr) = ((u - 128.0) / 224.0, (v - 128.0) / 224.0);
703 let r = yn + 2.0 * (1.0 - kr) * cr;
704 let b = yn + 2.0 * (1.0 - kb) * cb;
705 let g = (yn - kr * r - kb * b) / (1.0 - kr - kb);
706 [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)]
707}
708
709/// RGB in 0..=1 to limited-range 8-bit-scale YUV.
710fn to_yuv([r, g, b]: [f32; 3], (kr, kb): (f32, f32)) -> (f32, f32, f32) {
711 let yn = kr * r + (1.0 - kr - kb) * g + kb * b;
712 let cb = (b - yn) / (2.0 * (1.0 - kb));
713 let cr = (r - yn) / (2.0 * (1.0 - kr));
714 (16.0 + 219.0 * yn, 128.0 + 224.0 * cb, 128.0 + 224.0 * cr)
715}
716
717fn smoothstep(lo: f32, hi: f32, x: f32) -> f32 {
718 if hi <= lo {
719 return if x < lo { 0.0 } else { 1.0 };
720 }
721 let t = ((x - lo) / (hi - lo)).clamp(0.0, 1.0);
722 t * t * (3.0 - 2.0 * t)
723}
724
725/// A colour key: coverage falls to 0 where a pixel's colour is within
726/// `tolerance` of the key's (measured on chroma, so a shadow on the screen keys
727/// as the lit part does), softening over `softness`; `spill` takes the key's own
728/// hue out of what is left, so a green fringe goes grey.
729fn chroma_key<T: Sample>(e: &Effect, u: &mut [T], v: &mut [T], w: usize, h: usize, matrix: Matrix, alpha: &mut [u8]) {
730 let rgb = [e.v(0) / 255.0, e.v(1) / 255.0, e.v(2) / 255.0];
731 let (_, ku, kv) = to_yuv(rgb, weights(matrix));
732 let (dirx, diry) = (ku - 128.0, kv - 128.0);
733 let len = (dirx * dirx + diry * diry).sqrt();
734 let (tol, soft, spill) = (e.v(3), e.v(4), e.v(5));
735 let d = depth::<T>();
736 let (cw, ch) = chroma_dims(w, h);
737 let mut block = vec![0u8; cw];
738 for row in 0..ch {
739 for (col, a) in block.iter_mut().enumerate() {
740 let i = row * cw + col;
741 let (pu, pv) = (u[i].code() as f32 / d, v[i].code() as f32 / d);
742 let dist = ((pu - ku).powi(2) + (pv - kv).powi(2)).sqrt() / 128.0;
743 *a = (smoothstep(tol, tol + soft, dist) * 255.0).round() as u8;
744 if spill > 0.0 && len > 1.0 {
745 let p = ((pu - 128.0) * dirx + (pv - 128.0) * diry) / len;
746 if p > 0.0 {
747 let k = spill * p / len;
748 u[i] = T::from_f32((pu - k * dirx) * d);
749 v[i] = T::from_f32((pv - k * diry) * d);
750 }
751 }
752 }
753 for ly in [2 * row, 2 * row + 1].into_iter().filter(|&ly| ly < h) {
754 for (x, a) in alpha[ly * w..ly * w + w].iter_mut().enumerate() {
755 *a = mul255(*a, block[x / 2]);
756 }
757 }
758 }
759}
760
761fn mul255(a: u8, b: u8) -> u8 {
762 ((u32::from(a) * u32::from(b) + 127) / 255) as u8
763}
764
765/// Mosaic on one plane of `w` x `h` samples in place: each `block` x `block` cell
766/// takes its average. With `cover` (luma-sized, `lw` wide, read at `sub` times the
767/// plane's position) a cell is mixed in only where the coverage says, so the mosaic
768/// lands inside a mask and the rest of the picture is left as it was.
769fn pixelate<T: Sample>(plane: &mut [T], w: usize, h: usize, block: usize, sub: usize, lw: usize, cover: Option<&[u8]>) {
770 for by in (0..h).step_by(block) {
771 for bx in (0..w).step_by(block) {
772 let (ye, xe) = ((by + block).min(h), (bx + block).min(w));
773 let mut sum = 0u32;
774 for row in by..ye {
775 sum += plane[row * w + bx..row * w + xe].iter().map(|s| s.code()).sum::<u32>();
776 }
777 let n = ((ye - by) * (xe - bx)) as u32;
778 let avg = T::from_code((sum + n / 2) / n);
779 for row in by..ye {
780 for col in bx..xe {
781 let a = cover.map_or(255, |c| u32::from(c[row * sub * lw + col * sub]));
782 let s = &mut plane[row * w + col];
783 *s = T::from_code((s.code() * (255 - a) + avg.code() * a + 127) / 255);
784 }
785 }
786 }
787 }
788}
789
790/// A rectangle or ellipse mask: coverage 1 inside the shape and 0 outside, the
791/// edge softened over `feather` of the frame's height (centred on the edge), and
792/// the whole turned inside out by `invert`. The shape's centre and size are
793/// fractions of the frame.
794fn mask(e: &Effect, w: usize, h: usize, alpha: &mut [u8]) {
795 let (cx, cy) = (e.v(0) * w as f32, e.v(1) * h as f32);
796 let (hw, hh) = ((e.v(2) * w as f32 / 2.0).max(0.0), (e.v(3) * h as f32 / 2.0).max(0.0));
797 let feather = e.v(4) * h as f32;
798 let invert = e.v(5) >= 0.5;
799 let ellipse = e.kind == EffectKind::EllipseMask;
800 for row in 0..h {
801 let py = row as f32 + 0.5 - cy;
802 for (col, a) in alpha[row * w..row * w + w].iter_mut().enumerate() {
803 let px = col as f32 + 0.5 - cx;
804 // Signed distance to the edge in pixels, negative inside.
805 let sd = if ellipse {
806 if hw <= 0.0 || hh <= 0.0 {
807 f32::INFINITY
808 } else {
809 let n = ((px / hw).powi(2) + (py / hh).powi(2)).sqrt();
810 (n - 1.0) * hw.min(hh)
811 }
812 } else {
813 let (qx, qy) = (px.abs() - hw, py.abs() - hh);
814 (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0)
815 };
816 let mut m = match feather > 0.0 {
817 true => (0.5 - sd / feather).clamp(0.0, 1.0),
818 false => f32::from(u8::from(sd <= 0.0)),
819 };
820 if invert {
821 m = 1.0 - m;
822 }
823 *a = mul255(*a, (m * 255.0).round() as u8);
824 }
825 }
826}
827
828/// `top` laid over `base` in place, where `cover` (luma-sized, 0..=255) says the
829/// clip shows, at strength `k`, in `mode`. Normal mode is a straight mix of the
830/// samples; the others are worked on RGB through `matrix`. Chroma takes the
831/// coverage and the blend of its block's top-left luma sample.
832#[expect(clippy::too_many_arguments, reason = "two pictures, their cover and how they meet")]
833pub fn blend_over<T: Sample>(
834 base: (&mut [T], &mut [T], &mut [T]),
835 top: (&[T], &[T], &[T]),
836 cover: &[u8],
837 k: f32,
838 mode: BlendMode,
839 matrix: Matrix,
840 w: usize,
841 h: usize,
842) {
843 let (by, bu, bv) = base;
844 let (ty, tu, tv) = top;
845 let (cw, ch) = chroma_dims(w, h);
846 let mix = |b: T, t: f32, a: f32| T::from_f32(b.code() as f32 + (t - b.code() as f32) * a);
847 if mode == BlendMode::Normal {
848 for (i, (b, t)) in by.iter_mut().zip(ty).enumerate() {
849 let a = f32::from(cover[i]) / 255.0 * k;
850 if a > 0.0 {
851 *b = mix(*b, t.code() as f32, a);
852 }
853 }
854 for i in 0..cw * ch {
855 let (cx, cy) = (i % cw, i / cw);
856 let a = f32::from(cover[2 * cy * w + 2 * cx]) / 255.0 * k;
857 if a > 0.0 {
858 bu[i] = mix(bu[i], tu[i].code() as f32, a);
859 bv[i] = mix(bv[i], tv[i].code() as f32, a);
860 }
861 }
862 return;
863 }
864 let wts = weights(matrix);
865 let d = depth::<T>();
866 for cy in 0..ch {
867 for cx in 0..cw {
868 let ci = cy * cw + cx;
869 let (bu8, bv8) = (bu[ci].code() as f32 / d, bv[ci].code() as f32 / d);
870 let (tu8, tv8) = (tu[ci].code() as f32 / d, tv[ci].code() as f32 / d);
871 let mut chroma = None;
872 for (oy, ox) in [(0, 0), (0, 1), (1, 0), (1, 1)] {
873 let (ly, lx) = (2 * cy + oy, 2 * cx + ox);
874 if ly >= h || lx >= w {
875 continue;
876 }
877 let i = ly * w + lx;
878 let a = f32::from(cover[i]) / 255.0 * k;
879 if a <= 0.0 {
880 continue;
881 }
882 let b = to_rgb(by[i].code() as f32 / d, bu8, bv8, wts);
883 let t = to_rgb(ty[i].code() as f32 / d, tu8, tv8, wts);
884 let out = [0, 1, 2].map(|c| b[c] + (mode.mix(b[c], t[c]) - b[c]) * a);
885 let (yy, uu, vv) = to_yuv(out, wts);
886 by[i] = T::from_f32(yy * d);
887 if (oy, ox) == (0, 0) {
888 chroma = Some((uu, vv));
889 }
890 }
891 if let Some((uu, vv)) = chroma {
892 bu[ci] = T::from_f32(uu * d);
893 bv[ci] = T::from_f32(vv * d);
894 }
895 }
896 }
897}
898
899/// Lays a picture whose stack composites ([`Composite::composites`]) over black,
900/// in place: what a clip with nothing beneath it shows -- a keyed or masked
901/// clip's cut-outs go black, and a blend meets the black a gap is.
902pub fn over_black<T: Sample>(planes: (&mut [T], &mut [T], &mut [T]), out: &Composite, matrix: Matrix, w: usize, h: usize) {
903 if !out.composites() {
904 return;
905 }
906 let (y, u, v) = planes;
907 let top = (y.to_vec(), u.to_vec(), v.to_vec());
908 y.fill(T::BLACK);
909 u.fill(T::NEUTRAL);
910 v.fill(T::NEUTRAL);
911 let full;
912 let cover = match out.alpha.as_deref() {
913 Some(a) => a,
914 None => {
915 full = vec![255u8; w * h];
916 &full
917 }
918 };
919 blend_over((y, u, v), (&top.0, &top.1, &top.2), cover, 1.0, out.mode, matrix, w, h);
920}
921
922#[cfg(test)]
923mod tests {
924 use super::*;
925
926 fn flat<T: Sample>(w: usize, h: usize, y: u32, u: u32, v: u32) -> (Vec<T>, Vec<T>, Vec<T>) {
927 let (cw, ch) = chroma_dims(w, h);
928 (
929 vec![T::from_code(y); w * h],
930 vec![T::from_code(u); cw * ch],
931 vec![T::from_code(v); cw * ch],
932 )
933 }
934
935 fn run<T: Sample>(fx: &[Effect], p: &mut (Vec<T>, Vec<T>, Vec<T>), w: usize, h: usize, secs: f64) -> Composite {
936 let mut s = Scratch::default();
937 apply(fx, (&mut p.0, &mut p.1, &mut p.2), w, h, secs, secs, Matrix::Bt709, &mut s)
938 }
939
940 #[test]
941 fn an_empty_or_switched_off_stack_touches_nothing() {
942 let (w, h) = (64, 36);
943 let mut p = flat::<u8>(w, h, 0, 0, 0);
944 for (i, s) in p.0.iter_mut().enumerate() {
945 *s = (i * 7 % 251) as u8;
946 }
947 let before = p.clone();
948 assert_eq!(run(&[], &mut p, w, h, 0.0), Composite::default());
949 let off: Vec<Effect> = EffectKind::ALL
950 .into_iter()
951 .map(|k| Effect { on: false, ..Effect::new(k) })
952 .collect();
953 assert!(!active(&off));
954 assert_eq!(run(&off, &mut p, w, h, 0.0), Composite::default());
955 assert_eq!(p, before, "not a sample moved");
956 }
957
958 #[test]
959 fn the_kernel_sums_to_one_and_a_flat_field_stays_flat() {
960 for r in [0.6, 1.0, 2.5, 10.0, 47.0] {
961 assert_eq!(kernel(r).iter().sum::<u32>(), 1 << SHIFT, "r={r}");
962 }
963 let (w, h) = (96, 54);
964 let mut p = flat::<u16>(w, h, 700, 300, 800);
965 run(&[Effect::new(EffectKind::Blur)], &mut p, w, h, 0.0);
966 assert!(p.0.iter().all(|&s| s == 700) && p.1.iter().all(|&s| s == 300));
967 }
968
969 #[test]
970 fn blur_spreads_an_edge_and_matches_at_both_depths() {
971 let (w, h) = (200, 108);
972 let mut a = flat::<u8>(w, h, 16, 128, 128);
973 let mut b = flat::<u16>(w, h, 64, 512, 512);
974 for row in 0..h {
975 for col in w / 2..w {
976 a.0[row * w + col] = 235;
977 b.0[row * w + col] = 940;
978 }
979 }
980 let mut fx = Effect::new(EffectKind::Blur);
981 fx.set("radius", 50.0).unwrap();
982 run(std::slice::from_ref(&fx), &mut a, w, h, 0.0);
983 run(std::slice::from_ref(&fx), &mut b, w, h, 0.0);
984 let mid = h / 2 * w;
985 assert!(a.0[mid + w / 2 - 2] > 30 && a.0[mid + w / 2 + 1] < 220, "the edge is soft");
986 assert_eq!(a.0[mid], 16, "far from the edge stays put");
987 for col in 0..w {
988 let (x, y) = (f32::from(a.0[mid + col]), f32::from(b.0[mid + col]) / 4.0);
989 assert!((x - y).abs() <= 1.0, "col {col}: {x} vs {y}");
990 }
991 }
992
993 #[test]
994 fn vignette_darkens_the_corners_and_not_the_centre() {
995 let (w, h) = (160, 90);
996 let mut p = flat::<u8>(w, h, 200, 160, 100);
997 run(&[Effect::new(EffectKind::Vignette)], &mut p, w, h, 0.0);
998 assert_eq!(p.0[h / 2 * w + w / 2], 200);
999 assert!(p.0[0] < 140, "corner {}", p.0[0]);
1000 assert!(p.1[0] < 160 && p.1[0] > 128, "the corner's tint fades toward grey");
1001 }
1002
1003 #[test]
1004 fn sharpen_and_glow_lift_what_they_should() {
1005 let (w, h) = (64, 64);
1006 let mut p = flat::<u8>(w, h, 100, 128, 128);
1007 p.0[32 * w + 32] = 150;
1008 run(&[Effect::new(EffectKind::Sharpen)], &mut p, w, h, 0.0);
1009 assert!(p.0[32 * w + 32] > 150, "a peak is pushed further");
1010 let (w, h) = (64, 540);
1011 let mut g = flat::<u8>(w, h, 30, 128, 128);
1012 for row in 268..272 {
1013 for i in 30..34 {
1014 g.0[row * w + i] = 235;
1015 }
1016 }
1017 let mut fx = Effect::new(EffectKind::Glow);
1018 fx.set("amount", 2.0).unwrap();
1019 run(std::slice::from_ref(&fx), &mut g, w, h, 0.0);
1020 assert!(g.0[270 * w + 27] > 30, "light spills round a bright spot");
1021 assert_eq!(g.0[0], 30, "dark stays dark");
1022 }
1023
1024 #[test]
1025 fn shake_is_seeded_smooth_and_deterministic() {
1026 let a: Vec<_> = (0..50).map(|f| shake_offset(20.0, 4.0, 7, f as f64 / 25.0)).collect();
1027 let b: Vec<_> = (0..50).map(|f| shake_offset(20.0, 4.0, 7, f as f64 / 25.0)).collect();
1028 let c: Vec<_> = (0..50).map(|f| shake_offset(20.0, 4.0, 8, f as f64 / 25.0)).collect();
1029 assert_eq!(a, b);
1030 assert_ne!(a, c, "another pattern moves otherwise");
1031 assert!(a.iter().any(|&(x, y)| x != 0 || y != 0));
1032 assert!(a.iter().all(|&(x, y)| x.abs() <= 20 && y.abs() <= 20 && x % 2 == 0 && y % 2 == 0));
1033 assert!(a.windows(2).all(|p| (p[0].0 - p[1].0).abs() <= 12), "smooth, not jumping");
1034 let (w, h) = (64, 36);
1035 let mut p = flat::<u8>(w, h, 50, 128, 128);
1036 for (i, s) in p.0.iter_mut().enumerate() {
1037 *s = (i % w) as u8;
1038 }
1039 let mut fx = Effect::new(EffectKind::Shake);
1040 fx.set("amount", 100.0).unwrap();
1041 let mut q = p.clone();
1042 run(std::slice::from_ref(&fx), &mut q, w, h, 0.3);
1043 let (dx, _) = shake_offset(100.0 * h as f32 / 1080.0, 4.0, 1, 0.3);
1044 assert_eq!(q.0[w + 10], (10 - dx).clamp(0, w as i32 - 1) as u8);
1045 }
1046
1047 #[test]
1048 fn a_green_key_cuts_out_green_and_keeps_the_rest() {
1049 let (w, h) = (16, 8);
1050 let (_, gu, gv) = to_yuv([0.0, 1.0, 0.0], weights(Matrix::Bt709));
1051 let (_, ru, rv) = to_yuv([1.0, 0.2, 0.2], weights(Matrix::Bt709));
1052 let mut p = flat::<u8>(w, h, 150, gu.round() as u32, gv.round() as u32);
1053 let cw = w / 2;
1054 for row in 0..h / 2 {
1055 for col in cw / 2..cw {
1056 p.1[row * cw + col] = ru.round() as u8;
1057 p.2[row * cw + col] = rv.round() as u8;
1058 }
1059 }
1060 let out = run(&[Effect::new(EffectKind::ChromaKey)], &mut p, w, h, 0.0);
1061 let a = out.alpha.expect("a key makes a cover");
1062 assert_eq!(a[0], 0, "green is gone");
1063 assert_eq!(a[w - 1], 255, "red stays");
1064 }
1065
1066 #[test]
1067 fn masks_cover_their_shape_feathered_and_inverted() {
1068 let (w, h) = (100, 100);
1069 let mut p = flat::<u8>(w, h, 100, 128, 128);
1070 let out = run(&[Effect::new(EffectKind::RectMask)], &mut p, w, h, 0.0);
1071 let a = out.alpha.unwrap();
1072 assert_eq!(a[50 * w + 50], 255);
1073 assert_eq!(a[5 * w + 5], 0);
1074 assert!(a[50 * w + 25] > 60 && a[50 * w + 25] < 200, "the edge is soft: {}", a[50 * w + 25]);
1075 let mut fx = Effect::new(EffectKind::EllipseMask);
1076 fx.set("invert", 1.0).unwrap();
1077 fx.set("feather", 0.0).unwrap();
1078 let a = run(std::slice::from_ref(&fx), &mut p, w, h, 0.0).alpha.unwrap();
1079 assert_eq!((a[50 * w + 50], a[0], a[26 * w + 26]), (0, 255, 255), "a corner of the box is outside the ellipse");
1080 }
1081
1082 #[test]
1083 fn pixelate_makes_each_block_one_value_and_a_mask_limits_it() {
1084 let (w, h) = (1920, 1080);
1085 let mut p = flat::<u8>(w, h, 0, 128, 128);
1086 for (i, s) in p.0.iter_mut().enumerate() {
1087 *s = (i % 251) as u8;
1088 }
1089 let mut fx = Effect::new(EffectKind::Pixelate);
1090 fx.set("size", 16.0).unwrap();
1091 run(std::slice::from_ref(&fx), &mut p, w, h, 0.0);
1092 for (bx, by) in [(0, 0), (16, 16)] {
1093 let first = p.0[by * w + bx];
1094 for row in by..by + 16 {
1095 assert!(p.0[row * w + bx..row * w + bx + 16].iter().all(|&s| s == first), "block at {bx},{by}");
1096 }
1097 }
1098 // Limited to an ellipse that covers only the middle of the frame: the corner keeps its samples.
1099 let mut q = flat::<u8>(w, h, 0, 128, 128);
1100 for (i, s) in q.0.iter_mut().enumerate() {
1101 *s = (i % 251) as u8;
1102 }
1103 let orig = q.0.clone();
1104 let mut e = Effect::new(EffectKind::EllipseMask);
1105 e.set("width", 0.2).unwrap();
1106 e.set("height", 0.2).unwrap();
1107 run(&[fx, e], &mut q, w, h, 0.0);
1108 assert_eq!(q.0[0], orig[0], "outside the mask the picture is as it was");
1109 assert_ne!(q.0[540 * w + 960], orig[540 * w + 960], "inside it is mosaiced");
1110 }
1111
1112 #[test]
1113 fn blend_modes_meet_grey_as_their_formulas_say() {
1114 let (w, h) = (4, 4);
1115 let grey = |y| flat::<u8>(w, h, y, 128, 128);
1116 let mid = 16 + 219 / 2;
1117 let cover = vec![255u8; w * h];
1118 let at = |mode, b: u32, t: u32| {
1119 let mut base = grey(b);
1120 let top = grey(t);
1121 blend_over((&mut base.0, &mut base.1, &mut base.2), (&top.0, &top.1, &top.2), &cover, 1.0, mode, Matrix::Bt709, w, h);
1122 base.0[0]
1123 };
1124 assert_eq!(at(BlendMode::Normal, 16, 200), 200);
1125 assert_eq!(at(BlendMode::Multiply, 235, mid), mid as u8);
1126 assert_eq!(at(BlendMode::Multiply, 16, 235), 16);
1127 assert_eq!(at(BlendMode::Screen, 16, mid), mid as u8);
1128 assert_eq!(at(BlendMode::Screen, 235, 16), 235);
1129 assert_eq!(at(BlendMode::Add, mid, mid), 234);
1130 assert_eq!(at(BlendMode::Darken, 100, 200), 100);
1131 assert_eq!(at(BlendMode::Lighten, 100, 200), 200);
1132 assert!(at(BlendMode::Overlay, 60, 200) < at(BlendMode::Screen, 60, 200));
1133 }
1134
1135 #[test]
1136 fn over_black_shows_a_cut_out_as_black() {
1137 let (w, h) = (100, 100);
1138 let mut p = flat::<u16>(w, h, 800, 600, 400);
1139 let out = run(&[Effect::new(EffectKind::EllipseMask)], &mut p, w, h, 0.0);
1140 over_black((&mut p.0, &mut p.1, &mut p.2), &out, Matrix::Bt709, w, h);
1141 assert_eq!((p.0[0], p.1[0]), (64, 512));
1142 assert_eq!(p.0[50 * w + 50], 800);
1143 }
1144
1145 #[test]
1146 fn a_mask_key_track_is_interpolated_at_the_frame_shown() {
1147 use crate::transform::KeyEase;
1148 let key = |at, x| MaskKey { at, x, y: 0.5, width: 0.2, height: 0.2, feather: 0.0, ease: KeyEase::Linear };
1149 let mut fx = Effect::new(EffectKind::RectMask);
1150 fx.keys = vec![key(0, 0.2), key(100, 0.8)];
1151 assert!((fx.posed(50.0).get("x").unwrap() - 0.5).abs() < 1e-6, "halfway between the keys");
1152 assert_eq!(fx.posed(-5.0).get("x"), Some(0.2), "held before the first key");
1153 assert_eq!(fx.posed(300.0).get("x"), Some(0.8), "held after the last key");
1154 assert!(animated(std::slice::from_ref(&fx)), "a keyed mask redraws as the frames change");
1155 }
1156
1157 #[test]
1158 fn set_clamps_and_names_what_there_is() {
1159 let mut e = Effect::new(EffectKind::Vignette);
1160 e.set("amount", 9.0).unwrap();
1161 assert_eq!(e.get("amount"), Some(1.0));
1162 let err = e.set("radius", 1.0).unwrap_err();
1163 assert!(err.contains("amount, softness"), "{err}");
1164 assert!(e.set("amount", f32::NAN).is_err());
1165 }
1166
1167 /// The perf note's number: one 1080p frame through a radius-10 blur.
1168 #[test]
1169 #[ignore = "a timing, run by hand: cargo test --release -p engine blur_1080p_timing -- --ignored --nocapture"]
1170 fn blur_1080p_timing() {
1171 let (w, h) = (1920, 1080);
1172 let mut p = flat::<u8>(w, h, 100, 128, 128);
1173 for (i, s) in p.0.iter_mut().enumerate() {
1174 *s = (i * 13 % 219 + 16) as u8;
1175 }
1176 let mut fx = Effect::new(EffectKind::Blur);
1177 fx.set("radius", 10.0).unwrap();
1178 let mut s = Scratch::default();
1179 let mut s16 = Scratch::default();
1180 let mut q = flat::<u16>(w, h, 400, 512, 512);
1181 for _ in 0..3 {
1182 apply(std::slice::from_ref(&fx), (&mut p.0, &mut p.1, &mut p.2), w, h, 0.0, 0.0, Matrix::Bt709, &mut s);
1183 }
1184 let n = 20;
1185 let t = std::time::Instant::now();
1186 for _ in 0..n {
1187 apply(std::slice::from_ref(&fx), (&mut p.0, &mut p.1, &mut p.2), w, h, 0.0, 0.0, Matrix::Bt709, &mut s);
1188 }
1189 let ms8 = t.elapsed().as_secs_f64() * 1000.0 / n as f64;
1190 let t = std::time::Instant::now();
1191 for _ in 0..n {
1192 apply(std::slice::from_ref(&fx), (&mut q.0, &mut q.1, &mut q.2), w, h, 0.0, 0.0, Matrix::Bt709, &mut s16);
1193 }
1194 let ms16 = t.elapsed().as_secs_f64() * 1000.0 / n as f64;
1195 println!("blur r=10 1080p: {ms8:.2} ms/frame 8-bit, {ms16:.2} ms/frame 10-bit");
1196 }
1197}