forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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