Skip to main content

alpha2_render/
masking.rs

1//! Internal effects behind clip shape masks, track mattes and key mixes.
2//!
3//! The timeline engine inserts these from a clip's `masks` and `matte`. Mask outlines are drawn
4//! as coverage by the vector pass and feathered by the Gaussian blur; these passes combine the
5//! coverages and apply them to the clip.
6
7use std::fmt::Write as _;
8
9use alpha2_gpu::CapabilityTier;
10
11use crate::{EffectDef, EffectKind, InputSpec, ParamSpec, ParamType, ParamUnit, ParamValue};
12
13/// Internal identifier of the track-matte pass.
14pub const TRACK_MATTE_EFFECT_ID: &str = "alpha2.internal.track-matte";
15
16/// Internal identifier of the key-mix pass whose coverage is its opacity times a mask's alpha.
17pub const KEY_MIX_EFFECT_ID: &str = "alpha2.internal.key-mix";
18
19/// Internal identifier of the key-mix pass whose coverage is its opacity alone.
20pub const KEY_MIX_UNMASKED_EFFECT_ID: &str = "alpha2.internal.key-mix-unmasked";
21
22/// Named input of a key-mix pass holding the picture its source replaces.
23pub const KEY_MIX_BACKDROP: &str = "backdrop";
24
25/// Named input of [`KEY_MIX_EFFECT_ID`] whose alpha scales the coverage.
26pub const KEY_MIX_MASK: &str = "mask";
27
28/// Parameter of a key-mix pass scaling the coverage, in `0..=1`.
29pub const KEY_MIX_OPACITY: &str = "opacity";
30
31/// Most masks one mask-combine pass takes, each a named input.
32pub const MAX_SHAPE_MASKS: usize = 8;
33
34const _: () = assert!(MAX_SHAPE_MASKS <= crate::MAX_EFFECT_INPUTS);
35
36/// Enum values of a mask's `mode{i}` parameter.
37pub const MASK_MODES: [&str; 3] = ["add", "subtract", "intersect"];
38
39/// Mask-combine pass ids; the pass for `n` masks is `MASK_COMBINE_EFFECT_IDS[n - 1]`.
40pub const MASK_COMBINE_EFFECT_IDS: [&str; MAX_SHAPE_MASKS] = [
41    "alpha2.internal.mask-combine-1",
42    "alpha2.internal.mask-combine-2",
43    "alpha2.internal.mask-combine-3",
44    "alpha2.internal.mask-combine-4",
45    "alpha2.internal.mask-combine-5",
46    "alpha2.internal.mask-combine-6",
47    "alpha2.internal.mask-combine-7",
48    "alpha2.internal.mask-combine-8",
49];
50
51/// Names of one mask's coverage input and parameters in [`mask_combine_definition`].
52#[derive(Copy, Clone, Debug, Eq, PartialEq)]
53pub struct MaskCombineNames {
54    /// Named input with the mask's coverage in alpha: `m{i}`.
55    pub input: &'static str,
56    /// `invert{i}`.
57    pub invert: &'static str,
58    /// `mode{i}`.
59    pub mode: &'static str,
60}
61
62macro_rules! mask_combine_names {
63    ($($index:literal),*) => {
64        [$(MaskCombineNames {
65            input: concat!("m", $index),
66            invert: concat!("invert", $index),
67            mode: concat!("mode", $index),
68        }),*]
69    };
70}
71
72/// Each mask's names by index, static so callers need not format them.
73pub const MASK_COMBINE_NAMES: [MaskCombineNames; MAX_SHAPE_MASKS] =
74    mask_combine_names!(0, 1, 2, 3, 4, 5, 6, 7);
75
76fn param(name: String, param_type: ParamType, default: ParamValue) -> ParamSpec {
77    ParamSpec {
78        name,
79        param_type,
80        default,
81        min: None,
82        max: None,
83        step: None,
84        unit: match param_type {
85            ParamType::Bool => ParamUnit::Bool,
86            ParamType::Enum => ParamUnit::Enum,
87            _ => ParamUnit::Normalized,
88        },
89        enum_values: if param_type == ParamType::Enum {
90            MASK_MODES.map(str::to_owned).to_vec()
91        } else {
92            Vec::new()
93        },
94    }
95}
96
97/// The pass combining `count` masks (1 to [`MAX_SHAPE_MASKS`]) into its source's coverage.
98///
99/// Mask `i` is input `m{i}` (coverage in alpha), inverted when `invert{i}` is set, and combined
100/// by `mode{i}`: coverage starts empty when the first mask adds and full otherwise; add is
101/// `c + m - c m`, subtract `c (1 - m)`, intersect `c m`. The source is multiplied by the result.
102///
103/// # Panics
104/// When `count` is zero or more than [`MAX_SHAPE_MASKS`].
105#[must_use]
106pub fn mask_combine_definition(count: usize) -> EffectDef {
107    assert!(
108        (1..=MAX_SHAPE_MASKS).contains(&count),
109        "a mask-combine pass takes 1 to {MAX_SHAPE_MASKS} masks"
110    );
111    let names = &MASK_COMBINE_NAMES[..count];
112    let mut params = Vec::with_capacity(count * 2);
113    let mut steps = String::new();
114    for names in names {
115        params.push(param(
116            names.invert.into(),
117            ParamType::Bool,
118            ParamValue::Bool(false),
119        ));
120        params.push(param(
121            names.mode.into(),
122            ParamType::Enum,
123            ParamValue::Enum(0),
124        ));
125        writeln!(
126            steps,
127            "    coverage = builtin_mask_step(coverage, sample_{input}(uv).a, params.{invert}, params.{mode});",
128            input = names.input,
129            invert = names.invert,
130            mode = names.mode,
131        )
132        .expect("writing to a String cannot fail");
133    }
134    EffectDef {
135        id: MASK_COMBINE_EFFECT_IDS[count - 1].into(),
136        version: 1,
137        kind: EffectKind::Effect,
138        inputs: names
139            .iter()
140            .map(|names| InputSpec {
141                name: names.input.into(),
142            })
143            .collect(),
144        params,
145        resources: Vec::new(),
146        wgsl_body: format!(
147            r"fn builtin_mask_step(coverage: f32, mask: f32, invert: u32, mode: u32) -> f32 {{
148    var m = clamp(mask, 0.0, 1.0);
149    if (invert != 0u) {{ m = 1.0 - m; }}
150    if (mode == 1u) {{ return coverage * (1.0 - m); }}
151    if (mode == 2u) {{ return coverage * m; }}
152    return coverage + m - coverage * m;
153}}
154
155fn effect(uv: vec2f, src: vec4f) -> vec4f {{
156    // Empty when the first mask adds, full otherwise.
157    var coverage = select(1.0, 0.0, params.mode0 == 0u);
158{steps}    return src * clamp(coverage, 0.0, 1.0);
159}}
160"
161        ),
162        tier_min: CapabilityTier::TierB,
163        license: Some(crate::builtins::ALPHA2_EFFECT_LICENSE.into()),
164    }
165}
166
167/// Every mask-combine pass, for one to [`MAX_SHAPE_MASKS`] masks.
168#[must_use]
169pub fn mask_combine_definitions() -> Vec<EffectDef> {
170    (1..=MAX_SHAPE_MASKS).map(mask_combine_definition).collect()
171}
172
173/// The track-matte pass: keeps the first input where the second's alpha (or luminance over
174/// black, BT.709 weights on linear light times alpha) says, optionally inverted.
175///
176/// A two-input transition that ignores progress; pass a value inside `(0, 1)` so its body runs.
177#[must_use]
178pub fn track_matte_definition() -> EffectDef {
179    EffectDef {
180        id: TRACK_MATTE_EFFECT_ID.into(),
181        version: 1,
182        kind: EffectKind::Transition,
183        inputs: Vec::new(),
184        params: vec![
185            ParamSpec {
186                unit: ParamUnit::Bool,
187                ..param("luma".into(), ParamType::Bool, ParamValue::Bool(false))
188            },
189            ParamSpec {
190                unit: ParamUnit::Bool,
191                ..param("inverted".into(), ParamType::Bool, ParamValue::Bool(false))
192            },
193        ],
194        resources: Vec::new(),
195        wgsl_body: r"fn builtin_matte_linear(value: f32) -> f32 {
196    if (value <= 0.04045) { return value / 12.92; }
197    return pow((value + 0.055) / 1.055, 2.4);
198}
199
200fn transition(uv: vec2f) -> vec4f {
201    let picture = from_color(uv);
202    let matte = to_color(uv);
203    var coverage = matte.a;
204    if (params.luma != 0u) {
205        let straight = clamp(matte.rgb / max(matte.a, 0.000001), vec3f(0.0), vec3f(1.0));
206        let linear = vec3f(
207            builtin_matte_linear(straight.r),
208            builtin_matte_linear(straight.g),
209            builtin_matte_linear(straight.b),
210        );
211        coverage = dot(linear, vec3f(0.2126, 0.7152, 0.0722)) * matte.a;
212    }
213    if (params.inverted != 0u) { coverage = 1.0 - coverage; }
214    return picture * clamp(coverage, 0.0, 1.0);
215}
216"
217        .into(),
218        tier_min: CapabilityTier::TierB,
219        license: Some(crate::builtins::ALPHA2_EFFECT_LICENSE.into()),
220    }
221}
222
223/// A key-mix pass: the `backdrop` input replaced by the source by `k = opacity x mask.a`
224/// (`k = opacity` when not `masked`), as `(1 - k) backdrop + k source` on premultiplied values,
225/// exactly the backdrop at `k = 0` and the source at `k = 1`.
226#[must_use]
227pub fn key_mix_definition(masked: bool) -> EffectDef {
228    let (id, coverage) = if masked {
229        (
230            KEY_MIX_EFFECT_ID,
231            format!("params.{KEY_MIX_OPACITY} * sample_{KEY_MIX_MASK}(uv).a"),
232        )
233    } else {
234        (
235            KEY_MIX_UNMASKED_EFFECT_ID,
236            format!("params.{KEY_MIX_OPACITY}"),
237        )
238    };
239    let inputs = std::iter::once(KEY_MIX_BACKDROP)
240        .chain(masked.then_some(KEY_MIX_MASK))
241        .map(|name| InputSpec { name: name.into() })
242        .collect();
243    EffectDef {
244        id: id.into(),
245        version: 1,
246        kind: EffectKind::Effect,
247        inputs,
248        params: vec![ParamSpec {
249            min: Some(0.0),
250            max: Some(1.0),
251            ..param(
252                KEY_MIX_OPACITY.into(),
253                ParamType::Float,
254                ParamValue::Float(1.0),
255            )
256        }],
257        resources: Vec::new(),
258        wgsl_body: format!(
259            "{}\nfn effect(uv: vec2f, src: vec4f) -> vec4f {{\n    \
260             return builtin_key_mix(sample_{KEY_MIX_BACKDROP}(uv), src, {coverage});\n}}\n",
261            alpha2_shaders::KEY_MIX
262        ),
263        tier_min: CapabilityTier::TierB,
264        license: Some(crate::builtins::ALPHA2_EFFECT_LICENSE.into()),
265    }
266}
267
268/// Both key-mix passes, with and without a mask.
269#[must_use]
270pub fn key_mix_definitions() -> [EffectDef; 2] {
271    [key_mix_definition(true), key_mix_definition(false)]
272}
273
274#[cfg(test)]
275mod tests {
276    use super::{
277        MASK_COMBINE_EFFECT_IDS, MASK_COMBINE_NAMES, MAX_SHAPE_MASKS, mask_combine_definition,
278    };
279
280    #[test]
281    fn each_masks_static_names_are_the_ones_the_pass_declares() {
282        for count in 1..=MAX_SHAPE_MASKS {
283            let definition = mask_combine_definition(count);
284            assert_eq!(definition.id, MASK_COMBINE_EFFECT_IDS[count - 1]);
285            let params = definition
286                .params
287                .iter()
288                .map(|spec| spec.name.clone())
289                .collect::<Vec<_>>();
290            let inputs = definition
291                .inputs
292                .iter()
293                .map(|input| input.name.clone())
294                .collect::<Vec<_>>();
295            let mut expected_params = Vec::new();
296            let mut expected_inputs = Vec::new();
297            for (index, names) in MASK_COMBINE_NAMES[..count].iter().enumerate() {
298                assert_eq!(names.input, format!("m{index}"));
299                assert_eq!(names.invert, format!("invert{index}"));
300                assert_eq!(names.mode, format!("mode{index}"));
301                expected_inputs.push(names.input.to_owned());
302                expected_params.push(names.invert.to_owned());
303                expected_params.push(names.mode.to_owned());
304            }
305            assert_eq!(inputs, expected_inputs);
306            assert_eq!(params, expected_params);
307        }
308    }
309}