forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

effects.rs413 lines, 21.5 KiBHistoryRawDownload
1//! The `effect` tool: a video clip's effects stack (blur, sharpen, vignette, glow, shake,
2//! chroma key, blend, masks) -- add, set, remove, move and list. The pixels are
3//! `engine::effects`; this is the argument handling and the replies. Every mutating op is one
4//! `set_effects` call, so one undo step.
5
6use engine::PlaybackSession;
7use engine::effects::{BlendMode, Effect, EffectKind, MAX_EFFECTS};
8use engine::project::{Lane, LaneKind};
9use serde_json::{Map, Value, json};
10
11use super::hear::record_pushes;
12use crate::parse;
13use crate::server::{Reply, Server, Tool, opt_str};
14
15const NO_PROJECT: &str = "no project open — call project_open or project_new first";
16
17const EFFECT_DOC: &str = r##"A video clip's effects stack: ops add, set, remove, move, list. The stack applies in order on the clip's placed picture (after its colour, fit and transform), in preview and in every export; a masked or keyed-out part shows the lanes below. Every mutating op is one undo step. Video lanes only; at most 16 effects per clip.
18- add {clip, kind, at?, params?, size?, color?, mode?}: a new effect at stack position `at` (default the end), at its defaults unless params say otherwise. size is pixelate's block size, the same as params {size}.
19- set {clip, index, params?, on?, color?, mode?}: changes the effect at stack position `index`; what is not named keeps its value. on:false switches it off without losing its settings.
20- remove {clip, index} · move {clip, from, to} (stack positions; `to` is where it lands).
21- list {clip}: the stack with each effect's position, kind, on/off and named values. list with no clip: the kinds with their parameters and ranges.
22params is {name: number}; a number outside a range is clamped and the reply says so. color:"#rrggbb" sets a chroma_key's red, green and blue; mode:"screen" sets a blend's mode (normal, multiply, screen, overlay, add, darken, lighten). Masks take invert as 1/0 or true/false.
23Effects are static: one value for the whole clip, unless keyed. Every numeric parameter of every effect can take keys through edit's effect_keys (the stack position is the effect index); a switch or a choice, such as a blend's mode or a mask's invert, stays static. A rect or ellipse mask's position can also follow a picture feature through the clip with track {clip, effect_index}. Distances (blur radius, shake amount, pixelate block size) are pixels at 1080 lines and scale with the frame height, so preview and export agree at any size. Ken Burns stays in transform_keys. Pixelate (size 2..200) makes mosaic blocks; a mask placed right after it limits the mosaic to that mask's shape and does not cut the clip, so an ellipse after a pixelate censors a face. Without a mask the whole picture is mosaiced. A stack that is empty or all switched off changes nothing. chroma_key and the masks reveal the lanes below; blend picks how the clip lies over them."##;
24
25pub fn tools() -> Vec<Tool> {
26 vec![Tool { name: "effect", description: EFFECT_DOC, schema: effect_schema, run: run_effect }]
27}
28
29fn effect_schema() -> Value {
30 json!({
31 "type": "object",
32 "properties": {
33 "op": { "type": "string", "enum": ["add", "set", "remove", "move", "list"], "description": "What to do." },
34 "clip": { "type": "string", "description": "A video clip address: LANE@START (V1@450) or LANE#INDEX (V1#0). Omit with op list to list the kinds." },
35 "kind": { "type": "string", "enum": EffectKind::ALL.map(EffectKind::name), "description": "add: which effect." },
36 "at": { "type": "integer", "description": "add: stack position (0 first). Default the end." },
37 "index": { "type": "integer", "description": "set, remove: the effect's stack position (0 first)." },
38 "from": { "type": "integer", "description": "move: stack position to take the effect from." },
39 "to": { "type": "integer", "description": "move: stack position it lands on." },
40 "params": { "type": "object", "description": "add, set: {name: number}, such as {\"radius\": 12}. op list with no clip shows the names and ranges." },
41 "size": { "type": "number", "description": "add: pixelate's block size in pixels at 1080 lines, 2..200." },
42 "on": { "type": "boolean", "description": "set: switch the effect on or off." },
43 "color": { "type": "string", "description": "chroma_key: the key colour as #rrggbb.", "examples": ["#00ff00"] },
44 "mode": { "type": "string", "enum": BlendMode::ALL.map(BlendMode::name), "description": "blend: how the clip lies over the lanes below." }
45 },
46 "required": ["op"]
47 })
48}
49
50fn kind_names() -> String {
51 EffectKind::ALL.map(EffectKind::name).join(", ")
52}
53
54/// A stack position argument.
55fn position(args: &Value, key: &str) -> Result<usize, String> {
56 match args.get(key) {
57 None | Some(Value::Null) => Err(format!("missing `{key}`: a stack position, 0 for the first effect")),
58 Some(v) => v.as_u64().map(|n| n as usize).ok_or_else(|| format!("{key} must be a whole number, 0 for the first effect")),
59 }
60}
61
62fn parse_color(s: &str) -> Result<[f32; 3], String> {
63 let h = s.trim().trim_start_matches('#');
64 if h.len() != 6 || !h.is_ascii() {
65 return Err(format!("color `{s}` is not #rrggbb"));
66 }
67 let ch = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).map(f32::from).map_err(|_| format!("color `{s}` is not #rrggbb"));
68 Ok([ch(0)?, ch(2)?, ch(4)?])
69}
70
71/// Applies `params`, `color` and `mode` of the call to `e`; returns notes for values clamped.
72fn apply_params(e: &mut Effect, args: &Value) -> Result<Vec<String>, String> {
73 let mut notes = Vec::new();
74 let mut put = |e: &mut Effect, name: &str, x: f64| -> Result<(), String> {
75 e.set(name, x as f32)?;
76 let got = f64::from(e.get(name).unwrap_or(0.0));
77 if (got - x).abs() > 1e-6 {
78 notes.push(format!("{name} {x} clamped to {got}"));
79 }
80 Ok(())
81 };
82 match args.get("params") {
83 None | Some(Value::Null) => {}
84 Some(Value::Object(m)) => {
85 for (k, v) in m {
86 let x = match v {
87 Value::Bool(b) => f64::from(u8::from(*b)),
88 v => v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| format!("{k} must be a number"))?,
89 };
90 put(e, k, x)?;
91 }
92 }
93 Some(_) => return Err("params must be an object of numbers, such as {\"radius\": 12}".to_owned()),
94 }
95 if let Some(c) = args.get("color").filter(|v| !v.is_null()) {
96 if e.kind != EffectKind::ChromaKey {
97 return Err(format!("color is for chroma_key; {} has no colour", e.kind.name()));
98 }
99 let rgb = parse_color(c.as_str().ok_or("color must be a string like \"#00ff00\"")?)?;
100 for (name, x) in ["red", "green", "blue"].into_iter().zip(rgb) {
101 put(e, name, f64::from(x))?;
102 }
103 }
104 if let Some(m) = args.get("mode").filter(|v| !v.is_null()) {
105 if e.kind != EffectKind::Blend {
106 return Err(format!("mode is for blend; {} has no mode", e.kind.name()));
107 }
108 let name = m.as_str().ok_or("mode must be a name such as \"screen\"")?;
109 let mode = BlendMode::from_name(name).ok_or_else(|| {
110 format!("unknown blend mode `{name}`; the modes are {}", BlendMode::ALL.map(BlendMode::name).join(", "))
111 })?;
112 let at = BlendMode::ALL.iter().position(|b| *b == mode).unwrap_or(0);
113 put(e, "mode", at as f64)?;
114 }
115 Ok(notes)
116}
117
118fn effect_json(i: usize, e: &Effect) -> Value {
119 let mut params = Map::new();
120 for p in e.kind.params() {
121 params.insert(p.name.to_owned(), json!(e.get(p.name)));
122 }
123 let mut v = json!({ "index": i, "kind": e.kind.name(), "label": e.kind.label(), "on": e.on, "params": params });
124 if e.kind == EffectKind::Blend {
125 v["mode"] = json!(BlendMode::from_value(e.values[0]).name());
126 }
127 v
128}
129
130fn effect_line(i: usize, e: &Effect) -> String {
131 let vals: Vec<String> = e
132 .kind
133 .params()
134 .iter()
135 .map(|p| match (e.kind, p.name) {
136 (EffectKind::Blend, "mode") => format!("mode={}", BlendMode::from_value(e.values[0]).name()),
137 _ => format!("{}={}", p.name, e.get(p.name).unwrap_or(0.0)),
138 })
139 .collect();
140 let keys = match e.keys.len() {
141 0 => String::new(),
142 n => format!(" keys={n}"),
143 };
144 format!("{i}: {} {} {}{keys}", e.kind.name(), if e.on { "on" } else { "off" }, vals.join(" "))
145}
146
147fn stack_text(stack: &[Effect]) -> String {
148 match stack.is_empty() {
149 true => "no effects".to_owned(),
150 false => stack.iter().enumerate().map(|(i, e)| effect_line(i, e)).collect::<Vec<_>>().join("\n"),
151 }
152}
153
154fn stack_json(addr: &str, stack: &[Effect]) -> Value {
155 json!({ "clip": addr, "effects": stack.iter().enumerate().map(|(i, e)| effect_json(i, e)).collect::<Vec<_>>() })
156}
157
158fn kinds_reply() -> Reply {
159 let mut lines = Vec::new();
160 let mut kinds = Vec::new();
161 for k in EffectKind::ALL {
162 let ps: Vec<String> =
163 k.params().iter().map(|p| format!("{} {}..{} (default {})", p.name, p.min, p.max, p.default)).collect();
164 lines.push(format!("{} — {}: {}", k.name(), k.label(), ps.join(", ")));
165 let params: Vec<Value> = k
166 .params()
167 .iter()
168 .map(|p| json!({ "name": p.name, "label": p.label, "min": p.min, "max": p.max, "default": p.default }))
169 .collect();
170 kinds.push(json!({ "kind": k.name(), "label": k.label(), "params": params }));
171 }
172 lines.push(format!("blend mode: {}", BlendMode::ALL.map(BlendMode::name).join(", ")));
173 Reply::ok(lines.join("\n")).with(json!({ "kinds": kinds }))
174}
175
176/// The clip's lane and index, refused unless it is a picture clip on an unlocked lane when
177/// `mutate`.
178fn resolve(s: &PlaybackSession, args: &Value, mutate: bool) -> Result<(Lane, usize, String), String> {
179 let addr = opt_str(args, "clip")
180 .ok_or("missing argument `clip`: give a clip address such as V1@450 (lane and start) or V1#0 (lane and index)")?;
181 let (lane, idx) = parse::clip(s, addr)?;
182 if lane.kind != LaneKind::Video {
183 return Err(format!("{addr}: effects are for picture clips on video lanes, and {} is not one", parse::lane_name(lane)));
184 }
185 if mutate {
186 super::edit::check_unlocked(s, &[lane])?;
187 }
188 Ok((lane, idx, parse::addr(lane, s.lane_clips(lane)[idx].start)))
189}
190
191fn out_of_range(what: &str, i: usize, len: usize) -> String {
192 match len {
193 0 => format!("{what} {i} is out of range: the clip has no effects; add one first"),
194 n => format!("{what} {i} is out of range: the stack has {n} effect{}, positions 0..{}", if n == 1 { "" } else { "s" }, n - 1),
195 }
196}
197
198/// The new stack for a mutating op, or the refusal.
199fn edit_stack(op: &str, args: &Value, mut stack: Vec<Effect>) -> Result<(Vec<Effect>, String, Vec<String>), String> {
200 let mut notes = Vec::new();
201 let what = match op {
202 "add" => {
203 let name = opt_str(args, "kind").ok_or_else(|| format!("add needs `kind`: one of {}", kind_names()))?;
204 let kind = EffectKind::from_name(name)
205 .ok_or_else(|| format!("unknown effect kind `{name}`; the kinds are {}", kind_names()))?;
206 if stack.len() >= MAX_EFFECTS {
207 return Err(format!("a clip holds at most {MAX_EFFECTS} effects; remove one first"));
208 }
209 let at = match args.get("at").filter(|v| !v.is_null()) {
210 None => stack.len(),
211 Some(_) => position(args, "at")?,
212 };
213 if at > stack.len() {
214 return Err(format!("at {at} is past the end: the stack has {} effects, so at is 0..{}", stack.len(), stack.len()));
215 }
216 let mut e = Effect::new(kind);
217 notes = apply_params(&mut e, args)?;
218 if let Some(size) = args.get("size").filter(|v| !v.is_null()) {
219 if kind != EffectKind::Pixelate {
220 return Err(format!("size is for pixelate; {} has no size", kind.name()));
221 }
222 let x = size.as_f64().filter(|x| x.is_finite()).ok_or("size must be a number of pixels, 2..200")?;
223 e.set("size", x as f32)?;
224 }
225 stack.insert(at, e);
226 format!("added {} at {at}", kind.name())
227 }
228 "set" => {
229 let i = position(args, "index")?;
230 let len = stack.len();
231 let e = stack.get_mut(i).ok_or_else(|| out_of_range("index", i, len))?;
232 notes = apply_params(e, args)?;
233 match args.get("on").filter(|v| !v.is_null()) {
234 None => {}
235 Some(Value::Bool(b)) => e.on = *b,
236 Some(_) => return Err("on must be true or false".to_owned()),
237 }
238 if args.get("params").is_none() && args.get("on").is_none() && args.get("color").is_none() && args.get("mode").is_none() {
239 return Err("set needs something to change: params, on, color or mode".to_owned());
240 }
241 format!("set {} {i}", e.kind.name())
242 }
243 "remove" => {
244 let i = position(args, "index")?;
245 if i >= stack.len() {
246 return Err(out_of_range("index", i, stack.len()));
247 }
248 format!("removed {} {i}", stack.remove(i).kind.name())
249 }
250 _ => {
251 let (from, to) = (position(args, "from")?, position(args, "to")?);
252 if from >= stack.len() {
253 return Err(out_of_range("from", from, stack.len()));
254 }
255 if to >= stack.len() {
256 return Err(out_of_range("to", to, stack.len()));
257 }
258 let e = stack.remove(from);
259 let name = e.kind.name();
260 stack.insert(to, e);
261 format!("moved {name} {from} → {to}")
262 }
263 };
264 Ok((stack, what, notes))
265}
266
267fn run_effect(srv: &mut Server, args: &Value) -> Reply {
268 let op = match opt_str(args, "op") {
269 Some(o @ ("add" | "set" | "remove" | "move" | "list")) => o,
270 Some(o) => return Reply::err(format!("unknown op `{o}`; the ops are add, set, remove, move, list")),
271 None => return Reply::err("missing argument `op`: add, set, remove, move or list"),
272 };
273 if op == "list" && args.get("clip").is_none_or(Value::is_null) {
274 return kinds_reply();
275 }
276 let Some(s) = srv.session.as_mut() else {
277 return Reply::err(NO_PROJECT);
278 };
279 let (lane, idx, addr) = match resolve(s, args, op != "list") {
280 Ok(v) => v,
281 Err(e) => return Reply::err(format!("effect {op}: {e}")),
282 };
283 let before = s.effects_of(lane, idx).to_vec();
284 if op == "list" {
285 return Reply::ok(format!("{addr}: {}", stack_text(&before))).with(stack_json(&addr, &before));
286 }
287 let (after, what, notes) = match edit_stack(op, args, before.clone()) {
288 Ok(v) => v,
289 Err(e) => return Reply::err(format!("effect {op} {addr}: {e}")),
290 };
291 let note = |notes: &[String]| notes.iter().map(|n| format!(" ({n})")).collect::<String>();
292 if after == before {
293 return Reply::ok(format!("{addr}: already set · {what}{}\n{}", note(&notes), stack_text(&after)))
294 .with(stack_json(&addr, &after));
295 }
296 let start = s.history_pushes();
297 if !s.set_effects(lane, idx, after) {
298 return Reply::err(format!("effect {op} {addr}: the engine refused it"));
299 }
300 let stack = s.effects_of(lane, idx).to_vec();
301 record_pushes(srv, start, format!("effect {op} {addr}"));
302 let undo = srv.ledger.len();
303 let mut j = stack_json(&addr, &stack);
304 j["undo_steps"] = json!(undo);
305 Reply::ok(format!("{addr}: {what}{} · undo step {undo}\n{}", note(&notes), stack_text(&stack))).with(j)
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 fn server() -> Server {
313 engine::ao::set_silent_output();
314 let p = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
315 let mut srv = Server::new();
316 srv.session = Some(PlaybackSession::open(p).expect("open test asset"));
317 srv
318 }
319
320 fn stack(srv: &Server) -> Vec<Effect> {
321 srv.session.as_ref().unwrap().effects_of(Lane::new(LaneKind::Video, 0), 0).to_vec()
322 }
323
324 #[test]
325 fn add_set_move_remove_are_one_undo_step_each() {
326 let mut srv = server();
327 let r = run_effect(&mut srv, &json!({"op": "add", "clip": "V1#0", "kind": "blur", "params": {"radius": 12}}));
328 assert!(!r.is_error && r.text.contains("added blur at 0") && r.text.contains("undo step 1"), "{}", r.text);
329 let r = run_effect(&mut srv, &json!({"op": "add", "clip": "V1#0", "kind": "vignette", "at": 0}));
330 assert!(!r.is_error, "{}", r.text);
331 assert_eq!(stack(&srv)[0].kind, EffectKind::Vignette);
332 assert_eq!(stack(&srv)[1].get("radius"), Some(12.0));
333 let r = run_effect(&mut srv, &json!({"op": "set", "clip": "V1#0", "index": 1, "params": {"radius": 500}, "on": false}));
334 assert!(!r.is_error && r.text.contains("radius 500 clamped to 100"), "{}", r.text);
335 assert!(!stack(&srv)[1].on && stack(&srv)[1].get("radius") == Some(100.0));
336 let r = run_effect(&mut srv, &json!({"op": "move", "clip": "V1#0", "from": 0, "to": 1}));
337 assert!(!r.is_error, "{}", r.text);
338 assert_eq!(stack(&srv)[1].kind, EffectKind::Vignette);
339 let r = run_effect(&mut srv, &json!({"op": "remove", "clip": "V1#0", "index": 0}));
340 assert!(!r.is_error && r.text.contains("removed blur") && r.text.contains("undo step 5"), "{}", r.text);
341 assert_eq!(stack(&srv).len(), 1);
342 let s = srv.session.as_mut().unwrap();
343 assert!(s.undo(), "remove undone alone");
344 assert_eq!(stack(&srv).len(), 2);
345 let s = srv.session.as_mut().unwrap();
346 for _ in 0..4 {
347 assert!(s.undo());
348 }
349 assert!(stack(&srv).is_empty());
350 }
351
352 #[test]
353 fn color_and_mode_conveniences_and_list() {
354 let mut srv = server();
355 let r = run_effect(&mut srv, &json!({"op": "add", "clip": "V1#0", "kind": "chroma_key", "color": "#00ff80", "params": {"tolerance": 0.4}}));
356 assert!(!r.is_error, "{}", r.text);
357 let e = stack(&srv)[0].clone();
358 assert_eq!((e.get("red"), e.get("green"), e.get("blue"), e.get("tolerance")), (Some(0.0), Some(255.0), Some(128.0), Some(0.4)));
359 let r = run_effect(&mut srv, &json!({"op": "add", "clip": "V1#0", "kind": "blend", "mode": "screen"}));
360 assert!(!r.is_error && r.text.contains("mode=screen"), "{}", r.text);
361 let r = run_effect(&mut srv, &json!({"op": "list", "clip": "V1#0"}));
362 let j = r.structured.as_deref().unwrap();
363 assert_eq!(j["effects"].as_array().unwrap().len(), 2);
364 assert_eq!(j["effects"][1]["mode"], "screen");
365 assert_eq!(j["effects"][0]["params"]["green"], 255.0);
366 let r = run_effect(&mut srv, &json!({"op": "list"}));
367 assert!(r.text.contains("ellipse_mask") && r.text.contains("radius 0..100"), "{}", r.text);
368 // Setting what is already there is not an undo step.
369 let r = run_effect(&mut srv, &json!({"op": "set", "clip": "V1#0", "index": 1, "mode": "screen"}));
370 assert!(r.text.contains("already set"), "{}", r.text);
371 assert_eq!(srv.ledger.len(), 2);
372 }
373
374 #[test]
375 fn refusals_are_specific_and_change_nothing() {
376 let mut srv = server();
377 let err = |srv: &mut Server, v: Value| {
378 let r = run_effect(srv, &v);
379 assert!(r.is_error, "{}", r.text);
380 r.text
381 };
382 let t = err(&mut srv, json!({"op": "add", "clip": "V1#0", "kind": "sparkle"}));
383 assert!(t.contains("unknown effect kind `sparkle`") && t.contains("chroma_key"), "{t}");
384 let t = err(&mut srv, json!({"op": "add", "clip": "V1#0", "kind": "blur", "params": {"size": 3}}));
385 assert!(t.contains("no parameter \"size\"") && t.contains("radius"), "{t}");
386 let t = err(&mut srv, json!({"op": "add", "clip": "V1#0", "kind": "blur", "color": "#fff000"}));
387 assert!(t.contains("color is for chroma_key"), "{t}");
388 let t = err(&mut srv, json!({"op": "add", "clip": "V1#0", "kind": "blend", "mode": "burn"}));
389 assert!(t.contains("unknown blend mode") && t.contains("multiply"), "{t}");
390 let t = err(&mut srv, json!({"op": "remove", "clip": "V1#0", "index": 0}));
391 assert!(t.contains("no effects"), "{t}");
392 let t = err(&mut srv, json!({"op": "add", "clip": "A1#0", "kind": "blur"}));
393 assert!(t.contains("not one"), "{t}");
394 let t = err(&mut srv, json!({"op": "add", "clip": "V1#0", "kind": "blur", "at": 3}));
395 assert!(t.contains("past the end"), "{t}");
396 for _ in 0..MAX_EFFECTS {
397 assert!(!run_effect(&mut srv, &json!({"op": "add", "clip": "V1#0", "kind": "sharpen"})).is_error);
398 }
399 let t = err(&mut srv, json!({"op": "add", "clip": "V1#0", "kind": "blur"}));
400 assert!(t.contains("at most 16"), "{t}");
401 let t = err(&mut srv, json!({"op": "move", "clip": "V1#0", "from": 0, "to": 16}));
402 assert!(t.contains("to 16 is out of range") && t.contains("0..15"), "{t}");
403 let t = err(&mut srv, json!({"op": "set", "clip": "V1#0", "index": 0}));
404 assert!(t.contains("needs something to change"), "{t}");
405 srv.session.as_mut().unwrap().set_lane_locked(Lane::new(LaneKind::Video, 0), true);
406 let t = err(&mut srv, json!({"op": "set", "clip": "V1#0", "index": 0, "on": false}));
407 assert!(t.contains("locked"), "{t}");
408 assert_eq!(stack(&srv).len(), MAX_EFFECTS);
409 assert_eq!(srv.ledger.len(), MAX_EFFECTS, "refusals pushed no undo step");
410 srv.session = None;
411 assert!(err(&mut srv, json!({"op": "list", "clip": "V1#0"})).contains("no project"));
412 }
413}