The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
feat(mask): a clip keeps a shape of its picture - line, mirror, circle, rectangle, heart or star - feathered, inverted and keyed (#239)
Jareer16a3d1395664
diff --git a/src/crates/concat-api/src/lib.rs b/src/crates/concat-api/src/lib.rsindex 3520feb7..0845a3dc 100644--- a/src/crates/concat-api/src/lib.rs+++ b/src/crates/concat-api/src/lib.rs@@ -1214,6 +1214,50 @@ mod tests {assert_eq!(recents[0].name, "Round trip");}+ /// A clip's mask over the wire, as a caller writes it: put on through+ /// `updateClip`'s patch, its numbers keyed through `setClipKey`, and+ /// read back in the project the reply carries (#239).+ #[test]+ fn a_mask_is_set_and_keyed_through_the_api() {+ let (mut api, scratch, _) = api();+ let path = project(&mut api, &scratch, "Masked");+ let added = view(ok(api.dispatch(Request::EditApply {+ path: path.clone(),+ command: Box::new(Command::AddMedia {+ item: still("/nowhere/still.png"),+ }),+ })));+ let placed = view(ok(api.dispatch(Request::EditApply {+ path: path.clone(),+ command: Box::new(Command::AddClipAtFirstFree {+ media_id: added.created_id.expect("minted"),+ start: 0.0,+ }),+ })));+ let clip_id = placed.project.active().clips[0].id.clone();+ for command in [+ json!({ "op": "updateClip", "clipId": clip_id,+ "patch": { "mask": { "shape": "star", "feather": 0.3, "invert": true } } }),+ json!({ "op": "setClipKey", "clipId": clip_id, "property": "maskWidth",+ "at": 0.0, "value": 0.2 }),+ json!({ "op": "setClipKey", "clipId": clip_id, "property": "maskWidth",+ "at": 1.0, "value": 1.2 }),+ ] {+ let request: Request = serde_json::from_value(json!({+ "method": "edit.apply", "path": path, "command": command+ }))+ .expect("parses");+ ok(api.dispatch(request));+ }+ let got = view(ok(api.dispatch(Request::ProjectGet { path })));+ let clip = &got.project.active().clips[0];+ let mask = clip.mask.expect("a mask");+ assert_eq!(mask.shape, concat_project::model::MaskShape::Star);+ assert!(mask.invert && (mask.feather - 0.3).abs() < 1e-12);+ let width = clip.value_at(concat_project::model::KeyProperty::MaskWidth, 0.5);+ assert!((width - 0.7).abs() < 1e-12, "the key rides: {width}");+ }+#[test]fn a_refusal_is_the_command_layers_sentence_with_its_code() {let (mut api, scratch, _) = api();diff --git a/src/crates/concat-core/src/animate.rs b/src/crates/concat-core/src/animate.rsindex 88ede256..4b144b68 100644--- a/src/crates/concat-core/src/animate.rs+++ b/src/crates/concat-core/src/animate.rs@@ -14,6 +14,7 @@//! This is the one place the per-frame arithmetic lives; the plan asks the//! clip, and the clip asks here.+use crate::mask::ShapeMask;use crate::timeline::Transform;/// How a key is approached from the one before it: a CSS timing function,@@ -244,6 +245,58 @@ pub struct Animation {/// clip - so it is a track here and not a second mechanism somewhere/// else. Nothing in the compositor reads it; the mixer does.pub volume: Track,+ /// The mask's numbers, when they ride. Unlike the placement's these+ /// are absolute - a key is the value itself, not a factor or an+ /// addition - since a mask is the clip's own and has no preset to be+ /// relative for.+ pub mask: MaskTracks,+}++/// The keys of a mask's numbers; see [`ShapeMask`] for what each is.+#[derive(Clone, PartialEq, Debug, Default)]+pub struct MaskTracks {+ /// The centre across.+ pub x: Track,+ /// The centre down.+ pub y: Track,+ /// The box's width.+ pub width: Track,+ /// The box's height.+ pub height: Track,+ /// The turn, in degrees.+ pub rotation: Track,+ /// The corners' roundness.+ pub roundness: Track,+ /// The edge's softness.+ pub feather: Track,+}++impl MaskTracks {+ /// True when no number has a key.+ pub fn is_empty(&self) -> bool {+ self.x.is_empty()+ && self.y.is_empty()+ && self.width.is_empty()+ && self.height.is_empty()+ && self.rotation.is_empty()+ && self.roundness.is_empty()+ && self.feather.is_empty()+ }++ /// `base` at `x`, a fraction of the clip: each keyed number its ride's+ /// value there, the rest as they are.+ pub fn mask_at(&self, base: ShapeMask, x: f64) -> ShapeMask {+ ShapeMask {+ x: self.x.value_at(x, base.x),+ y: self.y.value_at(x, base.y),+ width: self.width.value_at(x, base.width).max(0.001),+ height: self.height.value_at(x, base.height).max(0.001),+ rotation: self.rotation.value_at(x, base.rotation),+ roundness: self.roundness.value_at(x, base.roundness).clamp(0.0, 1.0),+ feather: self.feather.value_at(x, base.feather).clamp(0.0, 1.0),+ ..base+ }+ }}impl Animation {@@ -255,6 +308,7 @@ impl Animation {&& self.rotation.is_empty()&& self.opacity.is_empty()&& self.volume.is_empty()+ && self.mask.is_empty()}/// The clip's transform at `x`, a fraction of its length.@@ -343,6 +397,33 @@ mod tests {assert!(Animation::default().is_empty());}+ #[test]+ fn a_mask_rides_its_keys_absolutely() {+ let mut animation = Animation::default();+ animation.mask.width = Track::new(vec![+ key(0.0, 0.2, Ease::LINEAR),+ key(1.0, 0.6, Ease::LINEAR),+ ]);+ animation.mask.feather = Track::new(vec![+ key(0.0, 0.0, Ease::LINEAR),+ key(0.5, 2.0, Ease::LINEAR),+ ]);+ assert!(!animation.is_empty());+ let base = ShapeMask {+ width: 5.0,+ x: 0.1,+ ..ShapeMask::default()+ };+ let mid = animation.mask.mask_at(base, 0.5);+ assert!(+ (mid.width - 0.4).abs() < 1e-12,+ "the key, not a factor on 5"+ );+ assert_eq!(mid.x, 0.1, "an unkeyed number is the base's");+ assert_eq!(mid.feather, 1.0, "held to its range");+ assert!((animation.mask.mask_at(base, 0.25).feather - 1.0).abs() < 1e-12);+ }+#[test]fn the_eases_bend_the_way_their_names_say() {// The endpoints are pinned whatever the control points are.diff --git a/src/crates/concat-core/src/lib.rs b/src/crates/concat-core/src/lib.rsindex 0c2fbced..19f1e591 100644--- a/src/crates/concat-core/src/lib.rs+++ b/src/crates/concat-core/src/lib.rs@@ -19,6 +19,7 @@pub mod animate;pub mod arena;pub mod frame;+pub mod mask;pub mod retime;pub mod shader;pub mod time;diff --git a/src/crates/concat-core/src/mask.rs b/src/crates/concat-core/src/mask.rsnew file mode 100644index 00000000..2bbdf983--- /dev/null+++ b/src/crates/concat-core/src/mask.rs@@ -0,0 +1,489 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! A shape that keeps part of a clip's picture: a clip's mask.+//!+//! A mask is drawn analytically, as a signed distance from the shape's+//! edge, so it costs no texture and is sharp at any size. The distance is+//! measured in units of the picture's shorter side, which is what makes a+//! circle round on any aspect and a feather the same softness on a 720p+//! export and a 4K one. Negative is inside; the coverage falls from one to+//! zero across a band the feather sets, centred on the edge, and an+//! inverted mask keeps the outside instead.+//!+//! This is the one definition of the arithmetic. The GPU compositor runs a+//! line-for-line copy of it in WGSL (`concat-render`'s `MASK_WGSL`), and its+//! tests hold the two together; the CPU reference calls [`ShapeMask::coverage`]+//! directly. A change here is a change there.++/// Which shape a mask keeps. The order is the shader's numbering, one up:+/// zero there is "no mask".+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Hash)]+pub enum MaskShape {+ /// One side of a straight line through the centre: the part above it,+ /// turned with the mask.+ Linear,+ /// A band either side of a line through the centre, `height` thick.+ Mirror,+ /// An ellipse filling the mask's box; a circle when it is square.+ #[default]+ Circle,+ /// The mask's box, its corners rounded by `roundness`.+ Rectangle,+ /// A heart filling the box, point down.+ Heart,+ /// A five-pointed star, point up.+ Star,+}++impl MaskShape {+ /// Every shape, in the order a picker lists them.+ pub const ALL: [MaskShape; 6] = [+ MaskShape::Linear,+ MaskShape::Mirror,+ MaskShape::Circle,+ MaskShape::Rectangle,+ MaskShape::Heart,+ MaskShape::Star,+ ];++ /// The name a document writes. Stable for ever.+ pub fn name(self) -> &'static str {+ match self {+ MaskShape::Linear => "linear",+ MaskShape::Mirror => "mirror",+ MaskShape::Circle => "circle",+ MaskShape::Rectangle => "rectangle",+ MaskShape::Heart => "heart",+ MaskShape::Star => "star",+ }+ }++ /// The shape a document names, if this build knows it.+ pub fn parse(name: &str) -> Option<MaskShape> {+ MaskShape::ALL+ .into_iter()+ .find(|shape| shape.name() == name.trim())+ }++ /// The shader's number for this shape: one up from its place in+ /// [`MaskShape::ALL`], zero being no mask at all.+ pub fn code(self) -> f32 {+ match self {+ MaskShape::Linear => 1.0,+ MaskShape::Mirror => 2.0,+ MaskShape::Circle => 3.0,+ MaskShape::Rectangle => 4.0,+ MaskShape::Heart => 5.0,+ MaskShape::Star => 6.0,+ }+ }++ /// Whether the box's width means anything: a line has no width, and a+ /// band only a thickness.+ pub fn has_width(self) -> bool {+ !matches!(self, MaskShape::Linear | MaskShape::Mirror)+ }++ /// Whether the box's height means anything: a line has none.+ pub fn has_height(self) -> bool {+ self != MaskShape::Linear+ }+}++/// A mask, at one instant: everything the compositor needs to weigh a+/// pixel of the picture by it.+#[derive(Clone, Copy, PartialEq, Debug)]+pub struct ShapeMask {+ /// What it keeps.+ pub shape: MaskShape,+ /// The centre's offset from the picture's centre, in fractions of the+ /// picture's width; positive is right.+ pub x: f64,+ /// The same down the picture's height; positive is down.+ pub y: f64,+ /// The box's width, in the picture's shorter side.+ pub width: f64,+ /// The box's height, in the picture's shorter side; a band's thickness.+ pub height: f64,+ /// Clockwise degrees about the centre.+ pub rotation: f64,+ /// How round a rectangle's corners are: zero square, one as round as+ /// the box's shorter half allows.+ pub roundness: f64,+ /// How soft the edge is, `0..=1`: the band the coverage falls across,+ /// as a fraction of half the picture's shorter side.+ pub feather: f64,+ /// Keeps the outside of the shape instead of the inside.+ pub invert: bool,+}++impl Default for ShapeMask {+ /// A circle in the middle, two thirds of the picture's shorter side+ /// across, with a hard edge.+ fn default() -> Self {+ ShapeMask {+ shape: MaskShape::Circle,+ x: 0.0,+ y: 0.0,+ width: 0.66,+ height: 0.66,+ rotation: 0.0,+ roundness: 0.0,+ feather: 0.0,+ invert: false,+ }+ }+}++/// The parts of a mask the shader takes, packed as it takes them: three+/// four-vectors, so a layer's mask rides along on its vertices.+#[derive(Clone, Copy, PartialEq, Debug)]+pub struct MaskUniform {+ /// Shape code, invert (0 or 1), the feather band and the corner radius,+ /// the last two in short-side units.+ pub a: [f32; 4],+ /// The centre in fractions of the picture, from its centre, and the+ /// box's half width and half height in short-side units.+ pub b: [f32; 4],+ /// The cosine and sine of the turn, and the picture's width and height+ /// over its shorter side.+ pub c: [f32; 4],+}++impl MaskUniform {+ /// No mask: every pixel kept.+ pub const NONE: MaskUniform = MaskUniform {+ a: [0.0; 4],+ b: [0.0; 4],+ c: [1.0, 0.0, 1.0, 1.0],+ };+}++impl ShapeMask {+ /// What the shader takes for this mask over a picture `width` by+ /// `height`, with `pixel` the size of one output pixel in the picture's+ /// shorter side: the narrowest band an edge may have, so a hard edge is+ /// still smoothed over a pixel rather than stair-stepped.+ pub fn uniform(&self, width: f32, height: f32, pixel: f32) -> MaskUniform {+ let short = width.min(height).max(1.0);+ let finite = |value: f64, fallback: f64| {+ if value.is_finite() {+ value as f32+ } else {+ fallback as f32+ }+ };+ let half_w = (finite(self.width, 0.66) / 2.0).max(1e-4);+ let half_h = (finite(self.height, 0.66) / 2.0).max(1e-4);+ let band = (finite(self.feather, 0.0).clamp(0.0, 1.0) * 0.5).max(pixel.max(1e-6));+ let radius = finite(self.roundness, 0.0).clamp(0.0, 1.0) * half_w.min(half_h);+ let (sin, cos) = finite(self.rotation, 0.0).to_radians().sin_cos();+ MaskUniform {+ a: [+ self.shape.code(),+ if self.invert { 1.0 } else { 0.0 },+ band,+ radius,+ ],+ b: [finite(self.x, 0.0), finite(self.y, 0.0), half_w, half_h],+ c: [cos, sin, width / short, height / short],+ }+ }++ /// How much of the picture is kept at `u`, `v` - `0..1` across it as+ /// it is seen - over a picture `width` by `height`, with `pixel` as in+ /// [`ShapeMask::uniform`].+ pub fn coverage(&self, u: f32, v: f32, width: f32, height: f32, pixel: f32) -> f32 {+ coverage(&self.uniform(width, height, pixel), u, v)+ }+}++/// How much of the picture a packed mask keeps at `u`, `v`: the shader's+/// `mask_coverage`, line for line.+pub fn coverage(mask: &MaskUniform, u: f32, v: f32) -> f32 {+ let [code, invert, band, radius] = mask.a;+ if code < 0.5 {+ return 1.0;+ }+ let [x, y, half_w, half_h] = mask.b;+ let [cos, sin, aspect_w, aspect_h] = mask.c;+ // The pixel's offset from the mask's centre in short-side units, then+ // turned back into the mask's own frame (clockwise in y-down).+ let dx = (u - 0.5 - x) * aspect_w;+ let dy = (v - 0.5 - y) * aspect_h;+ let p = [dx * cos + dy * sin, -dx * sin + dy * cos];+ let d = distance(code, p, [half_w, half_h], radius);+ let kept = 1.0 - smoothstep(-band * 0.5, band * 0.5, d);+ if invert > 0.5 { 1.0 - kept } else { kept }+}++/// The signed distance from the shape's edge at `p`, in the mask's own+/// frame and short-side units: negative inside.+pub fn distance(code: f32, p: [f32; 2], half: [f32; 2], radius: f32) -> f32 {+ let [hx, hy] = half;+ match code.round() as i32 {+ 1 => p[1],+ 2 => p[1].abs() - hy,+ 3 => ellipse(p, half),+ 4 => rounded_box(p, half, radius),+ 5 => {+ // The heart's own frame: y up, its point at the origin, its+ // lobes' tops at 1.1036 and its sides at ±0.6036. Fitted to the+ // box and measured back in the box's units.+ const SIDE: f32 = 0.603_553_4;+ const MID: f32 = 0.551_776_7;+ let q = [p[0] / hx * SIDE, MID - p[1] / hy * MID];+ heart(q) * (hx / SIDE).min(hy / MID)+ }+ 6 => star(p[0] / hx, -p[1] / hy) * hx.min(hy),+ _ => -1.0,+ }+}++/// WGSL's `smoothstep`, for `edge0 < edge1`.+pub fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {+ let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);+ t * t * (3.0 - 2.0 * t)+}++/// WGSL's `sign`: zero at zero, which Rust's `signum` is not.+fn sign(value: f32) -> f32 {+ if value > 0.0 {+ 1.0+ } else if value < 0.0 {+ -1.0+ } else {+ 0.0+ }+}++fn length(p: [f32; 2]) -> f32 {+ (p[0] * p[0] + p[1] * p[1]).sqrt()+}++fn dot2(p: [f32; 2]) -> f32 {+ p[0] * p[0] + p[1] * p[1]+}++/// An ellipse with these half axes. Exact on a circle; on an ellipse a+/// close approximation (Quilez's), which is what a feather band needs -+/// the edge itself, where the distance is zero, is exact either way.+fn ellipse(p: [f32; 2], r: [f32; 2]) -> f32 {+ let k0 = length([p[0] / r[0], p[1] / r[1]]);+ let k1 = length([p[0] / (r[0] * r[0]), p[1] / (r[1] * r[1])]);+ if k1 <= 1e-9 {+ return -r[0].min(r[1]);+ }+ k0 * (k0 - 1.0) / k1+}++/// A box with these half sides and corners rounded by `radius`.+fn rounded_box(p: [f32; 2], half: [f32; 2], radius: f32) -> f32 {+ let q = [p[0].abs() - half[0] + radius, p[1].abs() - half[1] + radius];+ length([q[0].max(0.0), q[1].max(0.0)]) + q[0].max(q[1]).min(0.0) - radius+}++/// Quilez's heart: y up, the point at the origin.+fn heart(p: [f32; 2]) -> f32 {+ let x = p[0].abs();+ let y = p[1];+ if y + x > 1.0 {+ return length([x - 0.25, y - 0.75]) - std::f32::consts::SQRT_2 / 4.0;+ }+ let m = (x + y).max(0.0) * 0.5;+ dot2([x, y - 1.0]).min(dot2([x - m, y - m])).sqrt() * sign(x - y)+}++/// Quilez's five-pointed star, outer radius one, y up, a point straight up.+fn star(x: f32, y: f32) -> f32 {+ const K1: [f32; 2] = [0.809_017, -0.587_785_24];+ const K2: [f32; 2] = [-0.809_017, -0.587_785_24];+ const INNER: f32 = 0.45;+ let mut p = [x.abs(), y];+ let d1 = (K1[0] * p[0] + K1[1] * p[1]).max(0.0) * 2.0;+ p = [p[0] - d1 * K1[0], p[1] - d1 * K1[1]];+ let d2 = (K2[0] * p[0] + K2[1] * p[1]).max(0.0) * 2.0;+ p = [p[0] - d2 * K2[0], p[1] - d2 * K2[1]];+ p[0] = p[0].abs();+ p[1] -= 1.0;+ let ba = [INNER * -K1[1] - 0.0, INNER * K1[0] - 1.0];+ let h = ((p[0] * ba[0] + p[1] * ba[1]) / dot2(ba)).clamp(0.0, 1.0);+ length([p[0] - ba[0] * h, p[1] - ba[1] * h]) * sign(p[1] * ba[0] - p[0] * ba[1])+}++#[cfg(test)]+mod tests {+ use super::*;++ fn mask(shape: MaskShape) -> ShapeMask {+ ShapeMask {+ shape,+ ..ShapeMask::default()+ }+ }++ /// On a square picture of 100 pixels a side, one pixel is a hundredth.+ const PIXEL: f32 = 0.01;++ fn kept(mask: &ShapeMask, u: f32, v: f32) -> f32 {+ mask.coverage(u, v, 100.0, 100.0, PIXEL)+ }++ #[test]+ fn every_shape_keeps_its_middle_and_drops_its_far_corner() {+ for shape in MaskShape::ALL {+ let mask = ShapeMask {+ shape,+ width: 0.5,+ height: 0.5,+ ..ShapeMask::default()+ };+ // The line keeps the half above it, so its "middle" is a hair+ // above the centre.+ let (u, v) = if shape == MaskShape::Linear {+ (0.5, 0.3)+ } else {+ (0.5, 0.5)+ };+ assert!(kept(&mask, u, v) > 0.999, "{shape:?} keeps its middle");+ assert!(+ kept(&mask, 0.98, 0.98) < 0.001,+ "{shape:?} drops the corner"+ );+ let inverted = ShapeMask {+ invert: true,+ ..mask+ };+ assert!(kept(&inverted, u, v) < 0.001, "{shape:?} inverted");+ assert!(kept(&inverted, 0.98, 0.98) > 0.999, "{shape:?} inverted");+ }+ }++ #[test]+ fn a_circle_is_exact_and_round_on_a_wide_picture() {+ let circle = mask(MaskShape::Circle);+ // Radius 0.33 of the short side. On the edge, half kept.+ let d = distance(3.0, [0.33, 0.0], [0.33, 0.33], 0.0);+ assert!(d.abs() < 1e-6);+ let d = distance(3.0, [0.0, 0.5], [0.33, 0.33], 0.0);+ assert!((d - 0.17).abs() < 1e-6, "{d}");+ // On a 200 by 100 picture the short side is the height, so the+ // edge is 33 pixels from the centre both ways: u is 0.5 + 33/200.+ let wide = |u: f32, v: f32| circle.coverage(u, v, 200.0, 100.0, PIXEL);+ assert!((wide(0.5 + 0.33 / 2.0, 0.5) - 0.5).abs() < 1e-3);+ assert!((wide(0.5, 0.5 + 0.33) - 0.5).abs() < 1e-3);+ }++ #[test]+ fn the_feather_is_a_smoothstep_centred_on_the_edge() {+ // Feather 0.4 is a band 0.2 of the short side wide, 0.1 each way.+ let soft = ShapeMask {+ feather: 0.4,+ ..mask(MaskShape::Circle)+ };+ let at = |r: f32| kept(&soft, 0.5 + r, 0.5);+ assert!((at(0.33) - 0.5).abs() < 1e-4, "half on the edge");+ assert!(at(0.33 - 0.1) > 0.9999, "all of it a band inside");+ assert!(at(0.33 + 0.1) < 1e-4, "none of it a band outside");+ // Halfway into the band, smoothstep's quarter: 0.15625 kept out.+ assert!((at(0.33 - 0.05) - 0.843_75).abs() < 1e-3);+ assert!((at(0.33 + 0.05) - 0.156_25).abs() < 1e-3);+ // A hard edge is still a pixel wide, not a step.+ let hard = mask(MaskShape::Circle);+ assert!((kept(&hard, 0.5 + 0.33, 0.5) - 0.5).abs() < 1e-3);+ assert!(kept(&hard, 0.5 + 0.33 + PIXEL, 0.5) < 1e-3);+ }++ #[test]+ fn a_rectangle_rounds_its_corners() {+ let half = [0.3, 0.2];+ // Square corners: the corner point is on the edge.+ assert!(distance(4.0, [0.3, 0.2], half, 0.0).abs() < 1e-6);+ // Fully round: the corner is cut, by r(√2 - 1) along the diagonal.+ let r = 0.2;+ let d = distance(4.0, [0.3, 0.2], half, r);+ assert!(+ (d - r * (std::f32::consts::SQRT_2 - 1.0)).abs() < 1e-5,+ "{d}"+ );+ // The middle of a side is untouched by the rounding.+ assert!(distance(4.0, [0.3, 0.0], half, r).abs() < 1e-6);+ assert!((distance(4.0, [0.0, 0.0], half, r) + 0.2).abs() < 1e-6);+ }++ #[test]+ fn the_line_and_the_band_turn_with_the_mask() {+ let line = mask(MaskShape::Linear);+ assert!(kept(&line, 0.5, 0.4) > 0.999);+ assert!(kept(&line, 0.5, 0.6) < 0.001);+ // Turned a quarter clockwise, "above" is the right: the line's+ // up points along +x once the frame is turned.+ let turned = ShapeMask {+ rotation: 90.0,+ ..line+ };+ assert!(kept(&turned, 0.6, 0.5) > 0.999);+ assert!(kept(&turned, 0.4, 0.5) < 0.001);+ let band = ShapeMask {+ height: 0.2,+ ..mask(MaskShape::Mirror)+ };+ assert!(kept(&band, 0.1, 0.5) > 0.999, "a band runs edge to edge");+ assert!(kept(&band, 0.5, 0.65) < 0.001);+ assert!((kept(&band, 0.5, 0.6) - 0.5).abs() < 1e-3);+ }++ #[test]+ fn the_heart_and_the_star_fill_their_box() {+ let half = [0.3, 0.3];+ // The heart's point is on the box's bottom edge, its lobes at the+ // top, its sides at the box's sides.+ assert!(distance(5.0, [0.0, 0.3], half, 0.0).abs() < 1e-4);+ assert!(distance(5.0, [0.0, 0.0], half, 0.0) < 0.0);+ assert!(distance(5.0, [0.0, -0.31], half, 0.0) > 0.0);+ // The notch between the lobes is outside.+ assert!(distance(5.0, [0.0, -0.28], half, 0.0) > 0.0);+ // Its widest, where the lobes' circles are, is the box's side.+ assert!(distance(5.0, [0.3, -0.1077], half, 0.0).abs() < 1e-3);+ // The star's top point is on the box's top edge; between two+ // points it is outside, and its middle is in.+ assert!(distance(6.0, [0.0, -0.3], half, 0.0).abs() < 1e-4);+ assert!(distance(6.0, [0.0, -0.2], half, 0.0) < 0.0);+ assert!(distance(6.0, [0.0, 0.0], half, 0.0) < 0.0);+ let between = [+ 0.3 * 36f32.to_radians().sin(),+ -0.3 * 36f32.to_radians().cos(),+ ];+ assert!(distance(6.0, between, half, 0.0) > 0.0);+ }++ #[test]+ fn a_moved_mask_is_measured_from_its_own_centre() {+ let moved = ShapeMask {+ x: 0.25,+ y: -0.25,+ width: 0.2,+ height: 0.2,+ ..mask(MaskShape::Rectangle)+ };+ assert!(kept(&moved, 0.75, 0.25) > 0.999);+ assert!(kept(&moved, 0.5, 0.5) < 0.001);+ }++ #[test]+ fn names_round_trip_and_nonsense_is_survivable() {+ for shape in MaskShape::ALL {+ assert_eq!(MaskShape::parse(shape.name()), Some(shape));+ }+ assert_eq!(MaskShape::parse("blob"), None);+ let broken = ShapeMask {+ width: f64::NAN,+ feather: f64::INFINITY,+ ..ShapeMask::default()+ };+ let value = kept(&broken, 0.5, 0.5);+ assert!(value.is_finite());+ assert_eq!(coverage(&MaskUniform::NONE, 0.1, 0.9), 1.0);+ }+}diff --git a/src/crates/concat-core/src/timeline.rs b/src/crates/concat-core/src/timeline.rsindex 3af93fad..9efd2f23 100644--- a/src/crates/concat-core/src/timeline.rs+++ b/src/crates/concat-core/src/timeline.rs@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};use crate::animate::Animation;use crate::arena::{Arena, Id};+use crate::mask::ShapeMask;use crate::retime::SpeedCurve;use crate::time::{FrameRate, Rational, TimeRange};@@ -100,6 +101,9 @@ pub struct Clip {/// first frame shown for the length of the dissolve, where other/// editors show "repeated frames".pub hold: bool,+ /// The shape that keeps part of the picture, when one does; its+ /// numbers ride the animation's mask tracks.+ pub mask: Option<ShapeMask>,}/// How a layer's colour meets what is beneath it.@@ -222,6 +226,7 @@ impl Clip {animation: None,blend: Blend::Normal,hold: false,+ mask: None,}}@@ -243,6 +248,16 @@ impl Clip {}}+ /// The mask at `time`: the clip's own, its keyed numbers at their+ /// ride's values. None for a clip with no mask.+ pub fn mask_at(&self, time: Rational) -> Option<ShapeMask> {+ let mask = self.mask?;+ Some(match &self.animation {+ Some(animation) => animation.mask.mask_at(mask, self.fraction_at(time)),+ None => mask,+ })+ }+/// The opacity at `time`, before the fade ramps: the clip's own, scaled/// by its animation.pub fn opacity_at(&self, time: Rational) -> f32 {diff --git a/src/crates/concat-export/src/flatten.rs b/src/crates/concat-export/src/flatten.rsindex cdce86d7..9a692e71 100644--- a/src/crates/concat-export/src/flatten.rs+++ b/src/crates/concat-export/src/flatten.rs@@ -142,6 +142,9 @@ pub fn flatten_timeline_in(.background_on(clip, lane).and_then(|background| backdrop_of(project, background)),cutout: clip.cutout.clone(),+ // Pictures only: a mask on a clip that is all sound would+ // keep part of nothing.+ mask: clip.mask.filter(|_| kind != ClipKind::Audio),mask_dir: match (&clip.cutout, project_dir) {(Some(cutout), Some(dir)) => {concat_vision::mask_dir(dir, &media.path, cutout.subject)@@ -213,6 +216,9 @@ pub fn export_base(clip: &concat_project::model::Clip, property: KeyProperty) ->// A factor's neutral is one; an addition's is zero.KeyProperty::Scale | KeyProperty::Opacity | KeyProperty::Volume => 1.0,KeyProperty::OffsetX | KeyProperty::OffsetY | KeyProperty::Rotation => 0.0,+ // The mask travels whole, as `ExportClip::mask`, and its keys+ // replace its numbers; it never asks for a base.+ mask => clip.constant(mask),}}@@ -348,6 +354,63 @@ mod tests {assert_eq!(flat[0].effects, vec![AppliedFilter::new("concat.mono")]);}+ /// A clip's mask and its keys reach the engine's clip, which plans+ /// the monitor's frames and the export's alike: one path, so the two+ /// cannot draw different masks.+ #[test]+ fn a_mask_and_its_keys_reach_the_engine() {+ use concat_core::time::Rational;+ use concat_project::model::{ClipMask, KeyEase, MaskShape};+ let (mut editor, _, clip_id) = project_with_clip();+ editor+ .apply(Command::UpdateClip {+ clip_id: clip_id.clone(),+ patch: ClipPatch {+ mask: Some(Some(ClipMask {+ feather: 0.2,+ ..ClipMask::of(MaskShape::Heart)+ })),+ ..Default::default()+ },+ })+ .expect("masks");+ for (at, value) in [(0.0, -0.2), (1.0, 0.2)] {+ editor+ .apply(Command::SetClipKey {+ clip_id: clip_id.clone(),+ property: KeyProperty::MaskX,+ at,+ value,+ ease: KeyEase::LINEAR,+ })+ .expect("keys");+ }+ let flat = flatten_timeline(editor.project(), None);+ let mask = flat[0].mask.expect("the mask rides along");+ assert_eq!(mask.shape, MaskShape::Heart);+ assert!(flat[0].animation.iter().any(|key| key.property == "maskX"));++ let mut clip = concat_core::timeline::Clip::new(+ concat_core::timeline::MediaRef::new("a.mp4"),+ Rational::ZERO,+ Rational::from_int(10),+ );+ clip.mask = Some(mask.engine());+ clip.animation = crate::resolve::animation_of(&flat[0].animation);+ let start = clip.mask_at(Rational::ZERO).expect("a mask");+ let middle = clip.mask_at(Rational::from_int(5)).expect("a mask");+ assert!((start.x + 0.2).abs() < 1e-12);+ assert!(middle.x.abs() < 1e-12);+ assert_eq!(middle.shape, concat_core::mask::MaskShape::Heart);+ assert!((middle.feather - 0.2).abs() < 1e-12);+ // The placement is untouched by the mask's keys.+ assert!(+ clip.animation+ .as_ref()+ .is_some_and(|a| a.offset_x.is_empty())+ );+ }+#[test]fn text_clips_are_left_for_the_rasteriser() {let (mut editor, _, _) = project_with_clip();diff --git a/src/crates/concat-export/src/lib.rs b/src/crates/concat-export/src/lib.rsindex a97b1194..07502f9c 100644--- a/src/crates/concat-export/src/lib.rs+++ b/src/crates/concat-export/src/lib.rs@@ -44,7 +44,7 @@ use concat_media::audio::{self, AudioClip};use concat_media::{DecodeOptions, Decoder, EncodeOptions, Encoder, FrameSink, FrameSource, RateMode, VideoCodec,};-use concat_project::model::{AppliedFilter, ColorSpace, Cutout};+use concat_project::model::{AppliedFilter, ClipMask, ColorSpace, Cutout};use concat_render::{Compositor, FramePlan, PlannedLayer, PlannedTreatment, Transition, WgpuCompositor, plan_frame,};@@ -212,6 +212,10 @@ pub struct ExportClip {/// leaves the picture whole.#[serde(default)]pub cutout: Option<Cutout>,+ /// The shape that keeps part of the picture, as the document holds+ /// it; its keyed numbers ride in `animation` as `maskX` and on.+ #[serde(default)]+ pub mask: Option<ClipMask>,/// Draw the cutout tinted over the whole picture instead of cutting/// it: the view while the clip's brushes are in use. Preview only.#[serde(default)]@@ -331,6 +335,7 @@ impl ExportClip {media_duration: None,has_audio: None,cutout: None,+ mask: None,mask_dir: String::new(),stabilize: None,motion_dir: String::new(),@@ -345,7 +350,9 @@ impl ExportClip {#[derive(Deserialize, Clone, Debug, PartialEq)]#[serde(rename_all = "camelCase")]pub struct ExportKey {- /// "scale", "offsetX", "offsetY", "rotation", "opacity" or "volume".+ /// "scale", "offsetX", "offsetY", "rotation", "opacity" or "volume",+ /// or one of the mask's numbers: "maskX", "maskY", "maskWidth",+ /// "maskHeight", "maskRotation", "maskRoundness", "maskFeather".pub property: String,/// Where in the clip, `0..=1`.pub at: f64,diff --git a/src/crates/concat-export/src/resolve.rs b/src/crates/concat-export/src/resolve.rsindex ab676ca3..a52872b2 100644--- a/src/crates/concat-export/src/resolve.rs+++ b/src/crates/concat-export/src/resolve.rs@@ -324,6 +324,7 @@ pub(crate) fn build_timeline(}engine_clip.animation = animation_of(&clip.animation);engine_clip.blend = concat_core::timeline::Blend::parse(&clip.blend);+ engine_clip.mask = clip.mask.map(|mask| mask.engine());engine_clip.transform = Transform {scale: clip.scale,offset_x: clip.offset_x,@@ -467,7 +468,7 @@ pub(crate) fn animation_of(keys: &[ExportKey]) -> Option<Animation> {if keys.is_empty() {return None;}- let mut tracks: [Vec<Key>; 6] = Default::default();+ let mut tracks: [Vec<Key>; 13] = Default::default();for key in keys {let slot = match key.property.as_str() {"scale" => 0,@@ -476,6 +477,13 @@ pub(crate) fn animation_of(keys: &[ExportKey]) -> Option<Animation> {"rotation" => 3,"opacity" => 4,"volume" => 5,+ "maskX" => 6,+ "maskY" => 7,+ "maskWidth" => 8,+ "maskHeight" => 9,+ "maskRotation" => 10,+ "maskRoundness" => 11,+ "maskFeather" => 12,_ => continue,};let [x1, y1, x2, y2] = key.ease;@@ -485,7 +493,21 @@ pub(crate) fn animation_of(keys: &[ExportKey]) -> Option<Animation> {ease: Ease::new(x1, y1, x2, y2),});}- let [scale, x, y, rotation, opacity, volume] = tracks;+ let [+ scale,+ x,+ y,+ rotation,+ opacity,+ volume,+ mask_x,+ mask_y,+ mask_width,+ mask_height,+ mask_rotation,+ mask_roundness,+ mask_feather,+ ] = tracks;let animation = Animation {scale: Track::new(scale),offset_x: Track::new(x),@@ -493,6 +515,15 @@ pub(crate) fn animation_of(keys: &[ExportKey]) -> Option<Animation> {rotation: Track::new(rotation),opacity: Track::new(opacity),volume: Track::new(volume),+ mask: concat_core::animate::MaskTracks {+ x: Track::new(mask_x),+ y: Track::new(mask_y),+ width: Track::new(mask_width),+ height: Track::new(mask_height),+ rotation: Track::new(mask_rotation),+ roundness: Track::new(mask_roundness),+ feather: Track::new(mask_feather),+ },};(!animation.is_empty()).then_some(animation)}diff --git a/src/crates/concat-host/src/session.rs b/src/crates/concat-host/src/session.rsindex c3bb4027..1dc5974a 100644--- a/src/crates/concat-host/src/session.rs+++ b/src/crates/concat-host/src/session.rs@@ -117,6 +117,11 @@ impl Session {}changed});+ // 0.2.4's mask effects, retired with no stand-in on the chain,+ // open as the clip's own mask (#239).+ for old in editor.upgrade_mask_effects() {+ upgraded.push((old, "mask".to_owned()));+ }// Fields an earlier version wrote and this one does not read, off// the clips, with the clips named for the window to say so.let retired = editor.drop_retired_fields();diff --git a/src/crates/concat-host/src/templates.rs b/src/crates/concat-host/src/templates.rsindex fd1cc1a0..c85653e6 100644--- a/src/crates/concat-host/src/templates.rs+++ b/src/crates/concat-host/src/templates.rs@@ -326,6 +326,7 @@ pub fn instantiate(// project does: its links read as links to the stand-ins.let catalogue = concat_effects::Catalogue::builtin();editor.upgrade_links(|link| catalogue.upgrade(link));+ editor.upgrade_mask_effects();if !fills.is_empty() {editor.apply(Command::Batch {diff --git a/src/crates/concat-project/src/commands/mod.rs b/src/crates/concat-project/src/commands/mod.rsindex 810f6dd2..94423328 100644--- a/src/crates/concat-project/src/commands/mod.rs+++ b/src/crates/concat-project/src/commands/mod.rs@@ -13,7 +13,7 @@ use std::sync::Arc;use serde::{Deserialize, Serialize};use crate::model::{- AppliedFilter, AudioTrack, Background, Clip, ClipKind, ColorRange, ColorSpace, Crop,+ AppliedFilter, AudioTrack, Background, Clip, ClipKind, ClipMask, ColorRange, ColorSpace, Crop,CustomFont, Cutout, CutoutMode, Enhanced, Framing, KeyEase, KeyProperty, MediaItem, MediaKind,MediaOrigin, Project, ShapeStyle, SpeedPoint, Stabilize, Stroke, TextStyle, Timeline, Track,Transition, VideoSettings,@@ -121,6 +121,16 @@ pub struct ClipPatch {skip_serializing_if = "Option::is_none")]pub crop: Option<Option<Crop>>,+ /// The mask, same three-way wire semantics as `crop`: absent leaves it+ /// alone, null takes it off, a value replaces it, tidied on the way in.+ /// Its keys are the clip's own (`setClipKey` with `maskX` and on), and+ /// stay when it is taken off, for a mask put back on to ride again.+ #[serde(+ default,+ with = "double_option",+ skip_serializing_if = "Option::is_none"+ )]+ pub mask: Option<Option<ClipMask>>,/// Wholesale replacement of the audio filter chain - the UI sends the/// full list, not a diff.pub filters: Option<Vec<AppliedFilter>>,@@ -1051,6 +1061,17 @@ impl Command {.iter().flatten().any(|crop| bad([crop.left, crop.top, crop.right, crop.bottom]))+ || patch.mask.iter().flatten().any(|mask| {+ bad([+ mask.x,+ mask.y,+ mask.width,+ mask.height,+ mask.rotation,+ mask.roundness,+ mask.feather,+ ])+ })|| patch.filters.as_deref().is_some_and(bad_chain)|| patch.video_effects.as_deref().is_some_and(bad_chain)|| patchdiff --git a/src/crates/concat-project/src/commands/properties.rs b/src/crates/concat-project/src/commands/properties.rsindex b14819ae..c54adfdb 100644--- a/src/crates/concat-project/src/commands/properties.rs+++ b/src/crates/concat-project/src/commands/properties.rs@@ -62,6 +62,9 @@ pub(super) fn apply(let crop = crop.map(Crop::tidy).filter(|crop| !crop.is_none());applied |= assign(&mut clip.crop, crop);}+ if let Some(mask) = patch.mask {+ applied |= assign(&mut clip.mask, mask.map(ClipMask::tidy));+ }if let Some(filters) = patch.filters {applied |= assign(&mut clip.filters, filters);}@@ -203,6 +206,7 @@ pub(super) fn apply(// same value at a different instant.KeyProperty::Volume => value.max(0.0),KeyProperty::OffsetX | KeyProperty::OffsetY | KeyProperty::Rotation => value,+ mask => ClipMask::clamp(mask, value),};let before = clip.keys.clone();clip.set_key(property, at, value, ease);diff --git a/src/crates/concat-project/src/editor.rs b/src/crates/concat-project/src/editor.rsindex d616f6dc..df68614a 100644--- a/src/crates/concat-project/src/editor.rs+++ b/src/crates/concat-project/src/editor.rs@@ -106,6 +106,82 @@ impl Editor {changed}+ /// Turns a link to one of 0.2.4's three mask effects - Mask: Circle,+ /// Rectangle and Linear, retired in 0.2.5 with the old effect format+ /// and nothing in their place (#239) - into the clip's own mask, as+ /// the document is read, like [`Editor::upgrade_links`]. Their knobs+ /// and the keys on them carry over into the mask's terms; the first+ /// enabled one on a clip with no mask of its own is taken, and any+ /// other stays a link to an effect that is not installed. Returns the+ /// ids of the effects that were turned into masks.+ pub fn upgrade_mask_effects(&mut self) -> Vec<String> {+ use std::sync::Arc;+ let mut upgraded: Vec<String> = Vec::new();+ for timeline in &mut self.project.timelines {+ for index in 0..timeline.clips.len() {+ let clip = &timeline.clips[index];+ if clip.mask.is_some() || !clip.kind.is_visual() {+ continue;+ }+ let Some(entry) = clip+ .video_effects+ .iter()+ .position(|link| link.enabled && old_mask(&link.id).is_some())+ else {+ continue;+ };+ // The old masks measured some knobs against the frame's+ // width or height and some against its shorter side; the+ // media's own shape stands in for the frame's.+ let (width, height) = self+ .project+ .media+ .iter()+ .find(|item| item.id == clip.media_id)+ .and_then(|item| Some((f64::from(item.width?), f64::from(item.height?))))+ .filter(|(w, h)| *w > 0.0 && *h > 0.0)+ .unwrap_or((16.0, 9.0));+ let short = width.min(height);+ let (wide, tall) = (width / short, height / short);+ let link = clip.video_effects[entry].clone();+ let Some(shape) = old_mask(&link.id) else {+ continue;+ };+ let mut mask = crate::model::ClipMask::of(shape);+ mask.invert = link.params.get("invert").copied().unwrap_or(0.0) >= 0.5;+ if shape == crate::model::MaskShape::Linear {+ // A vertical edge keeping what is left of it: the line+ // turned a quarter back.+ mask.rotation = -90.0;+ }+ let mut keys: Vec<crate::model::ClipKey> = Vec::new();+ for (param, property, fallback, convert) in+ old_mask_knobs(shape, wide, tall).into_iter().flatten()+ {+ let value = link.params.get(param).copied().unwrap_or(fallback);+ mask.set(property, convert(value));+ keys.extend(link.keys_on(param).iter().map(|key| crate::model::ClipKey {+ property,+ at: key.at,+ value: crate::model::ClipMask::clamp(property, convert(key.value)),+ ease: key.ease,+ }));+ }+ if !upgraded.contains(&link.id) {+ upgraded.push(link.id.clone());+ }+ let timeline = Arc::make_mut(timeline);+ let clip = Arc::make_mut(&mut timeline.clips[index]);+ clip.video_effects.remove(entry);+ clip.mask = Some(mask.tidy());+ for key in keys {+ clip.set_key(key.property, key.at, key.value, key.ease);+ }+ }+ }+ upgraded+ }+/// Takes off the clip fields earlier versions wrote and this one no/// longer reads - 0.2.4's `reverse` flag and its preset animations -/// as the document is read, the way [`Editor::upgrade_links`] does: not@@ -369,3 +445,170 @@ pub struct RetiredFields {/// Clips an earlier version moved with a preset animation.pub animated: Vec<String>,}++/// The shape one of 0.2.4's mask effects keeps, by its package id.+fn old_mask(id: &str) -> Option<crate::model::MaskShape> {+ use crate::model::MaskShape;+ match id {+ "concat.mask-circle" => Some(MaskShape::Circle),+ "concat.mask-rectangle" => Some(MaskShape::Rectangle),+ "concat.mask-linear" => Some(MaskShape::Linear),+ _ => None,+ }+}++/// One knob of an old mask effect: its name, the mask number it becomes,+/// its old default, and how its value turns into that number's.+type OldKnob = (+ &'static str,+ crate::model::KeyProperty,+ f64,+ Box<dyn Fn(f64) -> f64>,+);++/// The knobs of the old mask effect of `shape` and how each carries over,+/// for a picture `wide` and `tall` in its shorter side. The arithmetic is+/// the old shaders' (0.2.4's `concat.mask-*/effect.wgsl`): a circle's size+/// was its diameter in the shorter side, a rectangle's width and height+/// fractions of the frame's own, the feathers bands of the shorter side+/// (the line's of the width), the centres fractions of the frame from its+/// corner. A mask measures from the picture's centre, in its shorter side,+/// and its feather is a band of half the shorter side.+fn old_mask_knobs(shape: crate::model::MaskShape, wide: f64, tall: f64) -> [Option<OldKnob>; 5] {+ use crate::model::{KeyProperty, MaskShape};+ let centre = |value: f64| value / 100.0 - 0.5;+ match shape {+ MaskShape::Circle => [+ Some((+ "size",+ KeyProperty::MaskWidth,+ 50.0,+ Box::new(|v| v / 100.0),+ )),+ Some((+ "size",+ KeyProperty::MaskHeight,+ 50.0,+ Box::new(|v| v / 100.0),+ )),+ Some((+ "feather",+ KeyProperty::MaskFeather,+ 10.0,+ Box::new(|v| v / 100.0),+ )),+ Some(("x", KeyProperty::MaskX, 50.0, Box::new(centre))),+ Some(("y", KeyProperty::MaskY, 50.0, Box::new(centre))),+ ],+ MaskShape::Rectangle => [+ Some((+ "width",+ KeyProperty::MaskWidth,+ 50.0,+ Box::new(move |v| v / 100.0 * wide),+ )),+ Some((+ "height",+ KeyProperty::MaskHeight,+ 50.0,+ Box::new(move |v| v / 100.0 * tall),+ )),+ Some((+ "feather",+ KeyProperty::MaskFeather,+ 10.0,+ Box::new(|v| v / 100.0),+ )),+ Some(("x", KeyProperty::MaskX, 50.0, Box::new(centre))),+ Some(("y", KeyProperty::MaskY, 50.0, Box::new(centre))),+ ],+ _ => [+ Some(("position", KeyProperty::MaskX, 50.0, Box::new(centre))),+ Some((+ "feather",+ KeyProperty::MaskFeather,+ 20.0,+ Box::new(move |v| v / 50.0 * wide),+ )),+ None,+ None,+ None,+ ],+ }+}++#[cfg(test)]+mod mask_upgrade_tests {+ use super::*;+ use crate::model::{AppliedFilter, ClipKind, KeyEase, KeyProperty, MaskShape};++ fn with_link(link: AppliedFilter, size: (u32, u32)) -> Editor {+ let mut editor = Editor::new();+ editor.project.media.push(crate::model::MediaItem {+ id: "m1".into(),+ width: Some(size.0),+ height: Some(size.1),+ ..Default::default()+ });+ let timeline = std::sync::Arc::make_mut(&mut editor.project.timelines[0]);+ let track = timeline.tracks[0].id.clone();+ let mut clip = Clip::blank("c1", track, ClipKind::Video, "Mirror", 0.0, 4.0);+ clip.media_id = "m1".into();+ clip.video_effects = vec![AppliedFilter::new("concat.mono"), link];+ timeline.clips.push(std::sync::Arc::new(clip));+ editor+ }++ /// 0.2.4's Mask: Circle on a clip opens as the clip's own circle,+ /// the same size, softness and place, and the link goes; its keys+ /// carry over as the mask's.+ #[test]+ fn an_old_circle_mask_opens_as_the_clips_mask() {+ let mut link = AppliedFilter::new("concat.mask-circle");+ link.params.insert("size".into(), 40.0);+ link.params.insert("feather".into(), 20.0);+ link.params.insert("x".into(), 75.0);+ link.params.insert("invert".into(), 1.0);+ link.set_key("y", 0.0, 50.0, KeyEase::LINEAR);+ link.set_key("y", 1.0, 25.0, KeyEase::LINEAR);+ let mut editor = with_link(link, (1920, 1080));+ assert_eq!(editor.upgrade_mask_effects(), vec!["concat.mask-circle"]);+ let clip = &editor.project.timelines[0].clips[0];+ let mask = clip.mask.expect("a mask");+ assert_eq!(mask.shape, MaskShape::Circle);+ assert!((mask.width - 0.4).abs() < 1e-9 && (mask.height - 0.4).abs() < 1e-9);+ assert!((mask.feather - 0.2).abs() < 1e-9);+ assert!((mask.x - 0.25).abs() < 1e-9 && mask.y == 0.0);+ assert!(mask.invert);+ assert_eq!(clip.video_effects, vec![AppliedFilter::new("concat.mono")]);+ assert!((clip.value_at(KeyProperty::MaskY, 1.0) + 0.25).abs() < 1e-9);+ // Done once: a second read finds nothing to do.+ assert!(editor.upgrade_mask_effects().is_empty());+ }++ /// A rectangle's width and height were the frame's own fractions; on+ /// a wide picture they become the shorter side's. The line was a+ /// vertical edge keeping the left.+ #[test]+ fn an_old_rectangle_and_line_keep_their_shape_on_a_wide_picture() {+ let mut link = AppliedFilter::new("concat.mask-rectangle");+ link.params.insert("width".into(), 50.0);+ link.params.insert("height".into(), 50.0);+ let mut editor = with_link(link, (200, 100));+ editor.upgrade_mask_effects();+ let mask = editor.project.timelines[0].clips[0].mask.expect("a mask");+ assert!((mask.width - 1.0).abs() < 1e-9, "half of 200 is 100");+ assert!((mask.height - 0.5).abs() < 1e-9, "half of 100 is 50");++ let mut editor = with_link(AppliedFilter::new("concat.mask-linear"), (200, 100));+ editor.upgrade_mask_effects();+ let mask = editor.project.timelines[0].clips[0].mask.expect("a mask");+ assert_eq!(mask.shape, MaskShape::Linear);+ assert_eq!(mask.rotation, -90.0);+ assert_eq!(mask.x, 0.0);+ assert!(+ (mask.feather - 0.8).abs() < 1e-9,+ "a fifth of 200 is 40, of 50"+ );+ }+}diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rsindex 93a2ca72..35cc02ad 100644--- a/src/crates/concat-project/src/lib.rs+++ b/src/crates/concat-project/src/lib.rs@@ -2217,7 +2217,7 @@ mod tests {document["futureSetting"] = json!({ "on": true });document["timelines"][0]["colourSpace"] = json!("rec709");document["timelines"][0]["tracks"][0]["name"] = json!("Dialogue");- document["timelines"][0]["clips"][0]["mask"] = json!({ "shape": "ellipse" });+ document["timelines"][0]["clips"][0]["motionTrack"] = json!({ "shape": "ellipse" });document["media"][0]["proxy"] = json!("/proxies/a.mp4");let loaded = Editor::from_document(&document).expect("loads");@@ -2227,7 +2227,7 @@ mod tests {.active().clip(&clip_id).expect("clip")- .extra["mask"]["shape"],+ .extra["motionTrack"]["shape"],"ellipse");let saved = loaded.to_document(&settings());@@ -2235,13 +2235,13 @@ mod tests {assert_eq!(saved["timelines"][0]["colourSpace"], "rec709");assert_eq!(saved["timelines"][0]["tracks"][0]["name"], "Dialogue");assert_eq!(- saved["timelines"][0]["clips"][0]["mask"]["shape"],+ saved["timelines"][0]["clips"][0]["motionTrack"]["shape"],"ellipse");assert_eq!(saved["media"][0]["proxy"], "/proxies/a.mp4");// The flat mirror carries the clip's unknown field too: it is the// same clip serialised twice.- assert_eq!(saved["clips"][0]["mask"]["shape"], "ellipse");+ assert_eq!(saved["clips"][0]["motionTrack"]["shape"], "ellipse");// And the writer's own fields are never duplicated from `extra`.assert_eq!(loaded.project().extra.len(),@@ -2942,6 +2942,148 @@ mod tests {assert_eq!(restored.project(), editor.project());}+ /// A clip's mask is an edit like any other: put on and taken off by a+ /// patch, held to its ranges, its numbers keyed, and every bit of it+ /// saved and read back as it was.+ #[test]+ fn a_mask_and_its_keys_round_trip() {+ use crate::model::{ClipMask, KeyEase, KeyProperty, MaskShape};+ let (mut editor, _, clip_id) = fixture();+ let mask = ClipMask {+ roundness: 0.4,+ feather: 0.25,+ invert: true,+ rotation: 30.0,+ // Past its range: held to it on the way in.+ width: 9.0,+ ..ClipMask::of(MaskShape::Rectangle)+ };+ editor+ .apply(Command::UpdateClip {+ clip_id: clip_id.clone(),+ patch: ClipPatch {+ mask: Some(Some(mask)),+ ..ClipPatch::default()+ },+ })+ .expect("masks");+ for (at, value) in [(0.0, -0.3), (1.0, 0.3)] {+ editor+ .apply(Command::SetClipKey {+ clip_id: clip_id.clone(),+ property: KeyProperty::MaskX,+ at,+ value,+ ease: KeyEase::LINEAR,+ })+ .expect("keys");+ }+ // A key past the feather's range is held to it, as the field is.+ editor+ .apply(Command::SetClipKey {+ clip_id: clip_id.clone(),+ property: KeyProperty::MaskFeather,+ at: 0.5,+ value: 7.0,+ ease: KeyEase::LINEAR,+ })+ .expect("keys");+ let clip = editor.project().active().clip(&clip_id).expect("clip");+ let held = clip.mask.expect("a mask");+ assert_eq!(held.width, ClipMask::MAX_SIZE);+ assert_eq!(held.shape, MaskShape::Rectangle);+ assert!((clip.value_at(KeyProperty::MaskX, 0.5)).abs() < 1e-12);+ assert!((clip.value_at(KeyProperty::MaskX, 0.75) - 0.15).abs() < 1e-12);+ assert_eq!(clip.value_at(KeyProperty::MaskFeather, 0.5), 1.0);+ // An unkeyed number is the mask's own.+ assert_eq!(clip.value_at(KeyProperty::MaskRoundness, 0.5), 0.4);++ let document = editor.to_document(&settings());+ let written = &document["timelines"][0]["clips"][0];+ assert_eq!(written["mask"]["shape"], "rectangle");+ assert_eq!(written["mask"]["invert"], true);+ assert!(+ written["keys"]+ .as_array()+ .expect("keys")+ .iter()+ .any(|key| key["property"] == "maskX")+ );+ let restored = Editor::from_document(&document).expect("loads");+ assert_eq!(restored.project(), editor.project());++ // Null takes it off and leaves the rest of the clip alone.+ editor+ .apply(Command::UpdateClip {+ clip_id: clip_id.clone(),+ patch: ClipPatch {+ mask: Some(None),+ ..ClipPatch::default()+ },+ })+ .expect("unmasks");+ let clip = editor.project().active().clip(&clip_id).expect("clip");+ assert!(clip.mask.is_none());+ assert!(+ !editor.to_document(&settings())["timelines"][0]["clips"][0]+ .as_object()+ .expect("a clip")+ .contains_key("mask")+ );+ }++ /// The wire spelling a caller of the API writes: camelCase numbers, a+ /// lowercase shape, anything left out a new mask's, and a shape this+ /// build has not heard of a circle rather than a failed clip.+ #[test]+ fn a_mask_reads_from_its_wire_spelling() {+ use crate::model::{ClipMask, MaskShape};+ let patch: ClipPatch =+ serde_json::from_value(json!({ "mask": { "shape": "heart", "feather": 0.5 } }))+ .expect("parses");+ let mask = patch.mask.flatten().expect("a mask");+ assert_eq!(mask.shape, MaskShape::Heart);+ assert_eq!(mask.feather, 0.5);+ assert_eq!(mask.width, ClipMask::of(MaskShape::Circle).width);+ let odd: ClipMask =+ serde_json::from_value(json!({ "shape": "blob", "x": 0.2 })).expect("parses");+ assert_eq!((odd.shape, odd.x), (MaskShape::Circle, 0.2));+ let cleared: ClipPatch = serde_json::from_value(json!({ "mask": null })).expect("parses");+ assert_eq!(cleared.mask, Some(None));+ let untouched: ClipPatch = serde_json::from_value(json!({})).expect("parses");+ assert_eq!(untouched.mask, None);+ }++ /// A document from before masks opens with none, and one written by a+ /// build whose mask this one cannot read opens without it rather than+ /// without the clip.+ #[test]+ fn a_document_without_a_mask_opens_maskless() {+ let (editor, _, clip_id) = fixture();+ let mut document = editor.to_document(&settings());+ let restored = Editor::from_document(&document).expect("loads");+ assert!(+ restored+ .project()+ .active()+ .clip(&clip_id)+ .expect("clip")+ .mask+ .is_none()+ );+ document["timelines"][0]["clips"][0]["mask"] = json!("not a mask");+ let restored = Editor::from_document(&document).expect("loads");+ assert!(+ restored+ .project()+ .active()+ .clip(&clip_id)+ .expect("clip")+ .mask+ .is_none()+ );+ }+#[test]fn a_version_one_document_loads() {// The shape of a version-1 document as it sits on disk, optionaldiff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rsindex 1ccb6e44..845565db 100644--- a/src/crates/concat-project/src/model.rs+++ b/src/crates/concat-project/src/model.rs@@ -806,9 +806,210 @@ pub fn framing_scale(Some(scale.clamp(ranges::MIN_SCALE, ranges::MAX_SCALE))}+/// Which shape a clip's mask keeps. The names are written into project+/// files, so they are stable for ever.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum MaskShape {+ /// The part of the picture on one side of a line through the centre.+ Linear,+ /// A band along a line through the centre: the line mirrored.+ Mirror,+ /// An ellipse; a circle when its box is square. The default, and what+ /// the reader falls back to.+ #[default]+ Circle,+ /// A box, its corners rounded by the mask's `roundness`.+ Rectangle,+ /// A heart, point down.+ Heart,+ /// A five-pointed star, point up.+ Star,+}++impl MaskShape {+ /// Every shape, in the order the pickers list them.+ pub const ALL: [MaskShape; 6] = [+ MaskShape::Linear,+ MaskShape::Mirror,+ MaskShape::Circle,+ MaskShape::Rectangle,+ MaskShape::Heart,+ MaskShape::Star,+ ];++ /// The engine's shape.+ pub fn engine(self) -> concat_core::mask::MaskShape {+ use concat_core::mask::MaskShape as Engine;+ match self {+ MaskShape::Linear => Engine::Linear,+ MaskShape::Mirror => Engine::Mirror,+ MaskShape::Circle => Engine::Circle,+ MaskShape::Rectangle => Engine::Rectangle,+ MaskShape::Heart => Engine::Heart,+ MaskShape::Star => Engine::Star,+ }+ }+}++/// A shape that keeps part of a clip's picture: CapCut's Mask. Drawn over+/// the picture as it is seen - after the crop and the flips, before the+/// placement - so it moves, scales and turns with the clip, and multiplies+/// with the cutout's matte and everything else that weighs the picture.+///+/// Its numbers other than the shape and the invert can be keyed, as the+/// placement's can (`KeyProperty::MaskX` and on); a keyed number's keys+/// replace the constant here.+#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct ClipMask {+ /// What it keeps.+ #[serde(deserialize_with = "wire::mask_shape")]+ pub shape: MaskShape,+ /// The centre's offset from the picture's centre, as a fraction of the+ /// picture's width; positive is right.+ pub x: f64,+ /// The same down the picture's height; positive is down.+ pub y: f64,+ /// The box's width, as a fraction of the picture's shorter side - the+ /// unit that keeps a circle round on any aspect.+ pub width: f64,+ /// The box's height, on the same terms; a mirror's thickness.+ pub height: f64,+ /// Clockwise degrees about the mask's centre.+ pub rotation: f64,+ /// How round a rectangle's corners are, `0..=1`.+ pub roundness: f64,+ /// How soft the edge is, `0..=1`: one fades across half the picture's+ /// shorter side.+ pub feather: f64,+ /// Keeps the outside of the shape instead of the inside.+ #[serde(skip_serializing_if = "is_false")]+ pub invert: bool,+}++impl Default for ClipMask {+ fn default() -> Self {+ ClipMask::of(MaskShape::Circle)+ }+}++impl ClipMask {+ /// The smallest a mask's box may be, each way.+ pub const MIN_SIZE: f64 = 0.01;+ /// The largest, each way: four times the shorter side covers the+ /// longest side of any picture a person would mask.+ pub const MAX_SIZE: f64 = 4.0;+ /// How far off the picture's centre a mask may be moved, in its sides.+ pub const MAX_OFFSET: f64 = 2.0;++ /// A mask of `shape` at the size and place a new one starts from: in+ /// the middle, two thirds of the shorter side across - a band a third+ /// thick, a rectangle a little wider than tall.+ pub fn of(shape: MaskShape) -> ClipMask {+ let (width, height) = match shape {+ MaskShape::Linear => (1.0, 1.0),+ MaskShape::Mirror => (1.0, 0.33),+ MaskShape::Rectangle => (0.8, 0.5),+ MaskShape::Circle | MaskShape::Heart | MaskShape::Star => (0.66, 0.66),+ };+ ClipMask {+ shape,+ x: 0.0,+ y: 0.0,+ width,+ height,+ rotation: 0.0,+ roundness: 0.0,+ feather: 0.0,+ invert: false,+ }+ }++ /// A number held to the range its field may hold; see [`Self::tidy`].+ /// What a key on that number is held to as well.+ pub fn clamp(property: KeyProperty, value: f64) -> f64 {+ match property {+ KeyProperty::MaskX | KeyProperty::MaskY => {+ value.clamp(-Self::MAX_OFFSET, Self::MAX_OFFSET)+ }+ KeyProperty::MaskWidth | KeyProperty::MaskHeight => {+ value.clamp(Self::MIN_SIZE, Self::MAX_SIZE)+ }+ KeyProperty::MaskRoundness | KeyProperty::MaskFeather => value.clamp(0.0, 1.0),+ // A turn is a turn however many times round; a key past one is+ // a spin, so neither is wrapped.+ _ => value,+ }+ }++ /// The number a keyable property names, or None for a property that+ /// is not the mask's.+ pub fn get(&self, property: KeyProperty) -> Option<f64> {+ Some(match property {+ KeyProperty::MaskX => self.x,+ KeyProperty::MaskY => self.y,+ KeyProperty::MaskWidth => self.width,+ KeyProperty::MaskHeight => self.height,+ KeyProperty::MaskRotation => self.rotation,+ KeyProperty::MaskRoundness => self.roundness,+ KeyProperty::MaskFeather => self.feather,+ _ => return None,+ })+ }++ /// Sets the number a keyable property names, held to its range. A+ /// property that is not the mask's changes nothing.+ pub fn set(&mut self, property: KeyProperty, value: f64) {+ if !value.is_finite() {+ return;+ }+ let value = Self::clamp(property, value);+ match property {+ KeyProperty::MaskX => self.x = value,+ KeyProperty::MaskY => self.y = value,+ KeyProperty::MaskWidth => self.width = value,+ KeyProperty::MaskHeight => self.height = value,+ KeyProperty::MaskRotation => self.rotation = value,+ KeyProperty::MaskRoundness => self.roundness = value,+ KeyProperty::MaskFeather => self.feather = value,+ _ => {}+ }+ }++ /// Every number back in its range, a number that is not one replaced+ /// by a new mask's.+ pub fn tidy(self) -> ClipMask {+ let fresh = ClipMask::of(self.shape);+ let mut out = self;+ for property in KeyProperty::MASK {+ let value = self.get(property).filter(|value| value.is_finite());+ let value = value.or_else(|| fresh.get(property)).unwrap_or(0.0);+ out.set(property, value);+ }+ out+ }++ /// The engine's mask with these numbers.+ pub fn engine(&self) -> concat_core::mask::ShapeMask {+ concat_core::mask::ShapeMask {+ shape: self.shape.engine(),+ x: self.x,+ y: self.y,+ width: self.width,+ height: self.height,+ rotation: self.rotation,+ roundness: self.roundness,+ feather: self.feather,+ invert: self.invert,+ }+ }+}+/// Which property a user-set key belongs to.///-/// Five of the six are the picture's; the sixth is the mix's. They are one+/// Five of the first six are the picture's placement and the sixth is the+/// mix's; the seven after them are the mask's numbers. They are one/// enum because a key is a key - the panel that sets them, the commands that/// carry them and the document that stores them do not care which side of/// the clip a value ends up on, and only the thing that finally reads them@@ -828,6 +1029,20 @@ pub enum KeyProperty {Opacity,/// `Clip::volume`.Volume,+ /// `ClipMask::x`.+ MaskX,+ /// `ClipMask::y`.+ MaskY,+ /// `ClipMask::width`.+ MaskWidth,+ /// `ClipMask::height`.+ MaskHeight,+ /// `ClipMask::rotation`.+ MaskRotation,+ /// `ClipMask::roundness`.+ MaskRoundness,+ /// `ClipMask::feather`.+ MaskFeather,}impl KeyProperty {@@ -841,6 +1056,13 @@ impl KeyProperty {KeyProperty::Rotation => "rotation",KeyProperty::Opacity => "opacity",KeyProperty::Volume => "volume",+ KeyProperty::MaskX => "maskX",+ KeyProperty::MaskY => "maskY",+ KeyProperty::MaskWidth => "maskWidth",+ KeyProperty::MaskHeight => "maskHeight",+ KeyProperty::MaskRotation => "maskRotation",+ KeyProperty::MaskRoundness => "maskRoundness",+ KeyProperty::MaskFeather => "maskFeather",}}@@ -853,19 +1075,49 @@ impl KeyProperty {"rotation" => KeyProperty::Rotation,"opacity" => KeyProperty::Opacity,"volume" => KeyProperty::Volume,+ "maskX" => KeyProperty::MaskX,+ "maskY" => KeyProperty::MaskY,+ "maskWidth" => KeyProperty::MaskWidth,+ "maskHeight" => KeyProperty::MaskHeight,+ "maskRotation" => KeyProperty::MaskRotation,+ "maskRoundness" => KeyProperty::MaskRoundness,+ "maskFeather" => KeyProperty::MaskFeather,_ => return None,})}/// Every property that can be keyed, in the order a panel lists them.- pub const ALL: [KeyProperty; 6] = [+ pub const ALL: [KeyProperty; 13] = [KeyProperty::Scale,KeyProperty::OffsetX,KeyProperty::OffsetY,KeyProperty::Rotation,KeyProperty::Opacity,KeyProperty::Volume,+ KeyProperty::MaskX,+ KeyProperty::MaskY,+ KeyProperty::MaskWidth,+ KeyProperty::MaskHeight,+ KeyProperty::MaskRotation,+ KeyProperty::MaskRoundness,+ KeyProperty::MaskFeather,];++ /// The mask's numbers: the properties a clip's mask carries.+ pub const MASK: [KeyProperty; 7] = [+ KeyProperty::MaskX,+ KeyProperty::MaskY,+ KeyProperty::MaskWidth,+ KeyProperty::MaskHeight,+ KeyProperty::MaskRotation,+ KeyProperty::MaskRoundness,+ KeyProperty::MaskFeather,+ ];++ /// Whether this is one of the mask's numbers.+ pub fn is_mask(self) -> bool {+ KeyProperty::MASK.contains(&self)+ }}/// How a key is approached from the one before it: a CSS timing function's@@ -1305,7 +1557,9 @@ pub(crate) mod wire {use serde::{Deserialize, Deserializer};use serde_json::Value;- use super::{Background, ClipKind, ColorSpace, MediaKind, ParamKey, ShapeKind, TextAlign};+ use super::{+ Background, ClipKind, ColorSpace, MaskShape, MediaKind, ParamKey, ShapeKind, TextAlign,+ };/// The entries of a list that parse, in order; not a list at all is/// an empty one.@@ -1408,6 +1662,12 @@ pub(crate) mod wire {let value = Value::deserialize(deserializer)?;Ok(serde_json::from_value(value).unwrap_or_default())}++ /// A mask's shape, or a circle for one this build does not know.+ pub fn mask_shape<'de, D: Deserializer<'de>>(deserializer: D) -> Result<MaskShape, D::Error> {+ let value = Value::deserialize(deserializer)?;+ Ok(serde_json::from_value(value).unwrap_or_default())+ }}/// The ranges a clip's numbers are held in. One set, used by every@@ -1534,6 +1794,10 @@ pub struct Clip {#[serde(default, skip_serializing_if = "Option::is_none")]#[serde(deserialize_with = "wire::maybe")]pub cutout: Option<Cutout>,+ /// The shape that keeps part of the picture; see [`ClipMask`].+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[serde(deserialize_with = "wire::maybe")]+ pub mask: Option<ClipMask>,/// The camera's shake taken out; see [`Stabilize`]. None is off.#[serde(default, skip_serializing_if = "Option::is_none")]#[serde(deserialize_with = "wire::maybe")]@@ -1675,6 +1939,7 @@ impl Clip {blend: String::new(),crop: None,cutout: None,+ mask: None,stabilize: None,filters: Vec::new(),video_effects: Vec::new(),@@ -1732,6 +1997,7 @@ impl Clip {.map(Crop::tidy).filter(|crop| !crop.is_none());self.cutout = self.cutout.take().map(Cutout::tidy);+ self.mask = self.mask.take().map(ClipMask::tidy);self.stabilize = self.stabilize.take().map(Stabilize::tidy);if let Some(transition) = self.transition_in.as_mut() {transition.duration = finite(transition.duration, 1.0).max(MIN_TRANSITION);@@ -1750,6 +2016,7 @@ impl Clip {key.value.clamp(-MAX_OFFSET, MAX_OFFSET)}KeyProperty::Rotation => key.value,+ mask => ClipMask::clamp(mask, key.value),};}self.sort_keys();@@ -1777,6 +2044,13 @@ impl Clip {KeyProperty::Rotation => self.rotation,KeyProperty::Opacity => self.opacity,KeyProperty::Volume => self.volume,+ // A clip with no mask answers with a new one's numbers, so a+ // panel opening on it shows what the first shape will start at.+ mask => self+ .mask+ .unwrap_or_default()+ .get(mask)+ .unwrap_or_default(),}}@@ -1834,6 +2108,9 @@ impl Clip {KeyProperty::Rotation => self.rotation = value,KeyProperty::Opacity => self.opacity = value,KeyProperty::Volume => self.volume = value,+ // The mask's numbers are the mask's; a number written on a+ // clip with none puts one on, the shape a new one starts as.+ mask => self.mask.get_or_insert_with(ClipMask::default).set(mask, value),}}diff --git a/src/crates/concat-render/src/gpu.rs b/src/crates/concat-render/src/gpu.rsindex c4f9d78a..40a9e012 100644--- a/src/crates/concat-render/src/gpu.rs+++ b/src/crates/concat-render/src/gpu.rs@@ -33,6 +33,7 @@use std::collections::HashMap;use concat_core::frame::Frame;+use concat_core::mask::MaskUniform;use concat_core::shader::{Lut, RevealMap, ShaderPass, TransitionPass};use concat_core::timeline::Blend;@@ -59,6 +60,10 @@ struct Vertex {/// `0..1` across the picture as it is seen: what the mask is sampled/// at and what the wipes measure.pic: [f32; 2],+ /// The layer's shape mask, packed; see `MaskUniform` and `MASK_WGSL`.+ shape_a: [f32; 4],+ shape_b: [f32; 4],+ shape_c: [f32; 4],}/// Vertex data as raw bytes. `Vertex` is `repr(C)` and all `f32`, so its byte@@ -74,6 +79,95 @@ fn as_bytes(vertices: &[Vertex]) -> &[u8] {}}+/// A layer's shape mask, per fragment: `concat_core::mask::coverage` line+/// for line, which the CPU reference calls and the tests hold this to.+/// `a` is the shape's code, the invert, the feather band and the corner+/// radius; `b` the centre and the half box; `c` the turn's cosine and sine+/// and the picture's sides over its shorter one.+const MASK_WGSL: &str = r#"+fn mask_sign(value: f32) -> f32 {+ return select(select(0.0, -1.0, value < 0.0), 1.0, value > 0.0);+}++fn mask_ellipse(p: vec2<f32>, r: vec2<f32>) -> f32 {+ let k0 = length(p / r);+ let k1 = length(p / (r * r));+ if (k1 <= 1e-9) {+ return -min(r.x, r.y);+ }+ return k0 * (k0 - 1.0) / k1;+}++fn mask_box(p: vec2<f32>, half: vec2<f32>, radius: f32) -> f32 {+ let q = abs(p) - half + vec2<f32>(radius, radius);+ return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - radius;+}++fn mask_heart(p: vec2<f32>) -> f32 {+ let x = abs(p.x);+ let y = p.y;+ if (y + x > 1.0) {+ return length(vec2<f32>(x - 0.25, y - 0.75)) - sqrt(2.0) / 4.0;+ }+ let m = max(x + y, 0.0) * 0.5;+ let a = vec2<f32>(x, y - 1.0);+ let b = vec2<f32>(x - m, y - m);+ return sqrt(min(dot(a, a), dot(b, b))) * mask_sign(x - y);+}++fn mask_star(x: f32, y: f32) -> f32 {+ let k1 = vec2<f32>(0.809017, -0.58778524);+ let k2 = vec2<f32>(-0.809017, -0.58778524);+ let inner = 0.45;+ var p = vec2<f32>(abs(x), y);+ p = p - max(dot(k1, p), 0.0) * 2.0 * k1;+ p = p - max(dot(k2, p), 0.0) * 2.0 * k2;+ p.x = abs(p.x);+ p.y = p.y - 1.0;+ let ba = vec2<f32>(inner * -k1.y, inner * k1.x - 1.0);+ let h = clamp(dot(p, ba) / dot(ba, ba), 0.0, 1.0);+ return length(p - ba * h) * mask_sign(p.y * ba.x - p.x * ba.y);+}++fn mask_distance(code: f32, p: vec2<f32>, half: vec2<f32>, radius: f32) -> f32 {+ let shape = i32(round(code));+ if (shape == 1) {+ return p.y;+ }+ if (shape == 2) {+ return abs(p.y) - half.y;+ }+ if (shape == 3) {+ return mask_ellipse(p, half);+ }+ if (shape == 4) {+ return mask_box(p, half, radius);+ }+ if (shape == 5) {+ let side = 0.6035534;+ let mid = 0.5517767;+ let q = vec2<f32>(p.x / half.x * side, mid - p.y / half.y * mid);+ return mask_heart(q) * min(half.x / side, half.y / mid);+ }+ if (shape == 6) {+ return mask_star(p.x / half.x, -p.y / half.y) * min(half.x, half.y);+ }+ return -1.0;+}++fn mask_coverage(a: vec4<f32>, b: vec4<f32>, c: vec4<f32>, pic: vec2<f32>) -> f32 {+ if (a.x < 0.5) {+ return 1.0;+ }+ let dx = (pic.x - 0.5 - b.x) * c.z;+ let dy = (pic.y - 0.5 - b.y) * c.w;+ let p = vec2<f32>(dx * c.x + dy * c.y, -dx * c.y + dy * c.x);+ let d = mask_distance(a.x, p, b.zw, a.w);+ let kept = 1.0 - smoothstep(-a.z * 0.5, a.z * 0.5, d);+ return select(kept, 1.0 - kept, a.y > 0.5);+}+"#;+const SHADER: &str = r#"struct VsIn {@location(0) position: vec2<f32>,@@ -83,6 +177,9 @@ struct VsIn {@location(4) offset: vec3<f32>,@location(5) edges: vec2<f32>,@location(6) pic: vec2<f32>,+ @location(7) shape_a: vec4<f32>,+ @location(8) shape_b: vec4<f32>,+ @location(9) shape_c: vec4<f32>,}struct VsOut {@@ -93,6 +190,9 @@ struct VsOut {@location(3) offset: vec3<f32>,@location(4) edges: vec2<f32>,@location(5) pic: vec2<f32>,+ @location(6) @interpolate(flat) shape_a: vec4<f32>,+ @location(7) @interpolate(flat) shape_b: vec4<f32>,+ @location(8) @interpolate(flat) shape_c: vec4<f32>,}@vertex@@ -105,6 +205,9 @@ fn vs_main(in: VsIn) -> VsOut {out.offset = in.offset;out.edges = in.edges;out.pic = in.pic;+ out.shape_a = in.shape_a;+ out.shape_b = in.shape_b;+ out.shape_c = in.shape_c;return out;}@@ -124,7 +227,9 @@ fn shade(in: VsOut) -> vec4<f32> {let mask = textureSample(mask_texture, mask_sampler, in.pic);// The wipes: a pixel past the moving edge is not drawn at all.let kept = select(0.0, 1.0, in.pic.x < in.edges.x && in.pic.x >= in.edges.y);- let alpha = colour.a * in.opacity * mask.a * kept;+ // The shape mask, multiplied in with the matte, the wipes and the rest.+ let shaped = mask_coverage(in.shape_a, in.shape_b, in.shape_c, in.pic);+ let alpha = colour.a * in.opacity * mask.a * kept * shaped;// The fades: the colour scaled and offset.let shaded = colour.rgb * in.scale + in.offset;return vec4<f32>(shaded, alpha);@@ -869,7 +974,7 @@ impl WgpuCompositor {let budget = pool_budget_for(device.adapter_info().device_type);let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {label: Some("concat compositor"),- source: wgpu::ShaderSource::Wgsl(SHADER.into()),+ source: wgpu::ShaderSource::Wgsl(format!("{MASK_WGSL}{SHADER}").into()),});let bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {@@ -983,7 +1088,8 @@ impl WgpuCompositor {step_mode: wgpu::VertexStepMode::Vertex,attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Float32, 3 => Float32,- 4 => Float32x3, 5 => Float32x2, 6 => Float32x2+ 4 => Float32x3, 5 => Float32x2, 6 => Float32x2,+ 7 => Float32x4, 8 => Float32x4, 9 => Float32x4],};@@ -1508,6 +1614,7 @@ impl WgpuCompositor {flips,opacity,layer.shading(),+ layer.shape_uniform(&geometry),plan.width,plan.height,));@@ -1556,6 +1663,9 @@ impl WgpuCompositor {offset: [0.0; 3],edges: [2.0, -1.0],pic: [u, v],+ shape_a: MaskUniform::NONE.a,+ shape_b: MaskUniform::NONE.b,+ shape_c: MaskUniform::NONE.c,}};let vertices = [@@ -1596,6 +1706,9 @@ impl WgpuCompositor {offset: [0.0; 3],edges: [2.0, -1.0],pic: [u, v],+ shape_a: MaskUniform::NONE.a,+ shape_b: MaskUniform::NONE.b,+ shape_c: MaskUniform::NONE.c,};vertices.extend_from_slice(&[corner(-1.0, 1.0, 0.0, 0.0),@@ -3272,6 +3385,7 @@ impl WgpuCompositor {(flip_h, flip_v): (bool, bool),opacity: f32,shading: Shading,+ shape: MaskUniform,out_width: u32,out_height: u32,) -> [Vertex; 6] {@@ -3299,6 +3413,9 @@ impl WgpuCompositor {offset: shading.offset,edges: [shading.left_edge, shading.right_edge],pic: [u, v],+ shape_a: shape.a,+ shape_b: shape.b,+ shape_c: shape.c,}};diff --git a/src/crates/concat-render/src/gpu/tests.rs b/src/crates/concat-render/src/gpu/tests.rsindex 100577b5..7aef9e28 100644--- a/src/crates/concat-render/src/gpu/tests.rs+++ b/src/crates/concat-render/src/gpu/tests.rs@@ -434,6 +434,128 @@ fn every_kind_of_layer_matches_the_cpu_reference() {assert_parity("faded and wiped", &plan(64, 48, vec![cut]), 0.99);}+/// A feathered circle on a white picture over black, read in the working+/// space where white is one: the light is the coverage. Whole in the+/// middle, half on the edge, nothing past the band - and the same number+/// the CPU's definition gives at each pixel's centre.+#[test]+fn a_feathered_circle_keeps_its_middle_and_fades_across_its_edge() {+ use concat_core::mask::{MaskShape, ShapeMask};+ let Some(mut gpu) = gpu() else { return };+ let mut circle = layer(solid(100, 100, [255, 255, 255, 255]));+ let shape = ShapeMask {+ shape: MaskShape::Circle,+ width: 0.6,+ height: 0.6,+ feather: 0.4,+ ..ShapeMask::default()+ };+ circle.shape = Some(shape);+ let drawn = working(&mut gpu, &plan(100, 100, vec![circle]));+ let at = |x: usize, y: usize| drawn[y * 100 + x][0];+ let expected = |x: usize, y: usize| {+ shape.coverage(+ (x as f32 + 0.5) / 100.0,+ (y as f32 + 0.5) / 100.0,+ 100.0,+ 100.0,+ 0.01,+ )+ };+ // The middle, a band inside the edge, the edge, and past the band.+ assert!((at(50, 50) - 1.0).abs() < 0.01, "middle {}", at(50, 50));+ assert!(+ (at(50 + 19, 50) - 1.0).abs() < 0.01,+ "inside {}",+ at(69, 50)+ );+ assert!((at(80, 50) - 0.5).abs() < 0.06, "edge {}", at(80, 50));+ assert!((at(50, 80) - 0.5).abs() < 0.06, "edge {}", at(50, 80));+ assert!(at(50 + 41, 50) < 0.01, "outside {}", at(91, 50));+ assert!(at(2, 2) < 0.001, "corner {}", at(2, 2));+ for (x, y) in [(75, 50), (80, 50), (85, 50), (50, 72), (64, 64), (71, 71)] {+ let (got, want) = (at(x, y), expected(x, y));+ assert!(+ (got - want).abs() < 0.01,+ "({x}, {y}): gpu {got}, cpu {want}"+ );+ }+}++/// Every shape against the CPU reference: turned, moved, feathered and+/// inverted, on a picture that is itself placed, cropped and carrying a+/// cutout's matte - the masks multiply.+#[test]+fn shape_masks_match_the_cpu_reference() {+ use concat_core::mask::{MaskShape, ShapeMask};+ for shape in MaskShape::ALL {+ for invert in [false, true] {+ let mut masked = layer(gradient(64, 48));+ masked.transform = Transform {+ scale: 0.9,+ rotation: 12.0,+ offset_x: 0.05,+ ..Transform::default()+ };+ masked.crop = Crop::of([0.1, 0.0, 0.05, 0.1]);+ // A stabilized clip's correction: the mask is on the picture+ // as corrected, so it holds still with it.+ masked.warp = Warp {+ a: 1.06,+ b: 0.03,+ tx: 0.02,+ ty: -0.01,+ };+ masked.shape = Some(ShapeMask {+ shape,+ x: 0.05,+ y: -0.04,+ width: 0.7,+ height: 0.5,+ rotation: 20.0,+ roundness: 0.5,+ feather: 0.15,+ invert,+ });+ let mut matte = Frame::transparent(16, 16);+ for y in 0..16u32 {+ for x in 0..16u32 {+ let a = if x < 3 { 0 } else { 255 };+ matte.set_pixel(x, y, [255, 255, 255, a]);+ }+ }+ masked.mask = Some(Arc::new(matte));+ assert_parity(+ &format!("{shape:?} mask, inverted {invert}"),+ &plan(64, 48, vec![layer(solid(64, 48, [0, 60, 0, 255])), masked]),+ 0.98,+ );+ }+ }+}++/// A masked picture never counts as covering the frame, and its canvas+/// background is drawn whole behind it - the mask cuts the picture, not+/// what stands behind it.+#[test]+fn a_masked_pictures_background_is_whole() {+ use concat_core::mask::ShapeMask;+ let mut masked = layer(solid(64, 48, [200, 0, 0, 255]));+ assert!(masked.covers(64, 48, true));+ masked.shape = Some(ShapeMask::default());+ assert!(!masked.covers(64, 48, true));+ let behind = masked+ .backdrop(&Backdrop::Colour([0, 0, 255]), 64, 48, |_| None)+ .expect("a colour always draws");+ assert!(behind.shape.is_none());+ let Some(mut gpu) = gpu() else { return };+ let frame = gpu.render(&plan(64, 48, vec![behind, masked]));+ let corner = frame.pixel(1, 1).expect("a pixel");+ let middle = frame.pixel(32, 24).expect("a pixel");+ assert!(corner[2] > 200 && corner[0] < 30, "blue behind: {corner:?}");+ assert!(middle[0] > 180 && middle[2] < 30, "red kept: {middle:?}");+}+/// What cannot be drawn is not drawn, the same way on both sides: a/// layer with a NaN opacity, one far outside the frame, one with no/// picture, and an opacity past one is one.diff --git a/src/crates/concat-render/src/plan.rs b/src/crates/concat-render/src/plan.rsindex 1996d738..279a9b1c 100644--- a/src/crates/concat-render/src/plan.rs+++ b/src/crates/concat-render/src/plan.rs@@ -26,6 +26,7 @@ use std::path::PathBuf;use std::sync::Arc;use concat_core::frame::{Frame, Signal};+use concat_core::mask::{MaskUniform, ShapeMask};use concat_core::shader::ShaderPass;use concat_core::time::Rational;use concat_core::timeline::{Blend, ClipId, Timeline, TrackKind, Transform};@@ -282,6 +283,11 @@ pub struct PlannedLayer {/// picture whatever its own size: what a cutout leaves. `None` keeps/// the picture whole.pub mask: Option<Arc<Frame>>,+ /// The clip's shape mask at this frame: a circle, a band, a heart that+ /// keeps part of the picture, drawn analytically over it and multiplied+ /// with `mask`, the crop and everything else that weighs the picture.+ /// `None` keeps it whole.+ pub shape: Option<ShapeMask>,/// What the cuts at either end do to the picture at this frame.pub transitions: Vec<Transition>,/// How the layer's colour meets what is beneath it.@@ -311,6 +317,7 @@ impl PlannedLayer {transform: Transform::default(),effects: Vec::new(),mask: None,+ shape: None,transitions: Vec::new(),blend: Blend::Normal,opacity: 1.0,@@ -328,6 +335,21 @@ impl PlannedLayer {}}+ /// The shape mask packed for the compositor, over the placement+ /// `geometry` gives: the picture's fitted size for its aspect, and one+ /// output pixel in its shorter side as the narrowest edge. The one+ /// place both compositors get it from, so the two cannot differ on it.+ pub fn shape_uniform(&self, geometry: &Geometry) -> MaskUniform {+ let Some(shape) = &self.shape else {+ return MaskUniform::NONE;+ };+ let (width, height) = (geometry.fitted.0 as f32, geometry.fitted.1 as f32);+ let (scale_x, scale_y) = geometry.scale;+ // One output pixel, in the picture's shorter side as it is drawn.+ let shown = (width * scale_x).min(height * scale_y).max(1.0);+ shape.uniform(width, height, 1.0 / shown)+ }+/// The transitions folded; see [`Shading`].pub fn shading(&self) -> Shading {Shading::of(&self.transitions)@@ -383,6 +405,7 @@ impl PlannedLayer {|| self.weight() < 1.0|| !self.effects.is_empty()|| self.mask.is_some()+ || self.shape.is_some()|| !self.transitions.is_empty()|| self.blend != Blend::Normal{@@ -428,6 +451,9 @@ impl PlannedLayer {let mut layer = PlannedLayer {transform: Transform::default(),mask: None,+ // The picture's shape mask is the picture's: the background+ // fills the frame behind it, and shows where the mask cuts.+ shape: None,blend: Blend::Normal,..self.clone()};@@ -796,6 +822,7 @@ pub fn plan_frame(timeline: &Timeline, time: Rational) -> FramePlan {transform: clip.transform_at(time),effects: Vec::new(),mask: None,+ shape: clip.mask_at(time),transitions: Vec::new(),blend: clip.blend,// The fade ramp multiplies in here, so the compositor only everdiff --git a/src/crates/concat-render/src/reference.rs b/src/crates/concat-render/src/reference.rsindex 8f82afb5..45935420 100644--- a/src/crates/concat-render/src/reference.rs+++ b/src/crates/concat-render/src/reference.rs@@ -15,6 +15,7 @@use std::borrow::Cow;use concat_core::frame::{BYTES_PER_PIXEL, Frame};+use concat_core::mask::{self, MaskUniform};use concat_core::shader::{ShaderPass, TransitionPass};use concat_core::timeline::Blend;@@ -96,6 +97,7 @@ fn draw(output: &mut Frame, plan: &FramePlan, layer: &PlannedLayer) {let weigh = Weighing {shading: layer.shading(),mask: layer.mask.as_deref(),+ shape: layer.shape_uniform(&geometry),opacity,blend: layer.blend,};@@ -134,6 +136,7 @@ fn prepare(source: &Frame, geometry: &Geometry, flip_h: bool, flip_v: bool) -> Fstruct Weighing<'a> {shading: Shading,mask: Option<&'a Frame>,+ shape: MaskUniform,opacity: f32,blend: Blend,}@@ -154,6 +157,7 @@ impl Weighing<'_> {);alpha *= sample_bilinear(mask, mx, my)[3] / 255.0;}+ alpha *= mask::coverage(&self.shape, u, v);if alpha <= 0.0 {return;}diff --git a/src/crates/concat/locales/ar.json b/src/crates/concat/locales/ar.jsonindex b556109f..1b304d00 100644--- a/src/crates/concat/locales/ar.json+++ b/src/crates/concat/locales/ar.json@@ -293,6 +293,17 @@"lib.pngImage": "صورة PNG","lib.saveFrame": "حفظ إطار الفيديو باسم","lib.wavAudio": "صوت WAV",+ "mask.circle": "دائرة",+ "mask.heart": "قلب",+ "mask.invert": "عكس",+ "mask.linear": "خطي",+ "mask.mirror": "مرآة",+ "mask.rectangle": "مستطيل",+ "mask.roundness": "استدارة الزوايا",+ "mask.row": "القناع · {0}",+ "mask.star": "نجمة",+ "mask.thickness": "السماكة",+ "mask.title": "قناع","mediaBin.importedFiles": "تم استيراد {0} ملفات","mediaBin.importedOneFile": "تم استيراد ملف واحد","mediaPane.allMedia": "كل الوسائط",diff --git a/src/crates/concat/locales/bn.json b/src/crates/concat/locales/bn.jsonindex e3a03a3c..918df9df 100644--- a/src/crates/concat/locales/bn.json+++ b/src/crates/concat/locales/bn.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG ছবি","lib.saveFrame": "ভিডিও ফ্রেম সংরক্ষণ করুন","lib.wavAudio": "WAV অডিও",+ "mask.circle": "বৃত্ত",+ "mask.heart": "হৃদয়",+ "mask.invert": "উল্টে দিন",+ "mask.linear": "লিনিয়ার",+ "mask.mirror": "মিরর",+ "mask.rectangle": "আয়তক্ষেত্র",+ "mask.roundness": "কোণের গোলাকারতা",+ "mask.row": "মাস্ক · {0}",+ "mask.star": "তারা",+ "mask.thickness": "পুরুত্ব",+ "mask.title": "মাস্ক","mediaBin.importedFiles": "{0}টি ফাইল আমদানি করা হয়েছে","mediaBin.importedOneFile": "১টি ফাইল আমদানি করা হয়েছে","mediaPane.allMedia": "সব মিডিয়া",diff --git a/src/crates/concat/locales/de.json b/src/crates/concat/locales/de.jsonindex 65875c0f..fe9ee5ae 100644--- a/src/crates/concat/locales/de.json+++ b/src/crates/concat/locales/de.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG-Bild","lib.saveFrame": "Videobild speichern unter","lib.wavAudio": "WAV-Audio",+ "mask.circle": "Kreis",+ "mask.heart": "Herz",+ "mask.invert": "Umkehren",+ "mask.linear": "Linear",+ "mask.mirror": "Spiegel",+ "mask.rectangle": "Rechteck",+ "mask.roundness": "Rundung",+ "mask.row": "Maske · {0}",+ "mask.star": "Stern",+ "mask.thickness": "Stärke",+ "mask.title": "Maske","mediaBin.importedFiles": "{0} Dateien importiert","mediaBin.importedOneFile": "1 Datei importiert","mediaPane.allMedia": "Alle Medien",diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.jsonindex c01f6bdf..605f4232 100644--- a/src/crates/concat/locales/en.json+++ b/src/crates/concat/locales/en.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG image","lib.saveFrame": "Save Video Frame As","lib.wavAudio": "WAV audio",+ "mask.circle": "Circle",+ "mask.heart": "Heart",+ "mask.invert": "Invert",+ "mask.linear": "Linear",+ "mask.mirror": "Mirror",+ "mask.rectangle": "Rectangle",+ "mask.roundness": "Roundness",+ "mask.row": "Mask · {0}",+ "mask.star": "Star",+ "mask.thickness": "Thickness",+ "mask.title": "Mask","mediaBin.importedFiles": "Imported {0} files","mediaBin.importedOneFile": "Imported 1 file","mediaPane.allMedia": "All media",diff --git a/src/crates/concat/locales/es.json b/src/crates/concat/locales/es.jsonindex f4e99827..b3211f71 100644--- a/src/crates/concat/locales/es.json+++ b/src/crates/concat/locales/es.json@@ -293,6 +293,17 @@"lib.pngImage": "Imagen PNG","lib.saveFrame": "Guardar fotograma como","lib.wavAudio": "Audio WAV",+ "mask.circle": "Círculo",+ "mask.heart": "Corazón",+ "mask.invert": "Invertir",+ "mask.linear": "Lineal",+ "mask.mirror": "Espejo",+ "mask.rectangle": "Rectángulo",+ "mask.roundness": "Redondeo",+ "mask.row": "Máscara · {0}",+ "mask.star": "Estrella",+ "mask.thickness": "Grosor",+ "mask.title": "Máscara","mediaBin.importedFiles": "{0} archivos importados","mediaBin.importedOneFile": "1 archivo importado","mediaPane.allMedia": "Todos los medios",diff --git a/src/crates/concat/locales/fa.json b/src/crates/concat/locales/fa.jsonindex a3cbe5bc..20537727 100644--- a/src/crates/concat/locales/fa.json+++ b/src/crates/concat/locales/fa.json@@ -293,6 +293,17 @@"lib.pngImage": "تصویر PNG","lib.saveFrame": "ذخیرهٔ فریم ویدیو بهعنوان","lib.wavAudio": "صدای WAV",+ "mask.circle": "دایره",+ "mask.heart": "قلب",+ "mask.invert": "وارونه",+ "mask.linear": "خطی",+ "mask.mirror": "آینه",+ "mask.rectangle": "مستطیل",+ "mask.roundness": "گردی گوشهها",+ "mask.row": "ماسک · {0}",+ "mask.star": "ستاره",+ "mask.thickness": "ضخامت",+ "mask.title": "ماسک","mediaBin.importedFiles": "{0} فایل وارد کردن شد","mediaBin.importedOneFile": "1 فایل وارد کردن شد","mediaPane.allMedia": "همه رسانهها",diff --git a/src/crates/concat/locales/fr.json b/src/crates/concat/locales/fr.jsonindex d42752da..a86ecc89 100644--- a/src/crates/concat/locales/fr.json+++ b/src/crates/concat/locales/fr.json@@ -293,6 +293,17 @@"lib.pngImage": "Image PNG","lib.saveFrame": "Enregistrer l’image vidéo sous","lib.wavAudio": "Audio WAV",+ "mask.circle": "Cercle",+ "mask.heart": "Cœur",+ "mask.invert": "Inverser",+ "mask.linear": "Linéaire",+ "mask.mirror": "Miroir",+ "mask.rectangle": "Rectangle",+ "mask.roundness": "Arrondi",+ "mask.row": "Masque · {0}",+ "mask.star": "Étoile",+ "mask.thickness": "Épaisseur",+ "mask.title": "Masque","mediaBin.importedFiles": "{0} fichiers importés","mediaBin.importedOneFile": "1 fichier importé","mediaPane.allMedia": "Tous les médias",diff --git a/src/crates/concat/locales/he.json b/src/crates/concat/locales/he.jsonindex 1e7e29e0..56c1453e 100644--- a/src/crates/concat/locales/he.json+++ b/src/crates/concat/locales/he.json@@ -293,6 +293,17 @@"lib.pngImage": "תמונת PNG","lib.saveFrame": "שמירת פריים הווידאו בשם","lib.wavAudio": "שמע WAV",+ "mask.circle": "עיגול",+ "mask.heart": "לב",+ "mask.invert": "היפוך",+ "mask.linear": "ליניארי",+ "mask.mirror": "מראה",+ "mask.rectangle": "מלבן",+ "mask.roundness": "עיגול פינות",+ "mask.row": "מסכה · {0}",+ "mask.star": "כוכב",+ "mask.thickness": "עובי",+ "mask.title": "מסכה","mediaBin.importedFiles": "יובאו {0} קבצים","mediaBin.importedOneFile": "יובא קובץ אחד","mediaPane.allMedia": "כל המדיה",diff --git a/src/crates/concat/locales/hi.json b/src/crates/concat/locales/hi.jsonindex 37bdfda7..3ced7fa6 100644--- a/src/crates/concat/locales/hi.json+++ b/src/crates/concat/locales/hi.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG इमेज","lib.saveFrame": "वीडियो फ़्रेम इस रूप में सेव करें","lib.wavAudio": "WAV ऑडियो",+ "mask.circle": "वृत्त",+ "mask.heart": "दिल",+ "mask.invert": "उलटें",+ "mask.linear": "रैखिक",+ "mask.mirror": "दर्पण",+ "mask.rectangle": "आयत",+ "mask.roundness": "कोनों की गोलाई",+ "mask.row": "मास्क · {0}",+ "mask.star": "तारा",+ "mask.thickness": "मोटाई",+ "mask.title": "मास्क","mediaBin.importedFiles": "{0} फ़ाइलें इंपोर्ट की गईं","mediaBin.importedOneFile": "1 फ़ाइल इंपोर्ट की गई","mediaPane.allMedia": "सभी मीडिया",diff --git a/src/crates/concat/locales/hr.json b/src/crates/concat/locales/hr.jsonindex 25d08a50..f4011ece 100644--- a/src/crates/concat/locales/hr.json+++ b/src/crates/concat/locales/hr.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG slika","lib.saveFrame": "Spremi sličicu videa kao","lib.wavAudio": "WAV zvuk",+ "mask.circle": "Krug",+ "mask.heart": "Srce",+ "mask.invert": "Obrni",+ "mask.linear": "Linearna",+ "mask.mirror": "Zrcalo",+ "mask.rectangle": "Pravokutnik",+ "mask.roundness": "Zaobljenost",+ "mask.row": "Maska · {0}",+ "mask.star": "Zvijezda",+ "mask.thickness": "Debljina",+ "mask.title": "Maska","mediaBin.importedFiles": "Uvezeno {0} datoteka","mediaBin.importedOneFile": "Uvezena 1 datoteka","mediaPane.allMedia": "Svi mediji",diff --git a/src/crates/concat/locales/id.json b/src/crates/concat/locales/id.jsonindex d5e1968d..5ed74784 100644--- a/src/crates/concat/locales/id.json+++ b/src/crates/concat/locales/id.json@@ -293,6 +293,17 @@"lib.pngImage": "Gambar PNG","lib.saveFrame": "Simpan Bingkai Video Sebagai","lib.wavAudio": "Audio WAV",+ "mask.circle": "Lingkaran",+ "mask.heart": "Hati",+ "mask.invert": "Balik",+ "mask.linear": "Linier",+ "mask.mirror": "Cermin",+ "mask.rectangle": "Persegi panjang",+ "mask.roundness": "Kebulatan sudut",+ "mask.row": "Masker · {0}",+ "mask.star": "Bintang",+ "mask.thickness": "Ketebalan",+ "mask.title": "Masker","mediaBin.importedFiles": "{0} file diimpor","mediaBin.importedOneFile": "1 file diimpor","mediaPane.allMedia": "Semua media",diff --git a/src/crates/concat/locales/it.json b/src/crates/concat/locales/it.jsonindex 646c212c..b979e545 100644--- a/src/crates/concat/locales/it.json+++ b/src/crates/concat/locales/it.json@@ -293,6 +293,17 @@"lib.pngImage": "Immagine PNG","lib.saveFrame": "Salva fotogramma come","lib.wavAudio": "Audio WAV",+ "mask.circle": "Cerchio",+ "mask.heart": "Cuore",+ "mask.invert": "Inverti",+ "mask.linear": "Lineare",+ "mask.mirror": "Specchio",+ "mask.rectangle": "Rettangolo",+ "mask.roundness": "Arrotondamento",+ "mask.row": "Maschera · {0}",+ "mask.star": "Stella",+ "mask.thickness": "Spessore",+ "mask.title": "Maschera","mediaBin.importedFiles": "{0} file importati","mediaBin.importedOneFile": "1 file importato","mediaPane.allMedia": "Tutti i media",diff --git a/src/crates/concat/locales/ja.json b/src/crates/concat/locales/ja.jsonindex 57d3e28b..342d4589 100644--- a/src/crates/concat/locales/ja.json+++ b/src/crates/concat/locales/ja.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG 画像","lib.saveFrame": "ビデオフレームを別名で保存","lib.wavAudio": "WAV 音声",+ "mask.circle": "円",+ "mask.heart": "ハート",+ "mask.invert": "反転",+ "mask.linear": "リニア",+ "mask.mirror": "ミラー",+ "mask.rectangle": "長方形",+ "mask.roundness": "角の丸み",+ "mask.row": "マスク · {0}",+ "mask.star": "星",+ "mask.thickness": "太さ",+ "mask.title": "マスク","mediaBin.importedFiles": "{0} 個のファイルを読み込みました","mediaBin.importedOneFile": "1 個のファイルを読み込みました","mediaPane.allMedia": "すべてのメディア",diff --git a/src/crates/concat/locales/ko.json b/src/crates/concat/locales/ko.jsonindex 5a1e735e..505cf884 100644--- a/src/crates/concat/locales/ko.json+++ b/src/crates/concat/locales/ko.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG 이미지","lib.saveFrame": "비디오 프레임을 다른 이름으로 저장","lib.wavAudio": "WAV 오디오",+ "mask.circle": "원",+ "mask.heart": "하트",+ "mask.invert": "반전",+ "mask.linear": "선형",+ "mask.mirror": "미러",+ "mask.rectangle": "직사각형",+ "mask.roundness": "모서리 둥글기",+ "mask.row": "마스크 · {0}",+ "mask.star": "별",+ "mask.thickness": "두께",+ "mask.title": "마스크","mediaBin.importedFiles": "파일 {0}개를 가져왔습니다","mediaBin.importedOneFile": "파일 1개를 가져왔습니다","mediaPane.allMedia": "모든 미디어",diff --git a/src/crates/concat/locales/nl.json b/src/crates/concat/locales/nl.jsonindex 04f7d523..d81c9306 100644--- a/src/crates/concat/locales/nl.json+++ b/src/crates/concat/locales/nl.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG-afbeelding","lib.saveFrame": "Videoframe opslaan als","lib.wavAudio": "WAV-audio",+ "mask.circle": "Cirkel",+ "mask.heart": "Hart",+ "mask.invert": "Omkeren",+ "mask.linear": "Lineair",+ "mask.mirror": "Spiegel",+ "mask.rectangle": "Rechthoek",+ "mask.roundness": "Afronding",+ "mask.row": "Masker · {0}",+ "mask.star": "Ster",+ "mask.thickness": "Dikte",+ "mask.title": "Masker","mediaBin.importedFiles": "Bestanden geïmporteerd: {0}","mediaBin.importedOneFile": "1 bestand geïmporteerd","mediaPane.allMedia": "Alle media",diff --git a/src/crates/concat/locales/pl.json b/src/crates/concat/locales/pl.jsonindex fd6ddd7a..f22e52a8 100644--- a/src/crates/concat/locales/pl.json+++ b/src/crates/concat/locales/pl.json@@ -293,6 +293,17 @@"lib.pngImage": "Obraz PNG","lib.saveFrame": "Zapisz klatkę wideo jako","lib.wavAudio": "Dźwięk WAV",+ "mask.circle": "Koło",+ "mask.heart": "Serce",+ "mask.invert": "Odwróć",+ "mask.linear": "Liniowa",+ "mask.mirror": "Lustro",+ "mask.rectangle": "Prostokąt",+ "mask.roundness": "Zaokrąglenie",+ "mask.row": "Maska · {0}",+ "mask.star": "Gwiazda",+ "mask.thickness": "Grubość",+ "mask.title": "Maska","mediaBin.importedFiles": "Zaimportowane pliki: {0}","mediaBin.importedOneFile": "Zaimportowano 1 plik","mediaPane.allMedia": "Wszystkie multimedia",diff --git a/src/crates/concat/locales/pt-BR.json b/src/crates/concat/locales/pt-BR.jsonindex f2d316a4..034270de 100644--- a/src/crates/concat/locales/pt-BR.json+++ b/src/crates/concat/locales/pt-BR.json@@ -293,6 +293,17 @@"lib.pngImage": "Imagem PNG","lib.saveFrame": "Salvar quadro do vídeo como","lib.wavAudio": "Áudio WAV",+ "mask.circle": "Círculo",+ "mask.heart": "Coração",+ "mask.invert": "Inverter",+ "mask.linear": "Linear",+ "mask.mirror": "Espelho",+ "mask.rectangle": "Retângulo",+ "mask.roundness": "Arredondamento",+ "mask.row": "Máscara · {0}",+ "mask.star": "Estrela",+ "mask.thickness": "Espessura",+ "mask.title": "Máscara","mediaBin.importedFiles": "{0} arquivos importados","mediaBin.importedOneFile": "1 arquivo importado","mediaPane.allMedia": "Todas as mídias",diff --git a/src/crates/concat/locales/ru.json b/src/crates/concat/locales/ru.jsonindex f27b631a..2e7e86ae 100644--- a/src/crates/concat/locales/ru.json+++ b/src/crates/concat/locales/ru.json@@ -293,6 +293,17 @@"lib.pngImage": "Изображение PNG","lib.saveFrame": "Сохранить кадр как","lib.wavAudio": "Звук WAV",+ "mask.circle": "Круг",+ "mask.heart": "Сердце",+ "mask.invert": "Инвертировать",+ "mask.linear": "Линейная",+ "mask.mirror": "Зеркало",+ "mask.rectangle": "Прямоугольник",+ "mask.roundness": "Скругление",+ "mask.row": "Маска · {0}",+ "mask.star": "Звезда",+ "mask.thickness": "Толщина",+ "mask.title": "Маска","mediaBin.importedFiles": "Импортировано файлов: {0}","mediaBin.importedOneFile": "Импортирован 1 файл","mediaPane.allMedia": "Все медиа",diff --git a/src/crates/concat/locales/th.json b/src/crates/concat/locales/th.jsonindex eb260aef..4aa2be68 100644--- a/src/crates/concat/locales/th.json+++ b/src/crates/concat/locales/th.json@@ -293,6 +293,17 @@"lib.pngImage": "ภาพ PNG","lib.saveFrame": "บันทึกเฟรมวิดีโอเป็น","lib.wavAudio": "เสียง WAV",+ "mask.circle": "วงกลม",+ "mask.heart": "หัวใจ",+ "mask.invert": "กลับด้าน",+ "mask.linear": "เชิงเส้น",+ "mask.mirror": "กระจก",+ "mask.rectangle": "สี่เหลี่ยมผืนผ้า",+ "mask.roundness": "ความโค้งมุม",+ "mask.row": "มาสก์ · {0}",+ "mask.star": "ดาว",+ "mask.thickness": "ความหนา",+ "mask.title": "มาสก์","mediaBin.importedFiles": "นำเข้า {0} ไฟล์แล้ว","mediaBin.importedOneFile": "นำเข้า 1 ไฟล์แล้ว","mediaPane.allMedia": "สื่อทั้งหมด",diff --git a/src/crates/concat/locales/tr.json b/src/crates/concat/locales/tr.jsonindex a6e3ca12..1b627559 100644--- a/src/crates/concat/locales/tr.json+++ b/src/crates/concat/locales/tr.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG görüntüsü","lib.saveFrame": "Video karesini farklı kaydet","lib.wavAudio": "WAV sesi",+ "mask.circle": "Daire",+ "mask.heart": "Kalp",+ "mask.invert": "Ters çevir",+ "mask.linear": "Doğrusal",+ "mask.mirror": "Ayna",+ "mask.rectangle": "Dikdörtgen",+ "mask.roundness": "Köşe yuvarlaklığı",+ "mask.row": "Maske · {0}",+ "mask.star": "Yıldız",+ "mask.thickness": "Kalınlık",+ "mask.title": "Maske","mediaBin.importedFiles": "{0} dosya içe aktarıldı","mediaBin.importedOneFile": "1 dosya içe aktarıldı","mediaPane.allMedia": "Tüm medya",diff --git a/src/crates/concat/locales/uk.json b/src/crates/concat/locales/uk.jsonindex bc5acf76..3713262e 100644--- a/src/crates/concat/locales/uk.json+++ b/src/crates/concat/locales/uk.json@@ -293,6 +293,17 @@"lib.pngImage": "Зображення PNG","lib.saveFrame": "Зберегти кадр відео як","lib.wavAudio": "Аудіо WAV",+ "mask.circle": "Коло",+ "mask.heart": "Серце",+ "mask.invert": "Інвертувати",+ "mask.linear": "Лінійна",+ "mask.mirror": "Дзеркало",+ "mask.rectangle": "Прямокутник",+ "mask.roundness": "Заокруглення",+ "mask.row": "Маска · {0}",+ "mask.star": "Зірка",+ "mask.thickness": "Товщина",+ "mask.title": "Маска","mediaBin.importedFiles": "Імпортовано файлів: {0}","mediaBin.importedOneFile": "Імпортовано 1 файл","mediaPane.allMedia": "Усі медіа",diff --git a/src/crates/concat/locales/ur.json b/src/crates/concat/locales/ur.jsonindex 4743f019..5ac154ad 100644--- a/src/crates/concat/locales/ur.json+++ b/src/crates/concat/locales/ur.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG تصویر","lib.saveFrame": "ویڈیو فریم بطور محفوظ کریں","lib.wavAudio": "WAV آڈیو",+ "mask.circle": "دائرہ",+ "mask.heart": "دل",+ "mask.invert": "الٹ دیں",+ "mask.linear": "خطی",+ "mask.mirror": "آئینہ",+ "mask.rectangle": "مستطیل",+ "mask.roundness": "کونوں کی گولائی",+ "mask.row": "ماسک · {0}",+ "mask.star": "ستارہ",+ "mask.thickness": "موٹائی",+ "mask.title": "ماسک","mediaBin.importedFiles": "{0} فائلیں امپورٹ ہوئیں","mediaBin.importedOneFile": "1 فائل امپورٹ ہوئی","mediaPane.allMedia": "تمام میڈیا",diff --git a/src/crates/concat/locales/vi.json b/src/crates/concat/locales/vi.jsonindex 3d82ef8f..33c4e23f 100644--- a/src/crates/concat/locales/vi.json+++ b/src/crates/concat/locales/vi.json@@ -293,6 +293,17 @@"lib.pngImage": "Ảnh PNG","lib.saveFrame": "Lưu khung hình video thành","lib.wavAudio": "Âm thanh WAV",+ "mask.circle": "Hình tròn",+ "mask.heart": "Trái tim",+ "mask.invert": "Đảo ngược",+ "mask.linear": "Tuyến tính",+ "mask.mirror": "Gương",+ "mask.rectangle": "Hình chữ nhật",+ "mask.roundness": "Độ bo góc",+ "mask.row": "Mặt nạ · {0}",+ "mask.star": "Ngôi sao",+ "mask.thickness": "Độ dày",+ "mask.title": "Mặt nạ","mediaBin.importedFiles": "Đã nhập {0} tệp","mediaBin.importedOneFile": "Đã nhập 1 tệp","mediaPane.allMedia": "Tất cả phương tiện",diff --git a/src/crates/concat/locales/zh-Hans.json b/src/crates/concat/locales/zh-Hans.jsonindex e008f9ae..2e215246 100644--- a/src/crates/concat/locales/zh-Hans.json+++ b/src/crates/concat/locales/zh-Hans.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG 图像","lib.saveFrame": "视频帧另存为","lib.wavAudio": "WAV 音频",+ "mask.circle": "圆形",+ "mask.heart": "爱心",+ "mask.invert": "反转",+ "mask.linear": "线性",+ "mask.mirror": "镜面",+ "mask.rectangle": "矩形",+ "mask.roundness": "圆角",+ "mask.row": "蒙版 · {0}",+ "mask.star": "星形",+ "mask.thickness": "厚度",+ "mask.title": "蒙版","mediaBin.importedFiles": "已导入 {0} 个文件","mediaBin.importedOneFile": "已导入 1 个文件","mediaPane.allMedia": "所有媒体",diff --git a/src/crates/concat/locales/zh-TW.json b/src/crates/concat/locales/zh-TW.jsonindex b1c59ba4..0c94cb91 100644--- a/src/crates/concat/locales/zh-TW.json+++ b/src/crates/concat/locales/zh-TW.json@@ -293,6 +293,17 @@"lib.pngImage": "PNG 影像","lib.saveFrame": "影片畫格另存為","lib.wavAudio": "WAV 音訊",+ "mask.circle": "圓形",+ "mask.heart": "愛心",+ "mask.invert": "反轉",+ "mask.linear": "線性",+ "mask.mirror": "鏡面",+ "mask.rectangle": "矩形",+ "mask.roundness": "圓角",+ "mask.row": "遮罩 · {0}",+ "mask.star": "星形",+ "mask.thickness": "厚度",+ "mask.title": "遮罩","mediaBin.importedFiles": "已匯入 {0} 個檔案","mediaBin.importedOneFile": "已匯入 1 個檔案","mediaPane.allMedia": "所有媒體",diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rsindex 9566f07f..4971c43b 100644--- a/src/crates/concat/src/studio.rs+++ b/src/crates/concat/src/studio.rs@@ -47,6 +47,8 @@ use concat_project::{Command, PlayheadSide};mod backdrop;mod consolidate;use consolidate::MergeJob;+mod masking;+use masking::{MaskFrame, MaskGrip};use slint::{Model, ModelRc, SharedString, VecModel};use crate::dock::{@@ -509,6 +511,14 @@ pub enum Gesture {centre: (f64, f64),from: f64,},+ /// A grip of the selected clip's mask dragged: the mask as the press+ /// found it, placed in the frame, and the press in frame pixels.+ StageMask {+ clip: String,+ grip: MaskGrip,+ frame: MaskFrame,+ from: (f64, f64),+ },/// A brush on the stage: the stroke so far, in source fractions for/// the command it becomes and in stage fractions for the line drawn/// under the pointer meanwhile.@@ -1277,6 +1287,13 @@ fn key_field_of(property: model::KeyProperty) -> ClipField {model::KeyProperty::Rotation => ClipField::Rotation,model::KeyProperty::Opacity => ClipField::Opacity,model::KeyProperty::Volume => ClipField::Volume,+ model::KeyProperty::MaskX => ClipField::MaskX,+ model::KeyProperty::MaskY => ClipField::MaskY,+ model::KeyProperty::MaskWidth => ClipField::MaskWidth,+ model::KeyProperty::MaskHeight => ClipField::MaskHeight,+ model::KeyProperty::MaskRotation => ClipField::MaskRotation,+ model::KeyProperty::MaskRoundness => ClipField::MaskRoundness,+ model::KeyProperty::MaskFeather => ClipField::MaskFeather,}}@@ -1363,6 +1380,10 @@ fn knob_range(property: model::KeyProperty) -> (f64, f64) {model::KeyProperty::Rotation => (-180.0, 180.0),model::KeyProperty::Opacity => (0.0, 1.0),model::KeyProperty::Volume => (-60.0, 24.0),+ model::KeyProperty::MaskX | model::KeyProperty::MaskY => (-1.0, 1.0),+ model::KeyProperty::MaskWidth | model::KeyProperty::MaskHeight => (0.01, 4.0),+ model::KeyProperty::MaskRotation => (-180.0, 180.0),+ model::KeyProperty::MaskRoundness | model::KeyProperty::MaskFeather => (0.0, 1.0),}}@@ -1414,6 +1435,12 @@ fn write_keyable(clip: &mut Clip, property: model::KeyProperty, value: f64, at:model::KeyProperty::Rotation => clip.rotation = value,model::KeyProperty::Opacity => clip.opacity = value,model::KeyProperty::Volume => clip.volume = value,+ // The mask's numbers are the mask's; a number turned on a clip+ // with none puts one on, the shape a new one starts as.+ mask => clip+ .mask+ .get_or_insert_with(model::ClipMask::default)+ .set(mask, value),}}@@ -1511,6 +1538,9 @@ fn clip_commands(id: &str, before: &Clip, after: &Clip) -> Vec<Command> {if after.crop != before.crop {patch.crop = Some(after.crop);}+ if after.mask != before.mask {+ patch.mask = Some(after.mask);+ }commands.extend(key_commands(id, before, after));if after.text != before.text {patch.text = Some(after.text.clone());@@ -4767,6 +4797,7 @@ impl Studio {| Gesture::StageStretch { .. }| Gesture::TextWidth { .. }| Gesture::TextHeight { .. }+ | Gesture::StageMask { .. }| Gesture::Paint { .. } => {}}self.gesture = gesture;@@ -4864,6 +4895,7 @@ impl Studio {| Gesture::StageStretch { .. }| Gesture::TextWidth { .. }| Gesture::TextHeight { .. }+ | Gesture::StageMask { .. }| Gesture::Paint { .. }) => {self.gesture = other;}@@ -5008,6 +5040,43 @@ impl Studio {stabilize.tripod = value != 0.0;}}+ // The shape's place in the picker, or below zero for none.+ // A new shape keeps where the mask was, its turn, softness+ // and invert, and takes the new shape's own size.+ ClipField::MaskShape => {+ let shape = (value >= 0.0)+ .then(|| model::MaskShape::ALL.get(value as usize).copied())+ .flatten();+ clip.mask = shape.map(|shape| match clip.mask {+ Some(held) if held.shape == shape => held,+ Some(held) => model::ClipMask {+ x: held.x,+ y: held.y,+ rotation: held.rotation,+ roundness: held.roundness,+ feather: held.feather,+ invert: held.invert,+ ..model::ClipMask::of(shape)+ },+ None => model::ClipMask::of(shape),+ });+ }+ ClipField::MaskInvert => {+ if let Some(mask) = clip.mask.as_mut() {+ mask.invert = value != 0.0;+ }+ }+ ClipField::MaskX+ | ClipField::MaskY+ | ClipField::MaskWidth+ | ClipField::MaskHeight+ | ClipField::MaskRotation+ | ClipField::MaskRoundness+ | ClipField::MaskFeather => {+ if let Some(property) = Self::key_property_of(field) {+ write_keyable(clip, property, model::ClipMask::clamp(property, value), at);+ }+ }ClipField::Volume => {write_keyable(clip, model::KeyProperty::Volume, value.max(0.0), at)}@@ -5559,21 +5628,61 @@ impl Studio {.into_iter().map(|clip| {let footprint = self.footprint(clip);- StageItemData {+ let selected = self.selection.iter().any(|id| id == &clip.id);+ let mut item = StageItemData {id: clip.id.as_str().into(),kind: kind_of(clip),- selected: self.selection.iter().any(|id| id == &clip.id),+ selected,cx: footprint.cx as f32,cy: footprint.cy as f32,w: footprint.w as f32,h: footprint.h as f32,rotation: footprint.rotation as f32,scale: clip.scale as f32,+ mask: -1,+ ..Default::default()+ };+ // The mask's outline and grips, on the one clip selected.+ if selected+ && self.selection.len() == 1+ && let Some(frame) = self.mask_frame(clip)+ {+ let grips = frame.grips().map(|grip| frame.fraction(grip));+ item.mask = model::MaskShape::ALL+ .iter()+ .position(|shape| *shape == frame.mask.shape)+ .map_or(-1, |index| index as i32);+ item.mask_path = frame.outline().into();+ (item.mask_cx, item.mask_cy) = grips[0];+ (item.mask_wx, item.mask_wy) = grips[1];+ (item.mask_hx, item.mask_hy) = grips[2];+ (item.mask_kx, item.mask_ky) = grips[3];+ (item.mask_rx, item.mask_ry) = grips[4];+ (item.mask_fx, item.mask_fy) = grips[5];}+ item}).collect()}+ /// The clip's mask placed in the frame at the playhead, its keyed+ /// numbers at their ride's values; None for a clip with no mask or one+ /// that is not a picture.+ fn mask_frame(&self, clip: &Clip) -> Option<MaskFrame> {+ let held = clip.mask.filter(|_| clip.kind.is_visual())?;+ let at = place_in(clip, self.playhead);+ let mut mask = held;+ for property in model::KeyProperty::MASK {+ mask.set(property, shown(clip, property, at));+ }+ Some(MaskFrame::new(+ mask,+ &self.footprint(clip),+ self.output_size(),+ (clip.stretch_x, clip.stretch_y),+ ))+ }+/// The topmost picture under a frame point, skipping locked lanes the/// way a press on the lanes does.fn stage_hit(&self, x: f64, y: f64) -> Option<String> {@@ -5683,8 +5792,26 @@ impl Studio {if self.locked(&clip.track_id) {return;}- let footprint = self.footprint(&clip);let (width, height) = self.output_size();+ // A grip of the mask: the mask is what moves, not the picture.+ if let Some(grip) = MaskGrip::of(grip) {+ let Some(frame) = self.mask_frame(&clip) else {+ return;+ };+ self.flush_commit();+ self.begin_echo();+ self.gesture = Gesture::StageMask {+ clip: id.to_owned(),+ grip,+ frame,+ from: (+ f64::from(x) * f64::from(width),+ f64::from(y) * f64::from(height),+ ),+ };+ return;+ }+ let footprint = self.footprint(&clip);let centre = (footprint.cx * f64::from(width),footprint.cy * f64::from(height),@@ -5992,6 +6119,32 @@ impl Studio {clip.text.get_or_insert_with(TextStyle::default).max_height = next;}}+ Gesture::StageMask {+ clip,+ grip,+ frame,+ from,+ } => {+ let to = (x * f64::from(width), y * f64::from(height));+ let mut next = frame.dragged(*grip, *from, to);+ if snap && *grip == MaskGrip::Rotate {+ next.rotation = (next.rotation / 15.0).round() * 15.0;+ }+ let start = frame.mask;+ let playhead = self.playhead;+ if let Some(clip) = self.echo_clip_mut(clip) {+ let at = place_in(clip, playhead);+ // Only the numbers the grip moves: a keyed one the drag+ // left alone must not gain a key here.+ for property in model::KeyProperty::MASK {+ if let (Some(value), Some(was)) = (next.get(property), start.get(property))+ && value != was+ {+ write_keyable(clip, property, value, at);+ }+ }+ }+ }Gesture::StageRotate {clip,rotation,@@ -6038,6 +6191,7 @@ impl Studio {Gesture::StageScale { clip, .. }| Gesture::StageRotate { clip, .. }| Gesture::StageStretch { clip, .. }+ | Gesture::StageMask { clip, .. }| Gesture::TextWidth { clip, .. } => vec![clip],Gesture::Paint {clip,@@ -6106,6 +6260,16 @@ impl Studio {// snaps back to the ride the document still holds.// https://github.com/jub0t/Concat/issues/228commands.extend(key_commands(&id, before, after));+ // A mask's grips move its numbers that hold still.+ if after.mask != before.mask {+ commands.push(Command::UpdateClip {+ clip_id: id.clone(),+ patch: ClipPatch {+ mask: Some(after.mask),+ ..Default::default()+ },+ });+ }// A title's wrap width, from its side grips.if after.text != before.text {commands.push(Command::UpdateClip {@@ -9022,6 +9186,13 @@ impl Studio {ClipField::Rotation => model::KeyProperty::Rotation,ClipField::Opacity => model::KeyProperty::Opacity,ClipField::Volume => model::KeyProperty::Volume,+ ClipField::MaskX => model::KeyProperty::MaskX,+ ClipField::MaskY => model::KeyProperty::MaskY,+ ClipField::MaskWidth => model::KeyProperty::MaskWidth,+ ClipField::MaskHeight => model::KeyProperty::MaskHeight,+ ClipField::MaskRotation => model::KeyProperty::MaskRotation,+ ClipField::MaskRoundness => model::KeyProperty::MaskRoundness,+ ClipField::MaskFeather => model::KeyProperty::MaskFeather,_ => return None,})}@@ -9134,6 +9305,11 @@ impl Studio {};let mut rows = Vec::new();for property in model::KeyProperty::ALL {+ // The mask's numbers are rows only while there is a mask, or+ // keys left from one: seven rows of nothing otherwise.+ if property.is_mask() && clip.mask.is_none() && !clip.is_keyed(property) {+ continue;+ }// The same ranges and units as the inspector's knobs. The level// knob speaks decibels, floored where silence is.let (label, minimum, maximum, step, default_value, fmt, unit, unit_scale) =@@ -9198,6 +9374,76 @@ impl Studio {"",1.0,),+ model::KeyProperty::MaskX => (+ tf("mask.row", &[&t("common.positionX")]),+ -1.0,+ 1.0,+ 0.005,+ 0.0,+ ParamFormat::Centred,+ "%",+ 100.0,+ ),+ model::KeyProperty::MaskY => (+ tf("mask.row", &[&t("common.positionY")]),+ -1.0,+ 1.0,+ 0.005,+ 0.0,+ ParamFormat::Centred,+ "%",+ 100.0,+ ),+ model::KeyProperty::MaskWidth => (+ tf("mask.row", &[&t("common.width")]),+ 0.01,+ 4.0,+ 0.01,+ 0.66,+ ParamFormat::Fraction,+ "%",+ 100.0,+ ),+ model::KeyProperty::MaskHeight => (+ tf("mask.row", &[&t("common.height")]),+ 0.01,+ 4.0,+ 0.01,+ 0.66,+ ParamFormat::Fraction,+ "%",+ 100.0,+ ),+ model::KeyProperty::MaskRotation => (+ tf("mask.row", &[&t("common.rotation")]),+ -180.0,+ 180.0,+ 1.0,+ 0.0,+ ParamFormat::Degrees,+ "°",+ 1.0,+ ),+ model::KeyProperty::MaskRoundness => (+ tf("mask.row", &[&t("mask.roundness")]),+ 0.0,+ 1.0,+ 0.01,+ 0.0,+ ParamFormat::Fraction,+ "%",+ 100.0,+ ),+ model::KeyProperty::MaskFeather => (+ tf("mask.row", &[&t("clipInspector.feather")]),+ 0.0,+ 1.0,+ 0.01,+ 0.0,+ ParamFormat::Fraction,+ "%",+ 100.0,+ ),};let to_knob = |value: f64| knob_value(property, value);let keys: Vec<(f64, f64, model::KeyEase)> = clip@@ -9892,6 +10138,18 @@ impl Studio {crop_top: clip.crop.map(|crop| crop.top as f32).unwrap_or(0.0),crop_right: clip.crop.map(|crop| crop.right as f32).unwrap_or(0.0),crop_bottom: clip.crop.map(|crop| crop.bottom as f32).unwrap_or(0.0),+ mask: clip+ .mask+ .and_then(|mask| model::MaskShape::ALL.iter().position(|s| *s == mask.shape))+ .map_or(-1, |index| index as i32),+ mask_invert: clip.mask.is_some_and(|mask| mask.invert),+ mask_x: shown(clip, model::KeyProperty::MaskX, at) as f32,+ mask_y: shown(clip, model::KeyProperty::MaskY, at) as f32,+ mask_width: shown(clip, model::KeyProperty::MaskWidth, at) as f32,+ mask_height: shown(clip, model::KeyProperty::MaskHeight, at) as f32,+ mask_rotation: shown(clip, model::KeyProperty::MaskRotation, at) as f32,+ mask_roundness: shown(clip, model::KeyProperty::MaskRoundness, at) as f32,+ mask_feather: shown(clip, model::KeyProperty::MaskFeather, at) as f32,fade_in: clip.fade_in as f32,fade_out: clip.fade_out as f32,content: text.content.as_str().into(),diff --git a/src/crates/concat/src/studio/masking.rs b/src/crates/concat/src/studio/masking.rsnew file mode 100644index 00000000..6f25ddd4--- /dev/null+++ b/src/crates/concat/src/studio/masking.rs@@ -0,0 +1,409 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! A clip's mask on the monitor: its outline and its grips, and what a+//! drag on one of them does to it.+//!+//! The mask lives on the picture as it is seen (see `model::ClipMask`): its+//! centre a fraction of the picture's width and height from the middle,+//! its box in the picture's shorter side, its turn on top of the clip's.+//! This is that arithmetic run forwards into the frame, for the outline and+//! the grips, and backwards, for a drag. All in frame pixels, where a turn+//! is a turn; the overlay gets fractions of the frame.+//!+//! A picture pulled along one axis (`stretch_x` != `stretch_y`) draws its+//! mask pulled along with it, which a rotated outline here does not follow:+//! the grips are placed for the unpulled picture. Rare, and said here.++use concat_core::mask::{self, MaskUniform};+use concat_project::model::{ClipMask, MaskShape};++use super::Footprint;++/// Which grip a press landed on: what the overlay numbers them, from 20.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum MaskGrip {+ /// The centre: the whole mask moves.+ Move,+ /// The right edge's middle: the width.+ Width,+ /// The bottom edge's middle: the height, a band's thickness.+ Height,+ /// The bottom-right corner: both, keeping their proportion.+ Corner,+ /// The handle under the mask: the turn.+ Rotate,+ /// The handle above the mask, at the feather's outer edge: the softness.+ Feather,+}++impl MaskGrip {+ /// The first number the overlay gives a mask grip; the clip's own box+ /// has the ones below.+ pub const FIRST: i32 = 20;++ /// The grip the overlay's number names, if it is a mask's.+ pub fn of(number: i32) -> Option<MaskGrip> {+ Some(match number - Self::FIRST {+ 0 => MaskGrip::Move,+ 1 => MaskGrip::Width,+ 2 => MaskGrip::Height,+ 3 => MaskGrip::Corner,+ 4 => MaskGrip::Rotate,+ 5 => MaskGrip::Feather,+ _ => return None,+ })+ }+}++/// A mask placed in the frame: where its picture is and how it is turned,+/// and the mask's numbers at one instant.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct MaskFrame {+ /// The mask's numbers, keyed ones at their ride's value.+ pub mask: ClipMask,+ /// The picture's centre, in frame pixels.+ picture: (f64, f64),+ /// The picture's turn, radians.+ picture_turn: f64,+ /// The picture's size as drawn, in frame pixels.+ size: (f64, f64),+ /// The picture's shorter side as drawn, in frame pixels: the mask's+ /// unit of length.+ short: f64,+ /// The frame's size, for turning pixels into fractions.+ frame: (f64, f64),+}++impl MaskFrame {+ /// The mask on a picture whose box in the frame is `footprint`, in a+ /// frame `frame` pixels; `stretch` is the picture's pull along each+ /// axis, which its shorter side is measured without.+ pub fn new(+ mask: ClipMask,+ footprint: &Footprint,+ frame: (u32, u32),+ stretch: (f64, f64),+ ) -> MaskFrame {+ let (width, height) = (f64::from(frame.0), f64::from(frame.1));+ let size = (footprint.w * width, footprint.h * height);+ let short = (size.0 / stretch.0.max(1e-6))+ .min(size.1 / stretch.1.max(1e-6))+ .max(1.0);+ MaskFrame {+ mask,+ picture: (footprint.cx * width, footprint.cy * height),+ picture_turn: footprint.rotation.to_radians(),+ size,+ short,+ frame: (width, height),+ }+ }++ /// The mask's centre, in frame pixels.+ pub fn centre(&self) -> (f64, f64) {+ let along = (self.mask.x * self.size.0, self.mask.y * self.size.1);+ let (sin, cos) = self.picture_turn.sin_cos();+ (+ self.picture.0 + along.0 * cos - along.1 * sin,+ self.picture.1 + along.0 * sin + along.1 * cos,+ )+ }++ /// The mask's whole turn in the frame: the picture's and its own.+ fn turn(&self) -> f64 {+ self.picture_turn + self.mask.rotation.to_radians()+ }++ /// A point in the mask's own frame - pixels across and down from its+ /// centre, before its turn - as frame pixels.+ fn point(&self, local: (f64, f64)) -> (f64, f64) {+ let (cx, cy) = self.centre();+ let (sin, cos) = self.turn().sin_cos();+ (+ cx + local.0 * cos - local.1 * sin,+ cy + local.0 * sin + local.1 * cos,+ )+ }++ /// A frame pixel in the mask's own frame: the inverse of `point`.+ fn local(&self, at: (f64, f64)) -> (f64, f64) {+ let (cx, cy) = self.centre();+ let (dx, dy) = (at.0 - cx, at.1 - cy);+ let (sin, cos) = self.turn().sin_cos();+ (dx * cos + dy * sin, -dx * sin + dy * cos)+ }++ /// Half the box, in frame pixels: none across for a line or a band,+ /// none down for a line.+ fn half(&self) -> (f64, f64) {+ let shape = self.mask.shape.engine();+ let across = if shape.has_width() {+ self.mask.width * self.short / 2.0+ } else {+ 0.0+ };+ let down = if shape.has_height() {+ self.mask.height * self.short / 2.0+ } else {+ 0.0+ };+ (across, down)+ }++ /// How far the turn and feather handles stand off the box.+ fn stem(&self) -> f64 {+ (self.short * 0.08).max(12.0)+ }++ /// The grips, in frame pixels, in [`MaskGrip`] order from `Move`.+ pub fn grips(&self) -> [(f64, f64); 6] {+ let (hw, hh) = self.half();+ let band = self.mask.feather * self.short * 0.5;+ [+ self.point((0.0, 0.0)),+ self.point((hw, 0.0)),+ self.point((0.0, hh)),+ self.point((hw, hh)),+ self.point((0.0, hh + self.stem() * 1.6)),+ self.point((0.0, -(hh + band / 2.0 + self.stem()))),+ ]+ }++ /// A point of the frame as the overlay's path takes it: a thousandth+ /// of the frame's width across and of its height down.+ fn path_point(&self, at: (f64, f64)) -> String {+ format!(+ "{:.2} {:.2}",+ at.0 / self.frame.0 * 1000.0,+ at.1 / self.frame.1 * 1000.0+ )+ }++ /// The mask's outline as path commands on the overlay's thousand-unit+ /// box: a line or two across the picture for a line and a band, the+ /// edge itself for the rest - traced from the same distance the+ /// compositor draws, so a heart's outline is the heart that is kept.+ pub fn outline(&self) -> String {+ let (_, hh) = self.half();+ // Long enough to cross any picture the mask sits on.+ let reach = self.size.0.hypot(self.size.1);+ match self.mask.shape {+ MaskShape::Linear => format!(+ "M {} L {}",+ self.path_point(self.point((-reach, 0.0))),+ self.path_point(self.point((reach, 0.0)))+ ),+ MaskShape::Mirror => format!(+ "M {} L {} M {} L {}",+ self.path_point(self.point((-reach, -hh))),+ self.path_point(self.point((reach, -hh))),+ self.path_point(self.point((-reach, hh))),+ self.path_point(self.point((reach, hh)))+ ),+ _ => {+ let mut out = String::new();+ for (index, local) in self.edge(96).into_iter().enumerate() {+ let verb = if index == 0 { "M" } else { "L" };+ out.push_str(&format!("{verb} {} ", self.path_point(self.point(local))));+ }+ out.push('Z');+ out+ }+ }+ }++ /// `count` points round the shape's edge in its own frame, in pixels:+ /// along each ray from the centre, where the distance changes sign.+ fn edge(&self, count: usize) -> Vec<(f64, f64)> {+ let uniform: MaskUniform = self.mask.engine().uniform(1.0, 1.0, 0.0);+ let [code, _, _, radius] = uniform.a;+ let half = [uniform.b[2], uniform.b[3]];+ let reach = f64::from(half[0].max(half[1])) * 2.0;+ (0..count)+ .map(|index| {+ let angle = index as f64 / count as f64 * std::f64::consts::TAU;+ let (sin, cos) = angle.sin_cos();+ let inside = |r: f64| {+ mask::distance(code, [(cos * r) as f32, (sin * r) as f32], half, radius) < 0.0+ };+ // Walk out to the first point outside, then halve the step.+ let steps = 64;+ let mut outer = reach;+ for step in 1..=steps {+ let r = reach * step as f64 / steps as f64;+ if !inside(r) {+ outer = r;+ break;+ }+ }+ let mut inner = (outer - reach / steps as f64).max(0.0);+ for _ in 0..20 {+ let middle = (inner + outer) / 2.0;+ if inside(middle) {+ inner = middle;+ } else {+ outer = middle;+ }+ }+ let r = (inner + outer) / 2.0 * self.short;+ (cos * r, sin * r)+ })+ .collect()+ }++ /// The mask after `grip` is dragged from `from` to `to`, frame pixels;+ /// `self` is the mask as the press found it.+ pub fn dragged(&self, grip: MaskGrip, from: (f64, f64), to: (f64, f64)) -> ClipMask {+ let mut next = self.mask;+ match grip {+ MaskGrip::Move => {+ let (cx, cy) = self.centre();+ let moved = (+ cx + to.0 - from.0 - self.picture.0,+ cy + to.1 - from.1 - self.picture.1,+ );+ let (sin, cos) = self.picture_turn.sin_cos();+ let along = (+ moved.0 * cos + moved.1 * sin,+ -moved.0 * sin + moved.1 * cos,+ );+ next.x = along.0 / self.size.0.max(1.0);+ next.y = along.1 / self.size.1.max(1.0);+ }+ MaskGrip::Width => {+ next.width = 2.0 * self.local(to).0.abs() / self.short;+ }+ MaskGrip::Height => {+ next.height = 2.0 * self.local(to).1.abs() / self.short;+ }+ MaskGrip::Corner => {+ let before = self.local(from);+ let after = self.local(to);+ let ratio = after.0.hypot(after.1) / before.0.hypot(before.1).max(1.0);+ next.width = self.mask.width * ratio;+ next.height = self.mask.height * ratio;+ }+ MaskGrip::Rotate => {+ let (cx, cy) = self.centre();+ let swept = (to.1 - cy).atan2(to.0 - cx) - (from.1 - cy).atan2(from.0 - cx);+ let turned = self.mask.rotation + swept.to_degrees();+ next.rotation = (turned + 180.0).rem_euclid(360.0) - 180.0;+ }+ MaskGrip::Feather => {+ // Up the mask's own axis is softer.+ let pulled = self.local(from).1 - self.local(to).1;+ next.feather = self.mask.feather + pulled / (self.short * 0.5);+ }+ }+ next.tidy()+ }++ /// A point of the frame in pixels, as the overlay's fractions.+ pub fn fraction(&self, at: (f64, f64)) -> (f32, f32) {+ ((at.0 / self.frame.0) as f32, (at.1 / self.frame.1) as f32)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A 200 by 100 picture filling a 200 by 100 frame, unturned.+ fn whole() -> Footprint {+ Footprint {+ cx: 0.5,+ cy: 0.5,+ w: 1.0,+ h: 1.0,+ rotation: 0.0,+ }+ }++ fn placed(mask: ClipMask) -> MaskFrame {+ MaskFrame::new(mask, &whole(), (200, 100), (1.0, 1.0))+ }++ #[test]+ fn the_grips_sit_on_the_box_in_the_shorter_side() {+ let frame = placed(ClipMask {+ x: 0.25,+ width: 0.5,+ height: 0.4,+ ..ClipMask::of(MaskShape::Rectangle)+ });+ let grips = frame.grips();+ // A quarter of 200 right of the middle; the short side is 100.+ assert_eq!(grips[0], (150.0, 50.0));+ assert_eq!(grips[1], (175.0, 50.0));+ assert_eq!(grips[2], (150.0, 70.0));+ assert_eq!(grips[3], (175.0, 70.0));+ }++ #[test]+ fn a_drag_on_each_grip_does_what_it_says() {+ let frame = placed(ClipMask {+ width: 0.5,+ height: 0.5,+ ..ClipMask::of(MaskShape::Circle)+ });+ let moved = frame.dragged(MaskGrip::Move, (100.0, 50.0), (120.0, 40.0));+ assert!((moved.x - 0.1).abs() < 1e-9 && (moved.y + 0.1).abs() < 1e-9);+ let wider = frame.dragged(MaskGrip::Width, (125.0, 50.0), (140.0, 50.0));+ assert!((wider.width - 0.8).abs() < 1e-9);+ assert_eq!(wider.height, 0.5);+ let bigger = frame.dragged(MaskGrip::Corner, (125.0, 75.0), (150.0, 100.0));+ assert!((bigger.width - 1.0).abs() < 1e-9 && (bigger.height - 1.0).abs() < 1e-9);+ let turned = frame.dragged(MaskGrip::Rotate, (100.0, 90.0), (60.0, 50.0));+ assert!((turned.rotation - 90.0).abs() < 1e-6, "{}", turned.rotation);+ let softer = frame.dragged(MaskGrip::Feather, (100.0, 10.0), (100.0, 0.0));+ assert!((softer.feather - 0.2).abs() < 1e-9);+ }++ #[test]+ fn a_turned_picture_turns_its_mask_and_its_drags() {+ let footprint = Footprint {+ rotation: 90.0,+ ..whole()+ };+ let frame = MaskFrame::new(+ ClipMask {+ x: 0.25,+ ..ClipMask::of(MaskShape::Circle)+ },+ &footprint,+ (200, 100),+ (1.0, 1.0),+ );+ // A quarter of the picture's width to its right is down the frame+ // once the picture is turned a quarter clockwise.+ let (cx, cy) = frame.centre();+ assert!((cx - 100.0).abs() < 1e-9 && (cy - 100.0).abs() < 1e-9);+ // Dragging it back up to the middle puts it back in the middle.+ let back = frame.dragged(MaskGrip::Move, (100.0, 100.0), (100.0, 50.0));+ assert!(back.x.abs() < 1e-9 && back.y.abs() < 1e-9);+ }++ #[test]+ fn the_outline_traces_the_edge_the_compositor_keeps() {+ let frame = placed(ClipMask {+ width: 0.6,+ height: 0.6,+ ..ClipMask::of(MaskShape::Circle)+ });+ for (x, y) in frame.edge(16) {+ assert!((x.hypot(y) - 30.0).abs() < 0.01, "a circle of 30 pixels");+ }+ let star = placed(ClipMask::of(MaskShape::Star)).outline();+ assert!(star.starts_with("M ") && star.ends_with('Z'));+ let line = placed(ClipMask::of(MaskShape::Linear)).outline();+ assert_eq!(line.matches('L').count(), 1);+ assert_eq!(+ placed(ClipMask::of(MaskShape::Mirror))+ .outline()+ .matches('M')+ .count(),+ 2+ );+ }+}diff --git a/src/crates/concat/ui/icons.slint b/src/crates/concat/ui/icons.slintindex dc20a42c..1a864968 100644--- a/src/crates/concat/ui/icons.slint+++ b/src/crates/concat/ui/icons.slint@@ -53,6 +53,15 @@ export enum Glyph {sticker,/// a shape clip's badge: a triangle, a square and a circleshapes,+ /// the mask shapes, as the picker shows them: a line keeping what is+ /// above it, two lines a band runs between, a circle, a rectangle, a+ /// heart and a star+ mask-linear,+ mask-mirror,+ mask-circle,+ mask-rectangle,+ mask-heart,+ mask-star,chevron-right,sparkle,eye,@@ -281,6 +290,35 @@ export component Icon inherits Rectangle {+ " M14 3v4a2 2 0 0 0 2 2h4 M8 13h.01 M16 13h.01 M10 16s.8 1 2 1c1.3 0 2-1 2-1";}+ // The mask shapes. A line with the side it keeps marked above it;+ // two lines, the band a mirror keeps; then lucide's circle, a wide+ // lucide-style rounded rectangle, lucide/heart and lucide/star.+ if root.glyph == Glyph.mask-linear: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M3 14h18 M8 9l4-4l4 4 M12 5v6";+ }+ if root.glyph == Glyph.mask-mirror: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M3 7h18 M3 17h18 M12 10v4";+ }+ if root.glyph == Glyph.mask-circle: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0";+ }+ if root.glyph == Glyph.mask-rectangle: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M5 5h14a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3z";+ }+ if root.glyph == Glyph.mask-heart: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2"+ + "-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z";+ }+ if root.glyph == Glyph.mask-star: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26Z";+ }+// lucide/shapesif root.glyph == Glyph.shapes: Stroked {size: root.size; tint: root.tint; weight: root.weight;diff --git a/src/crates/concat/ui/inspector/clip-inspector.slint b/src/crates/concat/ui/inspector/clip-inspector.slintindex 5d274ed0..35589769 100644--- a/src/crates/concat/ui/inspector/clip-inspector.slint+++ b/src/crates/concat/ui/inspector/clip-inspector.slint@@ -1102,13 +1102,37 @@ export component VideoPanel inherits VerticalLayout {property <float> crop-right;property <float> crop-bottom;property <float> feather;+ property <float> mask-x;+ property <float> mask-y;+ property <float> mask-width;+ property <float> mask-height;+ property <float> mask-rotation;+ property <float> mask-roundness;+ property <float> mask-feather;property <float> smoothness;property <float> max-zoom;+ /// The mask's shape, as the picker orders them: -1 for none.+ property <int> mask: root.selected.mask;+ property <[string]> mask-names: [+ I18n.t("mask.linear"),+ I18n.t("mask.mirror"),+ I18n.t("mask.circle"),+ I18n.t("mask.rectangle"),+ I18n.t("mask.heart"),+ I18n.t("mask.star")+ ];function seed() {root.feather = root.selected.cutout-feather;root.smoothness = root.selected.stabilize-smoothness;root.max-zoom = root.selected.stabilize-max-zoom;+ root.mask-x = root.selected.mask-x;+ root.mask-y = root.selected.mask-y;+ root.mask-width = root.selected.mask-width;+ root.mask-height = root.selected.mask-height;+ root.mask-rotation = root.selected.mask-rotation;+ root.mask-roundness = root.selected.mask-roundness;+ root.mask-feather = root.selected.mask-feather;root.scale = root.selected.scale;root.offset-x = root.selected.offset-x;root.offset-y = root.selected.offset-y;@@ -1611,6 +1635,182 @@ export component VideoPanel inherits VerticalLayout {}}+ // The mask: a shape that keeps part of the picture, CapCut's Mask.+ // The row of shapes picks one - the first, None, takes it off - and+ // the numbers below place, size, turn and soften it, each keyable.+ // Drawn on the picture as it is seen, so it moves with the clip; the+ // monitor shows its outline with grips to drag while this is open.+ if root.selected.kind == ClipKind.video || root.selected.kind == ClipKind.image: Section {+ mask-header := SectionHeader {+ title: I18n.t("mask.title");+ collapsible: true;+ summary: root.mask < 0 ? I18n.t("common.none")+ : root.mask-names[Math.min(root.mask, root.mask-names.length - 1)]+ + (root.selected.mask-invert ? " · " + I18n.t("mask.invert") : "");+ }++ if mask-header.open: SectionBody {+ HorizontalLayout {+ padding-left: Theme.pad;+ padding-right: Theme.pad;+ spacing: 4px;+ ToolButton {+ glyph: Glyph.close;+ label: I18n.t("common.none");+ checked: root.mask < 0;+ clicked => { root.set(ClipField.mask-shape, -1); root.commit(); }+ }+ ToolButton {+ glyph: Glyph.mask-linear;+ label: root.mask-names[0];+ checked: root.mask == 0;+ clicked => { root.set(ClipField.mask-shape, 0); root.commit(); }+ }+ ToolButton {+ glyph: Glyph.mask-mirror;+ label: root.mask-names[1];+ checked: root.mask == 1;+ clicked => { root.set(ClipField.mask-shape, 1); root.commit(); }+ }+ ToolButton {+ glyph: Glyph.mask-circle;+ label: root.mask-names[2];+ checked: root.mask == 2;+ clicked => { root.set(ClipField.mask-shape, 2); root.commit(); }+ }+ ToolButton {+ glyph: Glyph.mask-rectangle;+ label: root.mask-names[3];+ checked: root.mask == 3;+ clicked => { root.set(ClipField.mask-shape, 3); root.commit(); }+ }+ ToolButton {+ glyph: Glyph.mask-heart;+ label: root.mask-names[4];+ checked: root.mask == 4;+ clicked => { root.set(ClipField.mask-shape, 4); root.commit(); }+ }+ ToolButton {+ glyph: Glyph.mask-star;+ label: root.mask-names[5];+ checked: root.mask == 5;+ clicked => { root.set(ClipField.mask-shape, 5); root.commit(); }+ }+ }++ if root.mask >= 0: SwitchRow {+ label: I18n.t("mask.invert");+ checked: root.selected.mask-invert;+ toggled(on) => { root.set(ClipField.mask-invert, on ? 1 : 0); root.commit(); }+ }++ if root.mask >= 0: Param {+ label: I18n.t("common.positionX");+ keyable: true;+ field: ClipField.mask-x;+ value <=> root.mask-x;+ minimum: -1;+ maximum: 1;+ step: 0.005;+ default-value: 0;+ fmt: ParamFormat.centred;+ unit: "%";+ unit-scale: 100;+ changed(v) => { root.set(ClipField.mask-x, v); root.commit(); }+ }++ if root.mask >= 0: Param {+ label: I18n.t("common.positionY");+ keyable: true;+ field: ClipField.mask-y;+ value <=> root.mask-y;+ minimum: -1;+ maximum: 1;+ step: 0.005;+ default-value: 0;+ fmt: ParamFormat.centred;+ unit: "%";+ unit-scale: 100;+ changed(v) => { root.set(ClipField.mask-y, v); root.commit(); }+ }++ // A line has no size, and a mirror only its thickness.+ if root.mask >= 2: Param {+ label: I18n.t("common.width");+ keyable: true;+ field: ClipField.mask-width;+ value <=> root.mask-width;+ minimum: 0.01;+ maximum: 4;+ step: 0.01;+ default-value: 0.66;+ fmt: ParamFormat.fraction;+ unit: "%";+ unit-scale: 100;+ changed(v) => { root.set(ClipField.mask-width, v); root.commit(); }+ }++ if root.mask >= 1: Param {+ label: root.mask == 1 ? I18n.t("mask.thickness") : I18n.t("common.height");+ keyable: true;+ field: ClipField.mask-height;+ value <=> root.mask-height;+ minimum: 0.01;+ maximum: 4;+ step: 0.01;+ default-value: root.mask == 1 ? 0.33 : 0.66;+ fmt: ParamFormat.fraction;+ unit: "%";+ unit-scale: 100;+ changed(v) => { root.set(ClipField.mask-height, v); root.commit(); }+ }++ if root.mask >= 0: Param {+ label: I18n.t("common.rotation");+ keyable: true;+ field: ClipField.mask-rotation;+ value <=> root.mask-rotation;+ minimum: -180;+ maximum: 180;+ step: 1;+ default-value: 0;+ fmt: ParamFormat.degrees;+ unit: "°";+ changed(v) => { root.set(ClipField.mask-rotation, v); root.commit(); }+ }++ if root.mask == 3: Param {+ label: I18n.t("mask.roundness");+ keyable: true;+ field: ClipField.mask-roundness;+ value <=> root.mask-roundness;+ minimum: 0;+ maximum: 1;+ step: 0.01;+ default-value: 0;+ fmt: ParamFormat.fraction;+ unit: "%";+ unit-scale: 100;+ changed(v) => { root.set(ClipField.mask-roundness, v); root.commit(); }+ }++ if root.mask >= 0: Param {+ label: I18n.t("clipInspector.feather");+ keyable: true;+ field: ClipField.mask-feather;+ value <=> root.mask-feather;+ minimum: 0;+ maximum: 1;+ step: 0.01;+ default-value: 0;+ fmt: ParamFormat.fraction;+ unit: "%";+ unit-scale: 100;+ changed(v) => { root.set(ClipField.mask-feather, v); root.commit(); }+ }+ }+ }+// What is cut off the source before it is fitted. Fractions of the// source's own edges, so a crop survives a change of output size.if !root.figure: Section {diff --git a/src/crates/concat/ui/timeline/model.slint b/src/crates/concat/ui/timeline/model.slintindex 05e0c8b3..4a92e67b 100644--- a/src/crates/concat/ui/timeline/model.slint+++ b/src/crates/concat/ui/timeline/model.slint@@ -183,6 +183,13 @@ export enum ClipField {/// which of the media's audio tracks the clip plays, as a row of/// Editor.audio-tracksaudio-track,+ /// the mask: its shape as a place in the picker, below zero for none;+ /// whether it keeps the outside; and its numbers, each keyable - the+ /// centre as fractions of the picture from its middle, the box in the+ /// picture's shorter side, the turn in degrees, the corners' roundness+ /// and the edge's softness 0..1+ mask-shape, mask-invert,+ mask-x, mask-y, mask-width, mask-height, mask-rotation, mask-roundness, mask-feather,}/// One keyable property's state at the playhead, as the inspector needs it.@@ -237,11 +244,11 @@ export global Keyframes {return { field: field, keyed: false, here: false, prev: false, next: false };}- /// This field's row. Slint has no lookup and the list is six long, so- /// the order Rust publishes them in *is* the index; `blank` covers the- /// moment before the first publish.+ /// This field's row. Slint has no lookup and the list is thirteen+ /// long, so the order Rust publishes them in *is* the index; `blank`+ /// covers the moment before the first publish.pure public function row(field: ClipField) -> ClipKeyData {- if (Keyframes.rows.length < 6) {+ if (Keyframes.rows.length < 13) {return Keyframes.blank(field);}return field == ClipField.scale ? Keyframes.rows[0]@@ -250,6 +257,13 @@ export global Keyframes {: field == ClipField.rotation ? Keyframes.rows[3]: field == ClipField.opacity ? Keyframes.rows[4]: field == ClipField.volume ? Keyframes.rows[5]+ : field == ClipField.mask-x ? Keyframes.rows[6]+ : field == ClipField.mask-y ? Keyframes.rows[7]+ : field == ClipField.mask-width ? Keyframes.rows[8]+ : field == ClipField.mask-height ? Keyframes.rows[9]+ : field == ClipField.mask-rotation ? Keyframes.rows[10]+ : field == ClipField.mask-roundness ? Keyframes.rows[11]+ : field == ClipField.mask-feather ? Keyframes.rows[12]: Keyframes.blank(field);}}@@ -374,6 +388,18 @@ export struct SelectedClipData {crop-top: float,crop-right: float,crop-bottom: float,+ /// the mask: its shape as a place in the picker (linear, mirror,+ /// circle, rectangle, heart, star), -1 for none; whether it is+ /// inverted; and its numbers at the playhead - see ClipField.mask-x+ mask: int,+ mask-invert: bool,+ mask-x: float,+ mask-y: float,+ mask-width: float,+ mask-height: float,+ mask-rotation: float,+ mask-roundness: float,+ mask-feather: float,fade-in: float,fade-out: float,@@ -514,6 +540,25 @@ export struct StageItemData {rotation: float,/// The clip's scale, for the readout under the box.scale: float,+ /// The selected clip's mask, when it has one and is the only one+ /// selected: its shape as a place in the picker (-1 for none), its+ /// outline as path commands on a thousand-unit box over the frame, and+ /// its grips' centres in fractions of the frame - the middle, the+ /// width's, the height's, the corner's, the turn's and the feather's.+ mask: int,+ mask-path: string,+ mask-cx: float,+ mask-cy: float,+ mask-wx: float,+ mask-wy: float,+ mask-hx: float,+ mask-hy: float,+ mask-kx: float,+ mask-ky: float,+ mask-rx: float,+ mask-ry: float,+ mask-fx: float,+ mask-fy: float,}/// One snap guide across the stage while a picture is dragged: the line thediff --git a/src/crates/concat/ui/workspace/preview-pane.slint b/src/crates/concat/ui/workspace/preview-pane.slintindex 3ef7ca98..137e2314 100644--- a/src/crates/concat/ui/workspace/preview-pane.slint+++ b/src/crates/concat/ui/workspace/preview-pane.slint@@ -461,6 +461,109 @@ component StageItem inherits Rectangle {}}+/// The selected clip's mask over it: the shape's outline, traced in Rust+/// from the distance the compositor draws, and its grips - the middle to+/// move it, the right edge for its width, the bottom for its height, the+/// corner for both, the round handle below to turn it and the one above,+/// at the feather's outer edge, to soften it. Numbered from 20, after the+/// clip's own grips; see `masking::MaskGrip`.+component MaskItem inherits Rectangle {+ in property <StageItemData> item;++ callback grip-pressed(grip: int, x: float, y: float);+ callback dragged(x: float, y: float, snap: bool);+ callback released();++ background: transparent;++ // A dark line under a light one, so the outline reads over any picture.+ Path {+ x: 0;+ y: 0;+ width: root.width;+ height: root.height;+ viewbox-width: 1000;+ viewbox-height: 1000;+ commands: root.item.mask-path;+ stroke: Theme.stage;+ stroke-width: 3px;+ }+ Path {+ x: 0;+ y: 0;+ width: root.width;+ height: root.height;+ viewbox-width: 1000;+ viewbox-height: 1000;+ commands: root.item.mask-path;+ stroke: #ffffff;+ stroke-width: 1.25px;+ }++ Grip {+ turn: true;+ at-x: root.item.mask-cx * root.width;+ at-y: root.item.mask-cy * root.height;+ stage-w: root.width; stage-h: root.height;+ cursor: MouseCursor.move;+ pressed(x, y) => { root.grip-pressed(20, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }+ // A line has no width and no height; a band only its thickness.+ if root.item.mask >= 2: Grip {+ at-x: root.item.mask-wx * root.width;+ at-y: root.item.mask-wy * root.height;+ stage-w: root.width; stage-h: root.height;+ cursor: MouseCursor.ew-resize;+ pressed(x, y) => { root.grip-pressed(21, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }+ if root.item.mask >= 1: Grip {+ at-x: root.item.mask-hx * root.width;+ at-y: root.item.mask-hy * root.height;+ stage-w: root.width; stage-h: root.height;+ cursor: MouseCursor.ns-resize;+ pressed(x, y) => { root.grip-pressed(22, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }+ if root.item.mask >= 2: Grip {+ at-x: root.item.mask-kx * root.width;+ at-y: root.item.mask-ky * root.height;+ stage-w: root.width; stage-h: root.height;+ cursor: MouseCursor.nwse-resize;+ pressed(x, y) => { root.grip-pressed(23, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }+ Grip {+ turn: true;+ at-x: root.item.mask-rx * root.width;+ at-y: root.item.mask-ry * root.height;+ stage-w: root.width; stage-h: root.height;+ cursor: MouseCursor.grab;+ pressed(x, y) => { root.grip-pressed(24, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }+ // The feather's handle: a hollow ring, unlike the others.+ feather := Grip {+ turn: true;+ at-x: root.item.mask-fx * root.width;+ at-y: root.item.mask-fy * root.height;+ stage-w: root.width; stage-h: root.height;+ cursor: MouseCursor.ns-resize;+ background: transparent;+ border-width: 2px;+ border-color: Theme.accent;+ pressed(x, y) => { root.grip-pressed(25, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }+}+/// One snap line, dashed by hand: Slint's Path strokes have no dash pattern,/// so the line is a run of short rectangles along the axis it marks. Thin and/// in the accent, the same as the box it is guiding.@@ -610,6 +713,17 @@ component StageOverlay inherits Rectangle {dragged(x, y, snap) => { root.dragged(x, y, snap); }released => { root.released(); }}+ // Over the clip's own box, so a mask grip on its edge wins.+ if entry.selected && entry.mask >= 0 && !root.painting: MaskItem {+ x: 0;+ y: 0;+ width: parent.width;+ height: parent.height;+ item: entry;+ grip-pressed(grip, x, y) => { root.grip-pressed(entry.id, grip, x, y); }+ dragged(x, y, snap) => { root.dragged(x, y, snap); }+ released => { root.released(); }+ }}}