forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

edit_fx.rs4454 lines, 201.5 KiBHistoryRawDownload
1//! Look, sound and lane ops for the batched `edit` verb: grade, placement, fit,
2//! equalizer, lane gain and flags, the master limiter, grouping, subtitle import,
3//! and title cards.
4//!
5//! [`apply`] takes one op object and either applies it to the session or refuses it
6//! with one sentence. It returns `None` for an op name that is not one of these, so
7//! the caller can offer the op to the other groups.
8
9use std::path::Path;
10
11use engine::color::ColorParams;
12use engine::effects::{EffectKey, EffectKind, ParamSpec};
13use engine::duck::{
14 Duck, MAX_ATTACK_MS, MAX_DEPTH_DB, MAX_RELEASE_MS, MAX_THRESHOLD_DB, MIN_DEPTH_DB,
15 MIN_THRESHOLD_DB, MIN_TIME_MS,
16};
17use engine::eq::{Band, BandKind, EqParams};
18use engine::limiter::Limiter;
19use engine::project::{
20 check_title, gain_keys_db_at, Clip, GainKey, Lane, LaneKind, Title, TitlePreset, MAX_CLIP_GAIN_DB,
21 MAX_GAIN_KEYS, MIN_CLIP_GAIN_DB,
22};
23use engine::scale::FitPolicy;
24use engine::text::{layout_share, missing_glyphs, Align, HPlace, Outline, Place, TextStyle, Weight, SIZE_RANGE};
25use engine::color::{ColorKey, MAX_COLOR_KEYS};
26use engine::transform::{Bezier, Corner, KeyEase, OpacityKey, TransformKey, TransformParams, MAX_TRANSFORM_KEYS};
27use engine::titleanim::{KEY_SCALE_RANGE, TitleAnim, TitleKey};
28use engine::PlaybackSession;
29use serde_json::{json, Value};
30
31use super::edit::{check_unlocked, length, need, opt_time};
32use crate::parse;
33
34/// What one op did: a line for the reply, and the clips it touched as (lane, start
35/// frame), so the caller can re-address them after later ops in the batch.
36#[derive(Debug)]
37pub struct Applied {
38 pub text: String,
39 pub touched: Vec<(Lane, u32)>,
40}
41
42/// Applies one `{op: "...", ...}` if it is one of this module's ops.
43///
44/// `None` when `op["op"]` is missing or names an op this module does not own.
45/// `fps` is the project frame rate, which the time arguments (title times) need.
46pub fn apply(s: &mut PlaybackSession, op: &Value, fps: f64) -> Option<Result<Applied, String>> {
47 let name = op.get("op")?.as_str()?;
48 let r = match name {
49 "color" => color(s, op),
50 "transform" => transform(s, op),
51 "transform_keys" => transform_keys(s, op, fps),
52 "opacity_keys" => opacity_keys(s, op, fps),
53 "mask_keys" => mask_keys(s, op, fps),
54 "effect_keys" => effect_keys(s, op, fps),
55 "color_keys" => color_keys(s, op, fps),
56 "lut" => lut(s, op),
57 "wheels" => wheels(s, op),
58 "curves" => curves(s, op),
59 "look" => look(s, op),
60 "auto_color" => auto_color(s, op),
61 "fit" => fit(s, op),
62 "eq" => eq(s, op),
63 "gain" => gain(s, op),
64 "gain_keys" => gain_keys(s, op, fps),
65 "gain_key" => gain_key(s, op, fps),
66 "gain_key_remove" => gain_key_remove(s, op, fps),
67 "gain_ramp" => gain_ramp(s, op, fps),
68 "gain_dip" => gain_dip(s, op, fps),
69 "lane_gain" => lane_gain(s, op),
70 "pan" => pan(s, op),
71 "pitch" => pitch(s, op),
72 "lane_pan" => lane_pan(s, op),
73 "duck" => duck(s, op),
74 "dynamics" => super::voice::dynamics(s, op, fps),
75 "stabilize" => super::stabilise::op(s, op),
76 "reframe" => super::reframe::op(s, op),
77 "angle" => super::multicam::angle(s, op),
78 "nest" => super::sequence::nest(s, op),
79 "break_apart" => super::sequence::break_apart(s, op),
80 "place_sequence" => super::sequence::place_sequence(s, op),
81 "limiter" => limiter(s, op),
82 "lane_add" => lane_add(s, op),
83 "lane_remove" => lane_remove(s, op),
84 "lane_move" => lane_move(s, op),
85 "lane_flags" => lane_flags(s, op),
86 "lane_name" => lane_name(s, op),
87 "deinterlace" => deinterlace(s, op),
88 "group" => group(s, op),
89 "ungroup" => ungroup(s, op),
90 "subtitles_import" => subtitles_import(s, op),
91 "title_add" => title_add(s, op, fps),
92 "title_set" => title_set(s, op, fps),
93 "title_remove" => title_remove(s, op, fps),
94 _ => return None,
95 };
96 Some(r)
97}
98
99// ---- ops ------------------------------------------------------------------
100
101/// `color {clip, brightness?, contrast?, saturation?, tint?, reset?}`.
102/// Merges onto the clip's current grade; `reset` takes the grade off and wins
103/// over the other fields.
104fn color(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
105 let (lane, idx, raw, start) = clip_arg(s, op)?;
106 let who = format!("color {raw}");
107 let keyed = s.color_keys_of(lane, idx).len();
108 if keyed > 0 {
109 return Err(format!(
110 "{who}: {raw} has {keyed} colour key(s), and a keyed clip's grade is its keys; change them with color_keys, or take them off first with color_keys {{clip, clear:true}}"
111 ));
112 }
113 if flag(op, "reset")? {
114 if !s.set_color(lane, idx, None) {
115 return Err(refused(&who));
116 }
117 return Ok(done(format!("{who} → reset"), vec![(lane, start)]));
118 }
119 let mut c: ColorParams = s.color_of(lane, idx).copied().unwrap_or_default();
120 let mut shown = Vec::new();
121 if let Some(v) = num(op, "brightness")? {
122 c.brightness = ranged(&who, "brightness", v, -1.0, 1.0)?;
123 shown.push(format!("brightness {:.2}", c.brightness));
124 }
125 if let Some(v) = num(op, "contrast")? {
126 c.contrast = ranged(&who, "contrast", v, 0.0, 2.0)?;
127 shown.push(format!("contrast {:.2}", c.contrast));
128 }
129 if let Some(v) = num(op, "saturation")? {
130 c.saturation = ranged(&who, "saturation", v, 0.0, 2.0)?;
131 shown.push(format!("saturation {:.2}", c.saturation));
132 }
133 if let Some(v) = num(op, "tint")? {
134 c.tint = ranged(&who, "tint", v, -1.0, 1.0)?;
135 shown.push(format!("tint {:.2}", c.tint));
136 }
137 if shown.is_empty() {
138 return Err(format!(
139 "{who}: give at least one of brightness, contrast, saturation, tint, or reset:true"
140 ));
141 }
142 if !s.set_color(lane, idx, Some(c)) {
143 return Err(refused(&who));
144 }
145 Ok(done(format!("{who} → {}", shown.join(", ")), vec![(lane, start)]))
146}
147
148/// The clip's grade for a look op: its address, the grade as it stands (identity
149/// for none), and the start frame. Picture clips only.
150fn look_target(s: &PlaybackSession, op: &Value, name: &str) -> Result<(Lane, usize, String, u32, ColorParams), String> {
151 let (lane, idx, raw, start) = clip_arg(s, op)?;
152 if lane.kind != LaneKind::Video {
153 return Err(format!("{name} {raw}: a look grades a picture; {raw} is on a {} lane", kind_word(lane.kind)));
154 }
155 let c = s.color_of(lane, idx).copied().unwrap_or_default();
156 Ok((lane, idx, raw, start, c))
157}
158
159/// Writes a look op's grade: no grade at all when everything is back at rest.
160fn write_look(s: &mut PlaybackSession, lane: Lane, idx: usize, c: ColorParams, who: &str) -> Result<(), String> {
161 let params = (!c.is_identity() || c.look.lut.is_some()).then_some(c);
162 if !s.set_color(lane, idx, params) {
163 return Err(refused(who));
164 }
165 Ok(())
166}
167
168/// A `.cube` path argument, opened and checked: a missing or malformed file is
169/// refused here, with the parser's reason, rather than set and silently skipped.
170fn open_lut(who: &str, raw: &str) -> Result<engine::cube::LutRef, String> {
171 let path = super::project::expand_home(raw.trim());
172 let path = std::path::absolute(&path).unwrap_or(path);
173 let r = engine::cube::LutRef::reload(&path);
174 match r.problem() {
175 Some(e) => Err(format!("{who}: cannot use that LUT: {e}")),
176 None => Ok(r),
177 }
178}
179
180fn lut_words(r: engine::cube::LutRef, mix: f32) -> String {
181 let path = r.path();
182 let name = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
183 let table = r.table().map(|c| format!(", {} {}", if c.three_d { "3D" } else { "1D" }, c.size)).unwrap_or_default();
184 format!("LUT {name}{table} at {:.0}%", mix * 100.0)
185}
186
187/// `lut {clip, path?, mix?, clear?}` or `lut {relink, path}`: a `.cube` file on the
188/// clip's grade (after its wheels and curves, before the four sliders), how much
189/// of it shows (mix 0..1, default 1), or off; `relink` points every clip naming
190/// one file at another, as media_relink does for a source.
191fn lut(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
192 if let Some(from) = op.get("relink") {
193 let from = from.as_str().ok_or("lut: `relink` is the path of the LUT file clips name now")?;
194 let who = "lut relink".to_string();
195 let to = req_str(op, "path").map_err(|e| format!("{who}: {e} (the file the LUT now is)"))?;
196 let fresh = open_lut(&who, to)?;
197 let from = super::project::expand_home(from.trim());
198 let named: Vec<std::path::PathBuf> = s.luts().into_iter().map(|r| r.path()).collect();
199 if !named.contains(&from) {
200 let list: Vec<String> = named.iter().map(|p| p.display().to_string()).collect();
201 return Err(format!(
202 "{who}: no clip names {}; the LUTs in use are: {}",
203 from.display(),
204 if list.is_empty() { "none".into() } else { list.join(", ") }
205 ));
206 }
207 let n = s.relink_lut(&from, &fresh.path());
208 return Ok(done(format!("{who} → {n} clip(s) now use {}", fresh.path().display()), Vec::new()));
209 }
210 let (lane, idx, raw, start, mut c) = look_target(s, op, "lut")?;
211 let who = format!("lut {raw}");
212 if flag(op, "clear")? {
213 c.look.lut = None;
214 c.look.lut_mix = 1.0;
215 write_look(s, lane, idx, c, &who)?;
216 return Ok(done(format!("{who} → off"), vec![(lane, start)]));
217 }
218 let path = match op.get("path") {
219 None | Some(Value::Null) => None,
220 Some(Value::String(p)) => Some(p.clone()),
221 Some(v) => return Err(format!("{who}: `path` must be a string, got {}", kind_of(v))),
222 };
223 let mix = num(op, "mix")?.map(|v| ranged(&who, "mix", v, 0.0, 1.0)).transpose()?;
224 if path.is_none() && mix.is_none() {
225 return Err(format!("{who}: give path (a .cube file), mix (0..1), or clear:true"));
226 }
227 if let Some(p) = path {
228 c.look.lut = Some(open_lut(&who, &p)?);
229 c.look.lut_mix = 1.0;
230 }
231 let Some(r) = c.look.lut else {
232 return Err(format!("{who}: {raw} has no LUT to mix; give path first"));
233 };
234 if let Some(m) = mix {
235 c.look.lut_mix = m;
236 }
237 write_look(s, lane, idx, c, &who)?;
238 Ok(done(format!("{who} → {}", lut_words(r, c.look.lut_mix)), vec![(lane, start)]))
239}
240
241/// One wheel argument: `[master, red, green, blue]`, or one number for the master alone.
242fn wheel_arg(who: &str, op: &Value, key: &str) -> Result<Option<[f32; 4]>, String> {
243 match op.get(key) {
244 None | Some(Value::Null) => Ok(None),
245 Some(Value::Number(n)) => {
246 let v = ranged(who, key, n.as_f64().unwrap_or(f64::NAN), -1.0, 1.0)?;
247 Ok(Some([v, 0.0, 0.0, 0.0]))
248 }
249 Some(Value::Array(a)) if a.len() == 4 => {
250 let mut out = [0f32; 4];
251 for (o, v) in out.iter_mut().zip(a) {
252 let x = v.as_f64().ok_or_else(|| format!("{who}: {key} holds {}, not a number", kind_of(v)))?;
253 *o = ranged(who, key, x, -1.0, 1.0)?;
254 }
255 Ok(Some(out))
256 }
257 Some(_) => Err(format!("{who}: {key} is [master, red, green, blue] (each -1..1), or one number for the master")),
258 }
259}
260
261fn wheel_words(name: &str, w: &[f32; 4]) -> Option<String> {
262 (w.iter().any(|&v| v != 0.0)).then(|| format!("{name} m{:+.2} r{:+.2} g{:+.2} b{:+.2}", w[0], w[1], w[2], w[3]))
263}
264
265/// `wheels {clip, lift?, gamma?, gain?, reset?}`: lift (blacks), gamma (mids) and
266/// gain (whites), each `[master, red, green, blue]` in -1..1 with 0 neutral, or one
267/// number for the master. A wheel named replaces that wheel; the others stay.
268fn wheels(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
269 let (lane, idx, raw, start, mut c) = look_target(s, op, "wheels")?;
270 let who = format!("wheels {raw}");
271 if flag(op, "reset")? {
272 c.look.wheels = engine::color::Wheels::default();
273 write_look(s, lane, idx, c, &who)?;
274 return Ok(done(format!("{who} → neutral"), vec![(lane, start)]));
275 }
276 let (lift, gamma, gain) = (wheel_arg(&who, op, "lift")?, wheel_arg(&who, op, "gamma")?, wheel_arg(&who, op, "gain")?);
277 if lift.is_none() && gamma.is_none() && gain.is_none() {
278 return Err(format!("{who}: give at least one of lift, gamma, gain ([master, red, green, blue], each -1..1), or reset:true"));
279 }
280 let w = &mut c.look.wheels;
281 if let Some(v) = lift {
282 w.lift = v;
283 }
284 if let Some(v) = gamma {
285 w.gamma = v;
286 }
287 if let Some(v) = gain {
288 w.gain = v;
289 }
290 let shown: Vec<String> = [("lift", w.lift), ("gamma", w.gamma), ("gain", w.gain)]
291 .iter()
292 .filter_map(|(n, v)| wheel_words(n, v))
293 .collect();
294 write_look(s, lane, idx, c, &who)?;
295 let text = if shown.is_empty() { "neutral".to_string() } else { shown.join(", ") };
296 Ok(done(format!("{who} → {text}"), vec![(lane, start)]))
297}
298
299/// `look {clip, name}`: the clip's grade becomes the look `name` (a built-in, or a saved
300/// one from the colour card's "Save current as look"), replacing its colour, wheels, curves
301/// and LUT in one undo step. A name nobody has gets the list of the looks there are.
302/// `look {clip, save: "<name>"}` is the other way round: the clip's grade is saved as a look
303/// of that name (the grading card's "Save current as look" does the same), and the project does
304/// not change, so there is no undo step.
305fn look(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
306 let (lane, idx, raw, start, grade) = look_target(s, op, "look")?;
307 if let Some(saved) = op.get("save") {
308 let who = format!("look {raw} save");
309 let Some(name) = saved.as_str() else {
310 return Err(format!("{who}: `save` is the name to save the grade under, as a string"));
311 };
312 let path = engine::looks::save(name, &grade).map_err(|e| format!("{who}: {e}"))?;
313 return Ok(done(format!("{who} {} → {}", name.trim(), path.display()), vec![(lane, start)]));
314 }
315 let who = format!("look {raw}");
316 let name = req_str(op, "name")?;
317 let keyed = s.color_keys_of(lane, idx).len();
318 if keyed > 0 {
319 return Err(format!(
320 "{who}: {raw} has {keyed} colour key(s), and a keyed clip's grade is its keys; take them off first with color_keys {{clip, clear:true}}"
321 ));
322 }
323 let params = engine::looks::load(name).map_err(|e| {
324 let saved = engine::looks::saved_names();
325 let saved = if saved.is_empty() { "none saved".to_string() } else { saved.join(", ") };
326 let built: Vec<&str> = engine::looks::builtins().iter().map(|(n, _)| *n).collect();
327 format!("{who}: {e}. Looks: {}; saved: {saved}", built.join(", "))
328 })?;
329 write_look(s, lane, idx, params, &who)?;
330 Ok(done(format!("{who} → {name}"), vec![(lane, start)]))
331}
332
333/// `auto_color {clip}`: reads a correction off the clip's middle frame as shot (grey-world
334/// white balance into the three channel gains, then a luma stretch that puts the 0.5 % and
335/// 99.5 % percentiles on 0.02 and 0.98 through brightness and contrast) and writes it onto the
336/// grade. Saturation, tint, curves and LUT are kept. The reply says what it set.
337fn auto_color(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
338 let (lane, idx, raw, start, c0) = look_target(s, op, "auto_color")?;
339 let who = format!("auto_color {raw}");
340 let keyed = s.color_keys_of(lane, idx).len();
341 if keyed > 0 {
342 return Err(format!(
343 "{who}: {raw} has {keyed} colour key(s), and a keyed clip's grade is its keys; take them off first with color_keys {{clip, clear:true}}"
344 ));
345 }
346 let mid = start + s.lane_clips(lane)[idx].len() / 2;
347 let (project, meta) = s.export_snapshot();
348 // Read at a size that keeps the analysis quick; the statistics do not need more.
349 let (w, h) = fit_to(meta.width, meta.height, 640);
350 let f = engine::export::compose_ungraded_at(&project, &meta, mid, w, h)
351 .map_err(|e| format!("{who}: cannot read frame {mid}: {e}"))?;
352 let rgb: Vec<u8> = f.bgra.as_chunks::<4>().0.iter().flat_map(|p| [p[2], p[1], p[0]]).collect();
353 let fix = engine::auto_color::analyse(&rgb, f.width as usize, f.height as usize)
354 .ok_or_else(|| format!("{who}: frame {mid} has no picture to read"))?;
355 let next = fix.apply(c0);
356 write_look(s, lane, idx, next, &who)?;
357 let g = fix.gain;
358 let text = format!(
359 "{who} → wheels gain red {:+.2}, green {:+.2}, blue {:+.2}, brightness {:+.2}, contrast {:.2} (luma 0.5 %/99.5 % was {:.2}/{:.2})",
360 g[0], g[1], g[2], fix.brightness, fix.contrast, fix.low, fix.high
361 );
362 Ok(done(text, vec![(lane, start)]))
363}
364
365/// `(w, h)` scaled down to `max` wide, keeping the aspect, never below 2 px.
366fn fit_to(w: u32, h: u32, max: u32) -> (u32, u32) {
367 if w <= max || w == 0 {
368 return (w.max(2), h.max(2));
369 }
370 let scaled = (u64::from(h) * u64::from(max) / u64::from(w)).max(2) as u32;
371 (max, scaled)
372}
373
374/// `curves {clip, master?, red?, green?, blue?, reset?}`: each a list of up to 16
375/// `[input, output]` points in 0..1, inputs rising; `[]` straightens that curve.
376fn curves(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
377 let (lane, idx, raw, start, mut c) = look_target(s, op, "curves")?;
378 let who = format!("curves {raw}");
379 if flag(op, "reset")? {
380 c.look.curves = [engine::color::Curve::default(); 4];
381 write_look(s, lane, idx, c, &who)?;
382 return Ok(done(format!("{who} → straight"), vec![(lane, start)]));
383 }
384 let mut shown = Vec::new();
385 for (ch, name) in engine::color::CHANNELS.iter().enumerate() {
386 let Some(v) = op.get(*name).filter(|v| !v.is_null()) else {
387 continue;
388 };
389 let pts = v.as_array().ok_or_else(|| format!("{who}: {name} is a list of [input, output] points"))?;
390 let mut out = Vec::with_capacity(pts.len());
391 for p in pts {
392 let xy = p.as_array().filter(|a| a.len() == 2).and_then(|a| Some([a[0].as_f64()? as f32, a[1].as_f64()? as f32]));
393 out.push(xy.ok_or_else(|| format!("{who}: a {name} point is [input, output], both 0..1"))?);
394 }
395 c.look.curves[ch] = engine::color::Curve::new(&out).map_err(|e| format!("{who}: {name}: {e}"))?;
396 shown.push(if out.is_empty() { format!("{name} straight") } else { format!("{name} {} point(s)", out.len()) });
397 }
398 if shown.is_empty() {
399 return Err(format!("{who}: give at least one of master, red, green, blue (a list of [input, output] points), or reset:true"));
400 }
401 write_look(s, lane, idx, c, &who)?;
402 Ok(done(format!("{who} → {}", shown.join(", ")), vec![(lane, start)]))
403}
404
405/// `transform {clip, x?, y?, scale?, rotate?, crop?: [l,r,t,b], opacity?, reset?}`.
406///
407/// Units, as `engine::transform` documents them: `x`/`y` are canvas fractions
408/// off centre (positive right / down), `scale` a multiplier on the fit size,
409/// `rotate` degrees clockwise (rendered at the nearest 90), each crop side a
410/// fraction of the source, and `opacity` 0 (clear) to 1 (opaque). `reset` wins
411/// over the other fields.
412fn transform(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
413 let (lane, idx, raw, start) = clip_arg(s, op)?;
414 let who = format!("transform {raw}");
415 let keys = s.transform_keys_of(lane, idx).len();
416 if keys > 0 {
417 return Err(format!(
418 "{who}: {raw} has {keys} transform key(s), and a keyed clip's placement is its keys; change them with transform_keys, or take them off first with transform_keys {{clip, clear:true}}"
419 ));
420 }
421 if flag(op, "reset")? {
422 if !s.set_transform(lane, idx, None) {
423 return Err(refused(&who));
424 }
425 return Ok(done(format!("{who} → reset"), vec![(lane, start)]));
426 }
427 let corner = corner_arg(&who, op)?;
428 if corner.is_some() && (num(op, "x")?.is_some() || num(op, "y")?.is_some()) {
429 return Err(format!(
430 "{who}: corner sets x and y itself, so give corner alone, or x and y alone"
431 ));
432 }
433 if corner.is_none() && op.get("margin").is_some_and(|v| !v.is_null()) {
434 return Err(format!("{who}: margin is the gap a corner keeps, so it goes with corner"));
435 }
436 let mut t: TransformParams = s.transform_of(lane, idx).copied().unwrap_or_default();
437 let mut shown = Vec::new();
438 if let Some(v) = num(op, "x")? {
439 t.pos_x = ranged(&who, "x", v, -1.0, 1.0)?;
440 shown.push(format!("x {:.2}", t.pos_x));
441 }
442 if let Some(v) = num(op, "y")? {
443 t.pos_y = ranged(&who, "y", v, -1.0, 1.0)?;
444 shown.push(format!("y {:.2}", t.pos_y));
445 }
446 if let Some(v) = num(op, "scale")? {
447 t.scale = ranged(&who, "scale", v, 0.05, 8.0)?;
448 shown.push(format!("scale {:.2}", t.scale));
449 }
450 if let Some(v) = num(op, "rotate")? {
451 t.rotate = ranged(&who, "rotate", v, -360.0, 360.0)?;
452 shown.push(format!("rotate {:.0}°", t.rotate));
453 }
454 if let Some(v) = op.get("crop").filter(|v| !v.is_null()) {
455 let arr = v
456 .as_array()
457 .filter(|a| a.len() == 4)
458 .ok_or_else(|| format!("{who}: crop takes [left, right, top, bottom], four fractions from 0 to 0.5"))?;
459 let mut f = [0.0f32; 4];
460 for (i, item) in arr.iter().enumerate() {
461 let x = item
462 .as_f64()
463 .filter(|x| x.is_finite())
464 .ok_or_else(|| format!("{who}: crop[{i}] must be a number, got {}", kind_of(item)))?;
465 f[i] = ranged(&who, &format!("crop[{i}]"), x, 0.0, 0.5)?;
466 }
467 t.crop_l = f[0];
468 t.crop_r = f[1];
469 t.crop_t = f[2];
470 t.crop_b = f[3];
471 shown.push(format!("crop {:.2}/{:.2}/{:.2}/{:.2}", f[0], f[1], f[2], f[3]));
472 }
473 if let Some(v) = num(op, "opacity")? {
474 let keyed = s.opacity_keys_of(lane, idx).len();
475 if keyed > 0 {
476 return Err(format!(
477 "{who}: {raw} has {keyed} opacity key(s), which give its opacity; change them with opacity_keys, or take them off first with opacity_keys {{clip, clear:true}}"
478 ));
479 }
480 t.opacity = ranged(&who, "opacity", v, 0.0, 1.0)?;
481 shown.push(format!("opacity {:.2}", t.opacity));
482 }
483 if let Some(corner) = corner {
484 // The corner is measured on the picture as it shows: its crop, then its
485 // quarter turn, at the current scale, with the margin in pixels.
486 let src = source_size(s, lane, idx).ok_or_else(|| {
487 format!("{who}: {raw} has no picture size to place by (a sound, or a generated clip)")
488 })?;
489 let (cw, ch) = s.resolution();
490 let margin = match num(op, "margin")? {
491 Some(m) => ranged(&who, "margin", m, 0.0, 4000.0)?,
492 None => engine::transform::CORNER_MARGIN_PX,
493 };
494 // The picture as it shows (its crop and quarter turn) sets the box, at the current scale.
495 let (x, y) = engine::transform::corner_placement(corner, &t, src, (cw, ch), margin);
496 t.pos_x = x;
497 t.pos_y = y;
498 shown.push(format!("corner {}, margin {margin:.0} px", corner_name(corner)));
499 }
500 if shown.is_empty() {
501 return Err(format!(
502 "{who}: give at least one of x, y, corner, scale, rotate, crop, opacity, or reset:true"
503 ));
504 }
505 if !s.set_transform(lane, idx, Some(t)) {
506 return Err(refused(&who));
507 }
508 Ok(done(format!("{who} → {}", shown.join(", ")), vec![(lane, start)]))
509}
510
511/// The `corner` of a transform op: `centre`, `top-left`, `top-right`, `bottom-left`
512/// or `bottom-right`. `None` when the op does not name one.
513fn corner_arg(who: &str, op: &Value) -> Result<Option<Corner>, String> {
514 let Some(v) = op.get("corner").filter(|v| !v.is_null()) else {
515 return Ok(None);
516 };
517 let text = v.as_str().ok_or_else(|| {
518 format!("{who}: corner is centre, top-left, top-right, bottom-left or bottom-right, got {}", kind_of(v))
519 })?;
520 match text {
521 "centre" | "center" => Ok(Some(Corner::Centre)),
522 "top-left" => Ok(Some(Corner::TopLeft)),
523 "top-right" => Ok(Some(Corner::TopRight)),
524 "bottom-left" => Ok(Some(Corner::BottomLeft)),
525 "bottom-right" => Ok(Some(Corner::BottomRight)),
526 other => Err(format!(
527 "{who}: corner is centre, top-left, top-right, bottom-left or bottom-right, got \"{other}\""
528 )),
529 }
530}
531
532/// The name a corner reads as in a reply.
533fn corner_name(corner: Corner) -> &'static str {
534 match corner {
535 Corner::Centre => "centre",
536 Corner::TopLeft => "top-left",
537 Corner::TopRight => "top-right",
538 Corner::BottomLeft => "bottom-left",
539 Corner::BottomRight => "bottom-right",
540 }
541}
542
543/// The pixel size of a clip's source picture: a video's, or a still's. `None` for
544/// sound, and for a generated clip, which has no file to measure.
545fn source_size(s: &PlaybackSession, lane: Lane, idx: usize) -> Option<(u32, u32)> {
546 let c = s.lane_clips(lane).get(idx)?;
547 let path = &s.sources().get(c.source)?.path;
548 match engine::probe_media(path).video {
549 Some(v) => Some((v.width, v.height)),
550 None if engine::is_image(path) => engine::decode::image_size(path).ok(),
551 None => None,
552 }
553}
554
555/// `transform_keys {clip, keys:[{at, x?, y?, scale?, rotate?, opacity?, ease?}], clear?}`:
556/// replaces the clip's placement animation, the slow zoom or a move over time. Video
557/// clips only. `at` is clip-relative: a time from the clip's start ("0s", "2.5s", a
558/// frame count), "50%" of the clip, or "end". A key leaves each field it does not
559/// name held from the previous key, and the first key from the clip's own
560/// transform. `ease` is "linear" (the default) or "ease" (slow in and out) and
561/// shapes the stretch from this key to the next; the last key has no stretch.
562/// `clear:true` takes the animation off, back to the clip's single transform. The
563/// reply lists the keys in timeline time. A keyed clip refuses `transform`.
564fn transform_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
565 let (lane, idx, raw, start) = clip_arg(s, op)?;
566 let who = format!("transform_keys {raw}");
567 if lane.kind != LaneKind::Video {
568 return Err(format!(
569 "{who}: {raw} is on an audio lane; placement keys belong to a picture clip"
570 ));
571 }
572 let c = s
573 .lane_clips(lane)
574 .get(idx)
575 .cloned()
576 .ok_or_else(|| refused(&who))?;
577 let list = match op.get("keys") {
578 None | Some(Value::Null) => None,
579 Some(Value::Array(a)) => Some(a),
580 Some(v) => {
581 return Err(format!(
582 "{who}: keys must be a list of {{at, x?, y?, scale?, rotate?, opacity?, ease?}} objects, got {}",
583 kind_of(v)
584 ))
585 }
586 };
587 if flag(op, "clear")? {
588 if list.is_some() {
589 return Err(format!("{who}: give keys or clear:true, not both"));
590 }
591 if s.transform_keys_of(lane, idx).is_empty() {
592 return Ok(done(format!("{who} → already no keys"), Vec::new()));
593 }
594 if !s.set_transform_keys(lane, idx, Vec::new()) {
595 return Err(refused(&who));
596 }
597 return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)]));
598 }
599 let list = list.ok_or_else(|| {
600 format!("{who}: missing `keys`: a list of {{at, x?, y?, scale?, rotate?, opacity?, ease?}} objects, or clear:true")
601 })?;
602 if list.is_empty() {
603 return Err(format!("{who}: keys is empty; use clear:true to take the animation off"));
604 }
605 if list.len() > MAX_TRANSFORM_KEYS {
606 return Err(format!("{who}: {} keys, and at most {MAX_TRANSFORM_KEYS} fit", list.len()));
607 }
608 let end = parse::session_end(s);
609 let frames = c.frames();
610 let mut timed: Vec<(u32, &Value)> = Vec::with_capacity(list.len());
611 for (i, k) in list.iter().enumerate() {
612 let n = i + 1;
613 let obj = k.as_object().ok_or_else(|| {
614 format!("{who}: key {n} must be an object such as {{\"at\": \"0s\", \"scale\": 1.0}}")
615 })?;
616 if let Some(bad) = obj
617 .keys()
618 .find(|k| !matches!(k.as_str(), "at" | "x" | "y" | "scale" | "rotate" | "opacity" | "ease"))
619 {
620 return Err(format!(
621 "{who}: key {n} has `{bad}`, which a key does not take: x, y, scale, rotate, opacity, ease, at"
622 ));
623 }
624 let at = obj
625 .get("at")
626 .ok_or_else(|| format!("{who}: key {n} has no `at`, the time from the clip's start"))?;
627 let off = clip_offset(&who, n, at, frames, fps, end)?;
628 timed.push((off, k));
629 }
630 timed.sort_by_key(|&(off, _)| off);
631 let base = s.transform_of(lane, idx).copied().unwrap_or_default();
632 let mut prev = base;
633 let mut keys: Vec<TransformKey> = Vec::with_capacity(timed.len());
634 for (i, (off, k)) in timed.iter().enumerate() {
635 let n = i + 1;
636 let mut p = prev;
637 if let Some(v) = num_of(k, "x")? {
638 p.pos_x = ranged(&who, "x", v, -1.0, 1.0)?;
639 }
640 if let Some(v) = num_of(k, "y")? {
641 p.pos_y = ranged(&who, "y", v, -1.0, 1.0)?;
642 }
643 if let Some(v) = num_of(k, "scale")? {
644 p.scale = ranged(&who, "scale", v, 0.05, 8.0)?;
645 }
646 if let Some(v) = num_of(k, "rotate")? {
647 p.rotate = ranged(&who, "rotate", v, -360.0, 360.0)?;
648 }
649 if let Some(v) = num_of(k, "opacity")? {
650 p.opacity = ranged(&who, "opacity", v, 0.0, 1.0)?;
651 }
652 let ease = ease_of(&who, n, k)?;
653 keys.push(TransformKey {
654 at: src_at(&c, start + off),
655 params: p,
656 ease,
657 });
658 prev = p;
659 }
660 if let Some(i) = keys.windows(2).position(|w| w[0].at == w[1].at) {
661 // At 1x a source frame is a timeline frame, so the clash is two keys at
662 // one time; at another speed two timeline frames can share a source one.
663 return Err(if c.speed == engine::project::Speed::NORMAL && c.speed_keys.is_empty() {
664 let t = tsec(f64::from(start + timed[i + 1].0), fps);
665 format!("{who}: two keys at the same time ({t}); space them further apart")
666 } else {
667 format!(
668 "{who}: two keys land on the same source frame at this speed; space them further apart"
669 )
670 });
671 }
672 if keys == s.transform_keys_of(lane, idx) {
673 return Ok(done(format!("{who} → already {}", transform_keys_text(&c, fps, &keys)), Vec::new()));
674 }
675 let text = format!("{who} → {}", transform_keys_text(&c, fps, &keys));
676 if !s.set_transform_keys(lane, idx, keys) {
677 return Err(refused(&who));
678 }
679 Ok(done(text, vec![(lane, start)]))
680}
681
682/// The `ease` of key `n` (a JSON object): one of the names [`KeyEase::from_name`]
683/// takes, `linear` when absent. A custom curve is `bezier(x1,y1,x2,y2)` or `[x1,y1,x2,y2]`.
684fn ease_of(who: &str, n: usize, key: &Value) -> Result<KeyEase, String> {
685 match key.get("ease") {
686 None | Some(Value::Null) => Ok(KeyEase::Linear),
687 Some(Value::String(name)) if name.trim_start().starts_with("bezier") => {
688 let values = name
689 .trim()
690 .strip_prefix("bezier(")
691 .and_then(|s| s.strip_suffix(')'))
692 .and_then(|s| s.split(',').map(|p| p.trim().parse::<f64>().ok()).collect::<Option<Vec<f64>>>());
693 match values {
694 Some(v) => bezier_of(who, n, &v),
695 None => Err(format!("{who}: key {n} bezier wants bezier(x1,y1,x2,y2), got {name:?}")),
696 }
697 }
698 Some(Value::String(name)) => KeyEase::from_name(name).ok_or_else(|| {
699 format!("{who}: key {n} ease is {EASES}, got {name:?}")
700 }),
701 Some(Value::Array(points)) => {
702 let values: Vec<f64> = points.iter().map(|p| p.as_f64().unwrap_or(f64::NAN)).collect();
703 bezier_of(who, n, &values)
704 }
705 Some(v) => Err(format!("{who}: key {n} ease must be a name ({EASES}), got {}", kind_of(v))),
706 }
707}
708
709/// The custom curve through four control coordinates `[x1, y1, x2, y2]`, each from `0` to `1`.
710/// A coordinate outside that range is refused, because a curve that overshoots would push an
711/// interpolated value past the two keys it runs between.
712fn bezier_of(who: &str, n: usize, v: &[f64]) -> Result<KeyEase, String> {
713 let refuse = || format!("{who}: key {n} bezier points are x1,y1,x2,y2, each from 0 to 1, got {v:?}");
714 let &[x1, y1, x2, y2] = v else {
715 return Err(refuse());
716 };
717 Bezier::new(x1 as f32, y1 as f32, x2 as f32, y2 as f32)
718 .map(KeyEase::Bezier)
719 .ok_or_else(refuse)
720}
721
722/// The ease names, for the refusals that list them.
723const EASES: &str = "\"linear\", \"ease_in\", \"ease_out\", \"ease_in_out\", \"hold\", \"bezier(x1,y1,x2,y2)\" or [x1,y1,x2,y2]";
724
725/// ` ease_in` for a reply, nothing for linear.
726fn ease_suffix(ease: KeyEase) -> String {
727 match ease {
728 KeyEase::Linear => String::new(),
729 e => format!(" {}", e.name()),
730 }
731}
732
733/// The keys of an `opacity_keys` / `color_keys` call as `(clip-relative frame, key object)`
734/// sorted by time: `keys` checked to be a non-empty list of objects holding only
735/// `allowed` fields, each with an `at`.
736fn timed_keys<'a>(
737 who: &str,
738 list: &'a [Value],
739 allowed: &[&str],
740 c: &Clip,
741 fps: f64,
742 end: u32,
743 cap: usize,
744) -> Result<Vec<(u32, &'a Value)>, String> {
745 if list.is_empty() {
746 return Err(format!("{who}: keys is empty; use clear:true to take the animation off"));
747 }
748 if list.len() > cap {
749 return Err(format!("{who}: {} keys, and at most {cap} fit", list.len()));
750 }
751 let frames = c.frames();
752 let mut timed = Vec::with_capacity(list.len());
753 for (i, k) in list.iter().enumerate() {
754 let n = i + 1;
755 let obj = k.as_object().ok_or_else(|| {
756 format!("{who}: key {n} must be an object such as {{\"at\": \"0s\", \"{}\": 0.5}}", allowed[0])
757 })?;
758 if let Some(bad) = obj.keys().find(|k| k.as_str() != "at" && k.as_str() != "ease" && !allowed.contains(&k.as_str())) {
759 return Err(format!(
760 "{who}: key {n} has `{bad}`, which a key does not take: {}, ease, at",
761 allowed.join(", ")
762 ));
763 }
764 let at = obj
765 .get("at")
766 .ok_or_else(|| format!("{who}: key {n} has no `at`, the time from the clip's start"))?;
767 timed.push((clip_offset(who, n, at, frames, fps, end)?, k));
768 }
769 timed.sort_by_key(|&(off, _)| off);
770 Ok(timed)
771}
772
773/// Refuses two keys on one source frame, in the words the transform keys use.
774fn clash_check(who: &str, c: &Clip, at: &[u32], timed: &[(u32, &Value)], start: u32, fps: f64) -> Result<(), String> {
775 if let Some(i) = at.windows(2).position(|w| w[0] == w[1]) {
776 return Err(if c.speed == engine::project::Speed::NORMAL {
777 let t = tsec(f64::from(start + timed[i + 1].0), fps);
778 format!("{who}: two keys at the same time ({t}); space them further apart")
779 } else {
780 format!("{who}: two keys land on the same source frame at this speed; space them further apart")
781 });
782 }
783 Ok(())
784}
785
786/// `opacity_keys {clip, keys:[{at, opacity, ease?}], clear?}`: replaces the clip's
787/// opacity animation (0 clear .. 1 opaque), the fade-in of an overlay or a pulse.
788/// `at` is clip-relative as in `transform_keys`. A key that names no `opacity`
789/// holds the previous key's (the first, the clip's own opacity). The keys replace
790/// the clip's constant opacity while they exist; the fades multiply on top.
791/// `clear:true` takes them off.
792fn opacity_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
793 let (lane, idx, raw, start) = clip_arg(s, op)?;
794 let who = format!("opacity_keys {raw}");
795 if lane.kind != LaneKind::Video {
796 return Err(format!("{who}: {raw} is on an audio lane; opacity keys belong to a picture clip"));
797 }
798 let c = s.lane_clips(lane).get(idx).cloned().ok_or_else(|| refused(&who))?;
799 let list = match op.get("keys") {
800 None | Some(Value::Null) => None,
801 Some(Value::Array(a)) => Some(a),
802 Some(v) => {
803 return Err(format!("{who}: keys must be a list of {{at, opacity, ease?}} objects, got {}", kind_of(v)))
804 }
805 };
806 if flag(op, "clear")? {
807 if list.is_some() {
808 return Err(format!("{who}: give keys or clear:true, not both"));
809 }
810 if s.opacity_keys_of(lane, idx).is_empty() {
811 return Ok(done(format!("{who} → already no keys"), Vec::new()));
812 }
813 if !s.set_opacity_keys(lane, idx, Vec::new()) {
814 return Err(refused(&who));
815 }
816 return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)]));
817 }
818 let list = list.ok_or_else(|| format!("{who}: missing `keys`: a list of {{at, opacity, ease?}} objects, or clear:true"))?;
819 let end = parse::session_end(s);
820 let timed = timed_keys(&who, list, &["opacity"], &c, fps, end, MAX_TRANSFORM_KEYS)?;
821 let mut prev = s.transform_of(lane, idx).map_or(1.0, |t| t.opacity);
822 let mut keys = Vec::with_capacity(timed.len());
823 for (i, (off, k)) in timed.iter().enumerate() {
824 let n = i + 1;
825 if let Some(v) = num_of(k, "opacity")? {
826 prev = ranged(&who, "opacity", v, 0.0, 1.0)?;
827 }
828 keys.push(OpacityKey { at: src_at(&c, start + off), opacity: prev, ease: ease_of(&who, n, k)? });
829 }
830 let at: Vec<u32> = keys.iter().map(|k| k.at).collect();
831 clash_check(&who, &c, &at, &timed, start, fps)?;
832 let text = format!("{who} → {}", opacity_keys_text(&c, fps, &keys));
833 if keys == s.opacity_keys_of(lane, idx) {
834 return Ok(done(format!("{who} → already {}", opacity_keys_text(&c, fps, &keys)), Vec::new()));
835 }
836 if !s.set_opacity_keys(lane, idx, keys) {
837 return Err(refused(&who));
838 }
839 Ok(done(text, vec![(lane, start)]))
840}
841
842/// The opacity keys as timeline times: at most twelve, then `(+N more)`.
843pub(super) fn opacity_keys_text(c: &Clip, fps: f64, keys: &[OpacityKey]) -> String {
844 const SHOWN: usize = 12;
845 let mut parts: Vec<String> = keys
846 .iter()
847 .take(SHOWN)
848 .map(|k| format!("{} opacity {:.2}{}", tsec(timeline_of(c, k.at), fps), k.opacity, ease_suffix(k.ease)))
849 .collect();
850 if keys.len() > SHOWN {
851 parts.push(format!("(+{} more)", keys.len() - SHOWN));
852 }
853 format!("{} key(s): {}", keys.len(), parts.join(" · "))
854}
855
856/// `mask_keys {clip, effect, keys:[{at, x?, y?, w?, h?, feather?, ease?}], clear?}`: a rect or
857/// ellipse mask's position, size and soft edge over the clip's own time. `effect` is the mask's
858/// stack position. A key leaves each field it does not name at the previous key's value (the
859/// first key, at the mask's own static value). `clear:true` takes the keys off, and the mask
860/// goes back to its static values. The same sorted, clamped list a tracker writes.
861fn mask_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
862 let (lane, idx, raw, start) = clip_arg(s, op)?;
863 let who = format!("mask_keys {raw}");
864 if lane.kind != LaneKind::Video {
865 return Err(format!("{who}: {raw} is on an audio lane; mask keys belong to a picture clip"));
866 }
867 let c = s.lane_clips(lane).get(idx).cloned().ok_or_else(|| refused(&who))?;
868 let slot = effect_slot(&who, op, &c)?;
869 let e = &c.effects[slot];
870 if !matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) {
871 return Err(format!("{who}: effect {slot} is {}, and only a rect or ellipse mask takes keys", e.kind.name()));
872 }
873 if flag(op, "clear")? {
874 if s.effect_keys_of(lane, idx, slot).is_empty() {
875 return Ok(done(format!("{who} → already no keys"), Vec::new()));
876 }
877 if !s.set_effect_keys(lane, idx, slot, Vec::new()) {
878 return Err(refused(&who));
879 }
880 return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)]));
881 }
882 let list = match op.get("keys") {
883 Some(Value::Array(a)) => a,
884 None | Some(Value::Null) => {
885 return Err(format!("{who}: missing `keys`: a list of {{at, x, y, w, h, feather, ease?}} objects, or clear:true"))
886 }
887 Some(v) => return Err(format!("{who}: keys must be a list of {{at, x, y, w, h, feather, ease?}} objects, got {}", kind_of(v))),
888 };
889 let names = ["x", "y", "w", "h", "feather"];
890 let r = EffectKind::RectMask.params();
891 // The mask's own values, in the order `names` lists them: x, y, width, height, feather.
892 let mut prev = [e.values[0], e.values[1], e.values[2], e.values[3], e.values[4]];
893 let end = parse::session_end(s);
894 let timed = timed_keys(&who, list, &names, &c, fps, end, MAX_TRANSFORM_KEYS)?;
895 let mut keys = Vec::with_capacity(timed.len());
896 for (i, (off, k)) in timed.iter().enumerate() {
897 let n = i + 1;
898 for (j, name) in names.iter().enumerate() {
899 if let Some(v) = num_of(k, name)? {
900 prev[j] = ranged(&who, name, v, f64::from(r[j].min), f64::from(r[j].max))?;
901 }
902 }
903 keys.push(EffectKey {
904 at: src_at(&c, start + off),
905 values: [prev[0], prev[1], prev[2], prev[3], prev[4], e.values[5]],
906 ease: ease_of(&who, n, k)?,
907 });
908 }
909 let at: Vec<u32> = keys.iter().map(|k| k.at).collect();
910 clash_check(&who, &c, &at, &timed, start, fps)?;
911 let text = format!("{who} → {}", effect_keys_text(&c, fps, r, &keys));
912 if keys == s.effect_keys_of(lane, idx, slot) {
913 return Ok(done(format!("{who} → already {}", effect_keys_text(&c, fps, r, &keys)), Vec::new()));
914 }
915 if !s.set_effect_keys(lane, idx, slot, keys) {
916 return Err(refused(&who));
917 }
918 Ok(done(text, vec![(lane, start)]))
919}
920
921/// `effect_keys {clip, effect, keys:[{at, <param>?: n, ease?}], clear?}`: animates any numeric
922/// parameter of the effect at stack position `effect` over the clip's own time. The parameter
923/// names are the effect's own (a blur's `radius`, a vignette's `amount` and `softness`, a mask's
924/// `x`, `y`, `width`, `height` and `feather`). A switch or a choice (a blend's `mode`, a mask's
925/// `invert`) cannot be keyed and is refused by name. A key leaves each parameter it does not name
926/// at the value the effect shows at that time. `clear:true` takes the keys off.
927fn effect_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
928 let (lane, idx, raw, start) = clip_arg(s, op)?;
929 let who = format!("effect_keys {raw}");
930 if lane.kind != LaneKind::Video {
931 return Err(format!("{who}: {raw} is on an audio lane; effect keys belong to a picture clip"));
932 }
933 let c = s.lane_clips(lane).get(idx).cloned().ok_or_else(|| refused(&who))?;
934 let slot = effect_slot(&who, op, &c)?;
935 let e = c.effects[slot].clone();
936 let specs = e.kind.params();
937 if flag(op, "clear")? {
938 if s.effect_keys_of(lane, idx, slot).is_empty() {
939 return Ok(done(format!("{who} → already no keys"), Vec::new()));
940 }
941 if !s.set_effect_keys(lane, idx, slot, Vec::new()) {
942 return Err(refused(&who));
943 }
944 return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)]));
945 }
946 let list = match op.get("keys") {
947 Some(Value::Array(a)) => a,
948 None | Some(Value::Null) => {
949 return Err(format!("{who}: missing `keys`: a list of {{at, <parameter>, ease?}} objects, or clear:true"))
950 }
951 Some(v) => return Err(format!("{who}: keys must be a list of {{at, <parameter>, ease?}} objects, got {}", kind_of(v))),
952 };
953 for k in list.iter().filter_map(Value::as_object) {
954 for spec in specs.iter().filter(|p| !p.keyable()) {
955 if k.contains_key(spec.name) {
956 return Err(format!("{who}: {} cannot be keyed: a switch or a choice holds its static value", spec.name));
957 }
958 }
959 }
960 let keyable: Vec<&str> = specs.iter().filter(|p| p.keyable()).map(|p| p.name).collect();
961 let end = parse::session_end(s);
962 let timed = timed_keys(&who, list, &keyable, &c, fps, end, MAX_TRANSFORM_KEYS)?;
963 let mut keys = Vec::with_capacity(timed.len());
964 for (i, (off, k)) in timed.iter().enumerate() {
965 let n = i + 1;
966 let at = src_at(&c, start + off);
967 // A parameter the key does not name holds the value the effect shows at that frame.
968 let mut values = e.posed(f64::from(at)).values;
969 for (j, spec) in specs.iter().enumerate().filter(|(_, p)| p.keyable()) {
970 if let Some(v) = num_of(k, spec.name)? {
971 values[j] = ranged(&who, spec.name, v, f64::from(spec.min), f64::from(spec.max))?;
972 }
973 }
974 keys.push(EffectKey { at, values, ease: ease_of(&who, n, k)? });
975 }
976 let at: Vec<u32> = keys.iter().map(|k| k.at).collect();
977 clash_check(&who, &c, &at, &timed, start, fps)?;
978 let text = format!("{who} → {}", effect_keys_text(&c, fps, specs, &keys));
979 if keys == s.effect_keys_of(lane, idx, slot) {
980 return Ok(done(format!("{who} → already {}", effect_keys_text(&c, fps, specs, &keys)), Vec::new()));
981 }
982 if !s.set_effect_keys(lane, idx, slot, keys) {
983 return Err(refused(&who));
984 }
985 Ok(done(text, vec![(lane, start)]))
986}
987
988/// The stack position a keys op names with `effect`, checked to be on the clip.
989fn effect_slot(who: &str, op: &Value, c: &Clip) -> Result<usize, String> {
990 let slot = match op.get("effect") {
991 None | Some(Value::Null) => {
992 return Err(format!("{who}: missing `effect`: the effect's stack position, 0 for the first"))
993 }
994 Some(v) => v.as_u64().ok_or_else(|| format!("{who}: effect must be a stack position, 0 for the first"))? as usize,
995 };
996 if slot >= c.effects.len() {
997 return Err(format!("{who}: effect {slot} is out of range: the clip has {} effects", c.effects.len()));
998 }
999 Ok(slot)
1000}
1001
1002/// One keyed value as a reply prints it: whole for a stepped parameter, else to two or three places.
1003fn value_text(v: f32, spec: &ParamSpec) -> String {
1004 if spec.step >= 1.0 {
1005 format!("{v:.0}")
1006 } else if spec.step >= 0.01 {
1007 format!("{v:.2}")
1008 } else {
1009 format!("{v:.3}")
1010 }
1011}
1012
1013/// The effect keys as timeline times, each with its keyable parameters' values: at most twelve,
1014/// then `(+N more)`.
1015fn effect_keys_text(c: &Clip, fps: f64, specs: &[ParamSpec], keys: &[EffectKey]) -> String {
1016 const SHOWN: usize = 12;
1017 if keys.is_empty() {
1018 return "cleared (0 keys)".to_string();
1019 }
1020 let keyed: Vec<(usize, &ParamSpec)> = specs.iter().enumerate().filter(|(_, p)| p.keyable()).collect();
1021 let mut parts: Vec<String> = keys
1022 .iter()
1023 .take(SHOWN)
1024 .map(|k| {
1025 let values: Vec<String> =
1026 keyed.iter().map(|(i, p)| format!("{} {}", p.name, value_text(k.values[*i], p))).collect();
1027 format!("{} {}{}", tsec(timeline_of(c, k.at), fps), values.join(" "), ease_suffix(k.ease))
1028 })
1029 .collect();
1030 if keys.len() > SHOWN {
1031 parts.push(format!("(+{} more)", keys.len() - SHOWN));
1032 }
1033 format!("{} key(s): {}", keys.len(), parts.join(" · "))
1034}
1035
1036/// `color_keys {clip, keys:[{at, brightness?, contrast?, saturation?, tint?, ease?}], clear?}`:
1037/// replaces the clip's colour animation. `at` is clip-relative as in `transform_keys`.
1038/// A key leaves each field it does not name at the previous key's value (the first
1039/// key, at the clip's own grade). The keys replace the clip's constant grade while
1040/// they exist (`color` refuses until they are cleared); `clear:true` takes them off.
1041fn color_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
1042 let (lane, idx, raw, start) = clip_arg(s, op)?;
1043 let who = format!("color_keys {raw}");
1044 if lane.kind != LaneKind::Video {
1045 return Err(format!("{who}: {raw} is on an audio lane; colour keys belong to a picture clip"));
1046 }
1047 let c = s.lane_clips(lane).get(idx).cloned().ok_or_else(|| refused(&who))?;
1048 let list = match op.get("keys") {
1049 None | Some(Value::Null) => None,
1050 Some(Value::Array(a)) => Some(a),
1051 Some(v) => {
1052 return Err(format!(
1053 "{who}: keys must be a list of {{at, brightness?, contrast?, saturation?, tint?, ease?}} objects, got {}",
1054 kind_of(v)
1055 ))
1056 }
1057 };
1058 if flag(op, "clear")? {
1059 if list.is_some() {
1060 return Err(format!("{who}: give keys or clear:true, not both"));
1061 }
1062 if s.color_keys_of(lane, idx).is_empty() {
1063 return Ok(done(format!("{who} → already no keys"), Vec::new()));
1064 }
1065 if !s.set_color_keys(lane, idx, Vec::new()) {
1066 return Err(refused(&who));
1067 }
1068 return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)]));
1069 }
1070 let list = list.ok_or_else(|| {
1071 format!("{who}: missing `keys`: a list of {{at, brightness?, contrast?, saturation?, tint?, ease?}} objects, or clear:true")
1072 })?;
1073 let end = parse::session_end(s);
1074 let timed = timed_keys(&who, list, &["brightness", "contrast", "saturation", "tint"], &c, fps, end, MAX_COLOR_KEYS)?;
1075 let mut prev: ColorParams = s.color_of(lane, idx).copied().unwrap_or_default();
1076 let mut keys = Vec::with_capacity(timed.len());
1077 for (i, (off, k)) in timed.iter().enumerate() {
1078 let n = i + 1;
1079 if let Some(v) = num_of(k, "brightness")? {
1080 prev.brightness = ranged(&who, "brightness", v, -1.0, 1.0)?;
1081 }
1082 if let Some(v) = num_of(k, "contrast")? {
1083 prev.contrast = ranged(&who, "contrast", v, 0.0, 2.0)?;
1084 }
1085 if let Some(v) = num_of(k, "saturation")? {
1086 prev.saturation = ranged(&who, "saturation", v, 0.0, 2.0)?;
1087 }
1088 if let Some(v) = num_of(k, "tint")? {
1089 prev.tint = ranged(&who, "tint", v, -1.0, 1.0)?;
1090 }
1091 keys.push(ColorKey { at: src_at(&c, start + off), params: prev, ease: ease_of(&who, n, k)? });
1092 }
1093 let at: Vec<u32> = keys.iter().map(|k| k.at).collect();
1094 clash_check(&who, &c, &at, &timed, start, fps)?;
1095 let text = format!("{who} → {}", color_keys_text(&c, fps, &keys));
1096 if keys == s.color_keys_of(lane, idx) {
1097 return Ok(done(format!("{who} → already {}", color_keys_text(&c, fps, &keys)), Vec::new()));
1098 }
1099 if !s.set_color_keys(lane, idx, keys) {
1100 return Err(refused(&who));
1101 }
1102 Ok(done(text, vec![(lane, start)]))
1103}
1104
1105/// The colour keys as timeline times: at most twelve, then `(+N more)`.
1106pub(super) fn color_keys_text(c: &Clip, fps: f64, keys: &[ColorKey]) -> String {
1107 const SHOWN: usize = 12;
1108 let mut parts: Vec<String> = keys
1109 .iter()
1110 .take(SHOWN)
1111 .map(|k| {
1112 let p = &k.params;
1113 format!(
1114 "{} brightness {:.2} contrast {:.2} saturation {:.2} tint {:.2}{}",
1115 tsec(timeline_of(c, k.at), fps),
1116 p.brightness,
1117 p.contrast,
1118 p.saturation,
1119 p.tint,
1120 ease_suffix(k.ease)
1121 )
1122 })
1123 .collect();
1124 if keys.len() > SHOWN {
1125 parts.push(format!("(+{} more)", keys.len() - SHOWN));
1126 }
1127 format!("{} key(s): {}", keys.len(), parts.join(" · "))
1128}
1129
1130/// `n` as an English ordinal, `1st`, `2nd`, `11th`, `242nd`: the position of
1131/// a key in the list it was given in.
1132fn ordinal(n: usize) -> String {
1133 let suffix = match (n % 100, n % 10) {
1134 (11..=13, _) => "th",
1135 (_, 1) => "st",
1136 (_, 2) => "nd",
1137 (_, 3) => "rd",
1138 _ => "th",
1139 };
1140 format!("{n}{suffix}")
1141}
1142
1143/// A key's `at` as a clip-relative frame offset: "end" is the clip's last frame
1144/// boundary, "N%" a share of its frames, anything else a time read as
1145/// [`parse::frame`] reads it, which must fall inside the clip.
1146fn clip_offset(who: &str, n: usize, at: &Value, frames: u32, fps: f64, end: u32) -> Result<u32, String> {
1147 if let Some(text) = at.as_str() {
1148 let text = text.trim();
1149 if text.eq_ignore_ascii_case("end") {
1150 return Ok(frames);
1151 }
1152 if let Some(pct) = text.strip_suffix('%') {
1153 let share: f64 = pct
1154 .trim()
1155 .parse()
1156 .map_err(|_| format!("{who}: key {n} at {text:?} is not a percentage"))?;
1157 if !(0.0..=100.0).contains(&share) {
1158 return Err(format!("{who}: key {n} at {text} is outside the clip, 0% to 100%"));
1159 }
1160 return Ok((f64::from(frames) * share / 100.0).round() as u32);
1161 }
1162 }
1163 let off = parse::frame(at, fps, end).map_err(|e| format!("{who}: key {n}: {e}"))?;
1164 if off > frames {
1165 return Err(format!(
1166 "{who}: the {} key, at {}, is past the clip, which is {} long",
1167 ordinal(n),
1168 tsec(f64::from(off), fps),
1169 tsec(f64::from(frames), fps)
1170 ));
1171 }
1172 Ok(off)
1173}
1174
1175/// The keys as timeline times, `10.000s scale 1.20 …`: at most twelve, then
1176/// `(+N more)`. Shared by the op's reply and, later, any clip listing.
1177pub(super) fn transform_keys_text(c: &Clip, fps: f64, keys: &[TransformKey]) -> String {
1178 const SHOWN: usize = 12;
1179 if keys.is_empty() {
1180 return "cleared (0 keys)".to_string();
1181 }
1182 let mut parts: Vec<String> = keys
1183 .iter()
1184 .take(SHOWN)
1185 .map(|k| {
1186 let p = &k.params;
1187 let ease = ease_suffix(k.ease);
1188 format!(
1189 "{} scale {:.2} x {:.2} y {:.2} rotate {:.0}° opacity {:.2}{ease}",
1190 tsec(timeline_of(c, k.at), fps),
1191 p.scale,
1192 p.pos_x,
1193 p.pos_y,
1194 p.rotate,
1195 p.opacity
1196 )
1197 })
1198 .collect();
1199 if keys.len() > SHOWN {
1200 parts.push(format!("(+{} more)", keys.len() - SHOWN));
1201 }
1202 format!("{} key(s): {}", keys.len(), parts.join(" · "))
1203}
1204
1205/// `fit {clip, policy: "fit"|"fill"|"stretch"|"center"}`.
1206fn fit(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1207 let (lane, idx, raw, start) = clip_arg(s, op)?;
1208 let name = req_str(op, "policy")?;
1209 let policy = match name {
1210 "fit" => FitPolicy::Fit,
1211 "fill" => FitPolicy::Fill,
1212 "stretch" => FitPolicy::Stretch,
1213 "center" => FitPolicy::Center,
1214 other => {
1215 return Err(format!(
1216 "fit {raw}: `{other}` is not a fit policy; use fit, fill, stretch or center"
1217 ))
1218 }
1219 };
1220 if !s.set_fit(lane, idx, policy) {
1221 return Err(refused(&format!("fit {raw}")));
1222 }
1223 Ok(done(format!("fit {raw} → {name}"), vec![(lane, start)]))
1224}
1225
1226/// `eq {clip, bands?: [{f, db, q?, kind?}], reset?}`. At most 20 bands; the GUI
1227/// caps are f 20–20000 Hz, db ±12, q 0.3–12. `q` defaults to 0.707 and `kind`
1228/// to `peak`. `bands` replaces the clip's equalizer; `reset` takes it off.
1229fn eq(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1230 let (lane, idx, raw, start) = clip_arg(s, op)?;
1231 let who = format!("eq {raw}");
1232 if flag(op, "reset")? {
1233 if !s.set_eq(lane, idx, None) {
1234 return Err(refused(&who));
1235 }
1236 return Ok(done(format!("{who} → reset"), vec![(lane, start)]));
1237 }
1238 let list = op
1239 .get("bands")
1240 .filter(|v| !v.is_null())
1241 .ok_or_else(|| format!("{who}: give bands (a list of {{f, db, q, kind}}) or reset:true"))?;
1242 let arr = list
1243 .as_array()
1244 .ok_or_else(|| format!("{who}: bands must be a list of {{f, db, q, kind}}, got {}", kind_of(list)))?;
1245 if arr.len() > engine::eq::MAX_BANDS {
1246 return Err(format!("{who}: at most {} bands, got {}", engine::eq::MAX_BANDS, arr.len()));
1247 }
1248 let mut bands = Vec::with_capacity(arr.len());
1249 for (i, b) in arr.iter().enumerate() {
1250 let bw = format!("{who} band {i}");
1251 if !b.is_object() {
1252 return Err(format!("{bw}: a band is an object such as {{\"f\": 1000, \"db\": 3}}, got {}", kind_of(b)));
1253 }
1254 let f = req_num_in(b, "f", &bw, 20.0, 20_000.0)?;
1255 let db = req_num_in(b, "db", &bw, -12.0, 12.0)?;
1256 let q = match num_of(b, "q")? {
1257 Some(q) => ranged(&bw, "q", q, 0.3, 12.0)?,
1258 None => 0.707,
1259 };
1260 let kind = match num_kind(b)? {
1261 Some(k) => k,
1262 None => BandKind::Peak,
1263 };
1264 bands.push(Band { freq_hz: f, gain_db: db, q, kind });
1265 }
1266 let n = bands.len();
1267 if !s.set_eq(lane, idx, Some(EqParams { bands })) {
1268 return Err(refused(&who));
1269 }
1270 let text = if n == 0 {
1271 format!("{who} → flat (0 bands)")
1272 } else {
1273 format!("{who} → {n} band(s)")
1274 };
1275 Ok(done(text, vec![(lane, start)]))
1276}
1277
1278/// `gain {clip, db}` or `gain {clip, add_db}`: the clip's own volume in dB, on
1279/// top of its lane's. `db` is absolute (-60..+24), `add_db` relative to where the
1280/// clip is now; the result is clamped to the same range. Audio clips only: a
1281/// video clip has no volume of its own here, so it is refused by name.
1282fn gain(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1283 let (lane, idx, raw, start) = clip_arg(s, op)?;
1284 let who = format!("gain {raw}");
1285 if lane.kind != LaneKind::Audio {
1286 return Err(format!(
1287 "{who}: {raw} is on a video lane, and a clip's gain is set on its audio clip; set it on the audio clip split from the same take"
1288 ));
1289 }
1290 let now = s.clip_gain_of(lane, idx).ok_or_else(|| refused(&who))?;
1291 let (lo, hi) = (MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
1292 let target = match (num(op, "db")?, num(op, "add_db")?) {
1293 (Some(_), Some(_)) => return Err(format!("{who}: give db (absolute) or add_db (relative), not both")),
1294 (Some(v), None) => ranged(&who, "db", v, f64::from(lo), f64::from(hi))?,
1295 (None, Some(v)) => {
1296 let step = ranged(&who, "add_db", v, -84.0, 84.0)?;
1297 (now + step).clamp(lo, hi)
1298 }
1299 (None, None) => {
1300 return Err(format!("{who}: missing argument `db` (absolute, -60 to +24 dB) or `add_db` (relative)"));
1301 }
1302 };
1303 if target == now {
1304 return Ok(done(format!("{who} → already {target:.1} dB"), Vec::new()));
1305 }
1306 if !s.set_clip_gain(lane, idx, target) {
1307 return Err(refused(&who));
1308 }
1309 Ok(done(format!("{who} → {target:.1} dB"), vec![(lane, start)]))
1310}
1311
1312/// `gain_keys {clip, keys:[[time, db], ...]}`: replaces the clip's whole volume
1313/// envelope. Each time is a timeline time inside the clip; `keys: []` clears it.
1314fn gain_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
1315 let (lane, idx, raw, c) = env_clip(s, op, "gain_keys")?;
1316 let who = format!("gain_keys {raw}");
1317 let list = match op.get("keys") {
1318 None | Some(Value::Null) => {
1319 return Err(format!("{who}: missing argument `keys`: a list of [time, dB] points, or [] to clear"))
1320 }
1321 Some(Value::Array(a)) => a,
1322 Some(v) => return Err(format!("{who}: keys must be a list of [time, dB] points, got {}", kind_of(v))),
1323 };
1324 let end = parse::session_end(s);
1325 let (lo, hi) = db_range();
1326 let mut pts = Vec::with_capacity(list.len());
1327 for (i, p) in list.iter().enumerate() {
1328 let n = i + 1;
1329 let pair = match p.as_array() {
1330 Some(a) if a.len() == 2 || a.len() == 3 => a,
1331 _ => return Err(format!("{who}: point {n} must be [time, dB] or [time, dB, ease], such as [\"10s\", -18]")),
1332 };
1333 let t = parse::frame(&pair[0], fps, end).map_err(|e| format!("{who}: point {n}: {e}"))?;
1334 in_clip(&who, &raw, &c, t, fps)?;
1335 let db = pair[1]
1336 .as_f64()
1337 .ok_or_else(|| format!("{who}: point {n}: the dB must be a number"))?;
1338 let ease = match pair.get(2) {
1339 None => KeyEase::Linear,
1340 Some(e) => ease_of(&who, n, &json!({ "ease": e }))?,
1341 };
1342 pts.push((t, ranged(&who, "dB", db, lo, hi)?, ease));
1343 }
1344 let keys = eased_keys_of(&who, &c, &pts)?;
1345 if keys == s.gain_keys_of(lane, idx) {
1346 return Ok(done(format!("{who} → already {}", keys_summary(&c, fps, &keys)), Vec::new()));
1347 }
1348 let text = format!("{who} → {}", keys_summary(&c, fps, &keys));
1349 if !s.set_gain_keys(lane, idx, keys) {
1350 return Err(refused(&who));
1351 }
1352 Ok(done(text, vec![(lane, c.start)]))
1353}
1354
1355/// `gain_key {clip, at, db}`: one point of the volume envelope at timeline time
1356/// `at`. A point already at that frame is replaced.
1357fn gain_key(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
1358 let (lane, idx, raw, c) = env_clip(s, op, "gain_key")?;
1359 let who = format!("gain_key {raw}");
1360 let t = need(op, "at", fps, parse::session_end(s))?;
1361 in_clip(&who, &raw, &c, t, fps)?;
1362 let (lo, hi) = db_range();
1363 let db = req_num_in(op, "db", &who, lo, hi)?;
1364 let ease = ease_of(&who, 1, op)?;
1365 let key = GainKey { ease, ..GainKey::new(src_at(&c, t), db) };
1366 if s.gain_keys_of(lane, idx).contains(&key) {
1367 return Ok(done(format!("{who} → already {} dB at {}", fmt_db(db), tsec(f64::from(t), fps)), Vec::new()));
1368 }
1369 if !s.add_gain_key(lane, idx, key) {
1370 return Err(format!(
1371 "{who}: the engine refused it; an envelope holds at most {MAX_GAIN_KEYS} points, so remove one with gain_key_remove first"
1372 ));
1373 }
1374 let n = s.gain_keys_of(lane, idx).len();
1375 Ok(done(
1376 format!("{who} → {} {} dB ({n} points)", tsec(f64::from(t), fps), fmt_db(db)),
1377 vec![(lane, c.start)],
1378 ))
1379}
1380
1381/// `gain_key_remove {clip, at}`: takes out the point within one frame of timeline
1382/// time `at`. When none is that close the refusal lists the points there are.
1383fn gain_key_remove(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
1384 let (lane, idx, raw, c) = env_clip(s, op, "gain_key_remove")?;
1385 let who = format!("gain_key_remove {raw}");
1386 let t = need(op, "at", fps, parse::session_end(s))?;
1387 in_clip(&who, &raw, &c, t, fps)?;
1388 let current = s.gain_keys_of(lane, idx).to_vec();
1389 let near = current
1390 .iter()
1391 .map(|k| (k.at, k.db, (timeline_of(&c, k.at) - f64::from(t)).abs()))
1392 .filter(|&(_, _, d)| d <= 1.0)
1393 .min_by(|a, b| a.2.total_cmp(&b.2));
1394 let Some((at, db, _)) = near else {
1395 let have = if current.is_empty() {
1396 "this clip has no gain keys".to_string()
1397 } else {
1398 format!("its points are {}", points_text(&c, fps, &current))
1399 };
1400 return Err(format!("{who}: no gain key within a frame of {}; {have}", tsec(f64::from(t), fps)));
1401 };
1402 if !s.remove_gain_key(lane, idx, at) {
1403 return Err(refused(&who));
1404 }
1405 let left = s.gain_keys_of(lane, idx).len();
1406 Ok(done(
1407 format!(
1408 "{who} → removed {} {} dB ({left} points left)",
1409 tsec(timeline_of(&c, at), fps),
1410 fmt_db(db)
1411 ),
1412 vec![(lane, c.start)],
1413 ))
1414}
1415
1416/// `gain_ramp {clip, from, to, from_db?, to_db}`: a straight dB ramp between two
1417/// timeline times. `from_db` defaults to the envelope's level at `from`. Points
1418/// inside `from..=to` are replaced; the ones outside stay.
1419fn gain_ramp(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
1420 let (lane, idx, raw, c) = env_clip(s, op, "gain_ramp")?;
1421 let who = format!("gain_ramp {raw}");
1422 let end = parse::session_end(s);
1423 let from = need(op, "from", fps, end)?;
1424 let to = need(op, "to", fps, end)?;
1425 span_check(&who, &raw, &c, from, to, fps)?;
1426 let (lo, hi) = db_range();
1427 let to_db = req_num_in(op, "to_db", &who, lo, hi)?;
1428 let from_db = match num(op, "from_db")? {
1429 Some(v) => ranged(&who, "from_db", v, lo, hi)?,
1430 None => env_db(s, (lane, idx), &c, from),
1431 };
1432 let (n, changed) = replace_span(s, &who, (lane, idx), &c, (from, to), &[(from, from_db), (to, to_db)])?;
1433 if !changed {
1434 return Ok(done(format!("{who} → already set"), Vec::new()));
1435 }
1436 Ok(done(
1437 format!(
1438 "{who} {} → {} dB to {} dB, {n} points",
1439 span_text(from, to, fps),
1440 fmt_db(from_db),
1441 fmt_db(to_db)
1442 ),
1443 vec![(lane, c.start)],
1444 ))
1445}
1446
1447/// `gain_dip {clip, from, to, db, ramp?="0.5s"}`: dips the envelope to `db` over
1448/// `from..to`, with a ramp of `ramp` in before `from` and back out after `to`. The
1449/// ramps start from the level there is now, and are clamped to the clip; a clamped
1450/// ramp is named in the reply. Points inside the dip (ramps included) are replaced.
1451/// For a dip that follows speech by itself, `duck` is the automatic alternative.
1452fn gain_dip(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
1453 let (lane, idx, raw, c) = env_clip(s, op, "gain_dip")?;
1454 let who = format!("gain_dip {raw}");
1455 let end = parse::session_end(s);
1456 let from = need(op, "from", fps, end)?;
1457 let to = need(op, "to", fps, end)?;
1458 span_check(&who, &raw, &c, from, to, fps).map_err(|e| format!("{e}{}", covering_hint(s, lane, from, to, fps)))?;
1459 let (lo, hi) = db_range();
1460 let db = req_num_in(op, "db", &who, lo, hi)?;
1461 let ramp = length(op, "ramp", fps)?.unwrap_or_else(|| (0.5 * fps).round() as u32);
1462 if ramp == 0 {
1463 return Err(format!("{who}: ramp must be more than 0 (default 0.5s)"));
1464 }
1465 let a = from.saturating_sub(ramp).max(c.start);
1466 let b = to.saturating_add(ramp).min(c.end());
1467 // A ramp cut short by the clip bounds is kept, but the reply says so.
1468 let mut notes = Vec::new();
1469 if from - a < ramp {
1470 notes.push(if from == a {
1471 format!(
1472 "no ramp in: the dip starts at the clip's start, so there is no fade down into it; start it later than {} for a ramp",
1473 tsec(f64::from(c.start), fps)
1474 )
1475 } else {
1476 format!(
1477 "ramp in shortened to {}s: the clip starts at {}",
1478 num_text(f64::from(from - a) / fps),
1479 tsec(f64::from(c.start), fps)
1480 )
1481 });
1482 }
1483 if b - to < ramp {
1484 notes.push(if b == to {
1485 "no ramp out: the dip ends at the clip's end".to_string()
1486 } else {
1487 format!(
1488 "ramp out shortened to {}s: the clip ends at {}",
1489 num_text(f64::from(b - to) / fps),
1490 tsec(f64::from(c.end()), fps)
1491 )
1492 });
1493 }
1494 let note = if notes.is_empty() { String::new() } else { format!(" (note: {})", notes.join("; ")) };
1495 // The ramp ends sit on the level now, read before anything changes.
1496 let mut pts = Vec::with_capacity(4);
1497 if a < from {
1498 pts.push((a, env_db(s, (lane, idx), &c, a)));
1499 }
1500 pts.push((from, db));
1501 pts.push((to, db));
1502 if b > to {
1503 pts.push((b, env_db(s, (lane, idx), &c, b)));
1504 }
1505 let n = pts.len();
1506 let (_, changed) = replace_span(s, &who, (lane, idx), &c, (a, b), &pts)?;
1507 if !changed {
1508 return Ok(done(format!("{who} → already set{note}"), Vec::new()));
1509 }
1510 Ok(done(
1511 format!(
1512 "{who} {} → {} dB (ramps {}s), {n} points{note}",
1513 span_text(from, to, fps),
1514 fmt_db(db),
1515 num_text(f64::from(ramp) / fps)
1516 ),
1517 vec![(lane, c.start)],
1518 ))
1519}
1520
1521/// What a span on a lane is covered by, for a refusal that named a span past one clip: the clips
1522/// of `lane` that the span reaches, so a dip is aimed at the clip (or clips) that play there.
1523/// Empty when no clip of the lane covers any of it.
1524fn covering_hint(s: &PlaybackSession, lane: Lane, from: u32, to: u32, fps: f64) -> String {
1525 let covers: Vec<String> = s
1526 .lane_clips(lane)
1527 .iter()
1528 .filter(|x| x.start < to && x.end() > from)
1529 .map(|x| parse::addr(lane, x.start))
1530 .collect();
1531 let span = format!("{}s–{}s", num_text(f64::from(from) / fps), num_text(f64::from(to) / fps));
1532 match covers.as_slice() {
1533 [] => String::new(),
1534 [one] => format!("; the span {span} is on {one}: dip that clip, or use lane gain keys"),
1535 [first, .., last] => format!(
1536 "; the span {span} covers {first}…{last}: dip each, or use lane gain keys"
1537 ),
1538 }
1539}
1540
1541/// The audio clip an envelope op names: its lane, index, the address as written, and
1542/// a copy of the clip. Video is refused by name, because the envelope is audio only.
1543fn env_clip(s: &PlaybackSession, op: &Value, what: &str) -> Result<(Lane, usize, String, Clip), String> {
1544 let (lane, idx, raw, _) = clip_arg(s, op)?;
1545 if lane.kind != LaneKind::Audio {
1546 return Err(format!(
1547 "{what} {raw}: {raw} is on a video lane, and a clip's volume envelope is set on its audio clip; set it on the audio clip split from the same take"
1548 ));
1549 }
1550 let c = s
1551 .lane_clips(lane)
1552 .get(idx)
1553 .cloned()
1554 .ok_or_else(|| refused(&format!("{what} {raw}")))?;
1555 Ok((lane, idx, raw, c))
1556}
1557
1558/// Puts `new` (timeline frame, dB) points into the envelope over the timeline span
1559/// `span` (both ends inclusive). Old points inside the span go, the ones outside
1560/// stay, and `new` lands on its source frames. Returns the point count and whether
1561/// the envelope changed at all.
1562fn replace_span(
1563 s: &mut PlaybackSession,
1564 who: &str,
1565 env: (Lane, usize),
1566 c: &Clip,
1567 span: (u32, u32),
1568 new: &[(u32, f32)],
1569) -> Result<(usize, bool), String> {
1570 let (lane, idx) = env;
1571 let (lo, hi) = (f64::from(span.0), f64::from(span.1));
1572 let current = s.gain_keys_of(lane, idx).to_vec();
1573 let fresh = keys_of(who, c, new)?;
1574 let mut keys: Vec<GainKey> = current
1575 .iter()
1576 .copied()
1577 .filter(|k| {
1578 let t = timeline_of(c, k.at);
1579 (t < lo || t > hi) && !fresh.iter().any(|f| f.at == k.at)
1580 })
1581 .collect();
1582 keys.extend(fresh);
1583 keys.sort_by_key(|k| k.at);
1584 if keys.len() > MAX_GAIN_KEYS {
1585 return Err(format!(
1586 "{who}: the envelope would hold {} points, and at most {MAX_GAIN_KEYS} fit; remove some first",
1587 keys.len()
1588 ));
1589 }
1590 if keys == current {
1591 return Ok((keys.len(), false));
1592 }
1593 let n = keys.len();
1594 if !s.set_gain_keys(lane, idx, keys) {
1595 return Err(refused(who));
1596 }
1597 Ok((n, true))
1598}
1599
1600/// Timeline-frame points as envelope points on their source frames, sorted. Refused
1601/// when there are too many, or when two land on one source frame.
1602fn keys_of(who: &str, c: &Clip, pts: &[(u32, f32)]) -> Result<Vec<GainKey>, String> {
1603 let eased: Vec<(u32, f32, KeyEase)> = pts.iter().map(|&(t, db)| (t, db, KeyEase::Linear)).collect();
1604 eased_keys_of(who, c, &eased)
1605}
1606
1607/// [`keys_of`] with an ease on each point.
1608fn eased_keys_of(who: &str, c: &Clip, pts: &[(u32, f32, KeyEase)]) -> Result<Vec<GainKey>, String> {
1609 let mut keys: Vec<GainKey> = pts
1610 .iter()
1611 .map(|&(t, db, ease)| GainKey { ease, ..GainKey::new(src_at(c, t), db) })
1612 .collect();
1613 keys.sort_by_key(|k| k.at);
1614 if keys.len() > MAX_GAIN_KEYS {
1615 return Err(format!("{who}: {} points, and at most {MAX_GAIN_KEYS} fit", keys.len()));
1616 }
1617 if keys.windows(2).any(|w| w[0].at == w[1].at) {
1618 return Err(format!(
1619 "{who}: two points land on the same source frame at this speed; space them further apart"
1620 ));
1621 }
1622 Ok(keys)
1623}
1624
1625/// Refuses a timeline frame outside the clip. The clip runs from its start up to and
1626/// including its end boundary, the displayed end, so `to: "3s"` on a clip that plays
1627/// 0–3 s is accepted; the end boundary is the clip's out point in the envelope.
1628fn in_clip(who: &str, raw: &str, c: &Clip, t: u32, fps: f64) -> Result<(), String> {
1629 if t < c.start || t > c.end() {
1630 return Err(format!(
1631 "{who}: {} is outside {raw}, which plays {}–{}",
1632 tsec(f64::from(t), fps),
1633 tsec(f64::from(c.start), fps),
1634 tsec(f64::from(c.end()), fps)
1635 ));
1636 }
1637 Ok(())
1638}
1639
1640/// A ramp's span checked: `from` before `to`, and both inside the clip.
1641fn span_check(who: &str, raw: &str, c: &Clip, from: u32, to: u32, fps: f64) -> Result<(), String> {
1642 if to <= from {
1643 return Err(format!(
1644 "{who}: to ({}) must be after from ({})",
1645 tsec(f64::from(to), fps),
1646 tsec(f64::from(from), fps)
1647 ));
1648 }
1649 in_clip(who, raw, c, from, fps)?;
1650 in_clip(who, raw, c, to, fps)
1651}
1652
1653/// The source frame a timeline frame `t` plays in `c`. The envelope is keyed to
1654/// source frames, so this is how an op's timeline time is stored.
1655fn src_of(c: &Clip, t: f64) -> f64 {
1656 f64::from(c.in_frame) + c.source_offset_f(t - f64::from(c.start))
1657}
1658
1659/// [`src_of`] rounded to a whole source frame, never below 0.
1660pub(super) fn src_at(c: &Clip, t: u32) -> u32 {
1661 src_of(c, f64::from(t)).round().max(0.0) as u32
1662}
1663
1664/// The timeline frame (fractional) at which source frame `at` plays in `c`; the
1665/// inverse of [`src_of`].
1666pub(super) fn timeline_of(c: &Clip, at: u32) -> f64 {
1667 f64::from(c.start) + c.timeline_offset_f(f64::from(at) - f64::from(c.in_frame))
1668}
1669
1670/// The envelope's own dB at timeline frame `t`, clip gain left out: what a ramp
1671/// starts from, so the ramp keeps the level it found.
1672fn env_db(s: &PlaybackSession, env: (Lane, usize), c: &Clip, t: u32) -> f32 {
1673 gain_keys_db_at(s.gain_keys_of(env.0, env.1), src_of(c, f64::from(t)))
1674}
1675
1676/// The envelope's points as timeline times, `10.000s -18.0 dB · …`: at most twelve,
1677/// then `(+N more)`. Shared by `clip_info` and the envelope ops' replies.
1678pub(super) fn points_text(c: &Clip, fps: f64, keys: &[GainKey]) -> String {
1679 const SHOWN: usize = 12;
1680 let mut parts: Vec<String> = keys
1681 .iter()
1682 .take(SHOWN)
1683 .map(|k| format!("{} {} dB{}", tsec(timeline_of(c, k.at), fps), fmt_db(k.db), ease_suffix(k.ease)))
1684 .collect();
1685 if keys.len() > SHOWN {
1686 parts.push(format!("(+{} more)", keys.len() - SHOWN));
1687 }
1688 parts.join(" · ")
1689}
1690
1691fn keys_summary(c: &Clip, fps: f64, keys: &[GainKey]) -> String {
1692 if keys.is_empty() {
1693 "cleared (0 points)".to_string()
1694 } else {
1695 format!("{} point(s): {}", keys.len(), points_text(c, fps, keys))
1696 }
1697}
1698
1699fn db_range() -> (f64, f64) {
1700 (f64::from(MIN_CLIP_GAIN_DB), f64::from(MAX_CLIP_GAIN_DB))
1701}
1702
1703/// A time in seconds at `fps`, three decimals: `10.000s`.
1704fn tsec(t: f64, fps: f64) -> String {
1705 format!("{:.3}s", t / fps)
1706}
1707
1708/// `10.000–25.000s`, the span two timeline frames make.
1709fn span_text(from: u32, to: u32, fps: f64) -> String {
1710 format!("{:.3}–{:.3}s", f64::from(from) / fps, f64::from(to) / fps)
1711}
1712
1713/// A dB value with one decimal; `+ 0.0` turns a negative zero into zero.
1714fn fmt_db(db: f32) -> String {
1715 format!("{:.1}", db + 0.0)
1716}
1717
1718/// A number with trailing zeros dropped: `0.5`, `2`.
1719fn num_text(v: f64) -> String {
1720 let s = format!("{v:.3}");
1721 s.trim_end_matches('0').trim_end_matches('.').to_string()
1722}
1723
1724/// `lane_gain {lane, db}`, -60..+12 dB. Unchanged values are a no-op, not an error.
1725fn lane_gain(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1726 let (lane, raw) = lane_arg(s, op)?;
1727 let who = format!("lane_gain {raw}");
1728 check_unlocked(s, &[lane])?;
1729 let v = num(op, "db")?.ok_or_else(|| format!("{who}: missing argument `db` (-60 to +12 dB)"))?;
1730 let db = ranged(&who, "db", v, -60.0, 12.0)?;
1731 if s.lane_gain_db(lane) == db {
1732 return Ok(done(format!("{who} → already {db:.1} dB"), Vec::new()));
1733 }
1734 if !s.set_lane_gain_db(lane, db) {
1735 return Err(refused(&who));
1736 }
1737 Ok(done(format!("{who} → {db:.1} dB"), Vec::new()))
1738}
1739
1740/// `pan {clip, pan}`, -1 (left) to 1 (right), 0 the middle. An audio clip only.
1741fn pan(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1742 let (lane, idx, raw, start) = clip_arg(s, op)?;
1743 let who = format!("pan {raw}");
1744 if lane.kind != LaneKind::Audio {
1745 return Err(format!("{who}: {raw} is on a video lane, and a clip's pan is set on its audio clip; set it on the audio clip split from the same take"));
1746 }
1747 let v = num(op, "pan")?.ok_or_else(|| format!("{who}: missing argument `pan` (-1 left to 1 right, 0 the middle)"))?;
1748 // Whole percent, which is what is stored.
1749 let pan = (ranged(&who, "pan", v, -1.0, 1.0)? * 100.0).round() as f32 / 100.0;
1750 if s.clip_pan_of(lane, idx) == Some(pan) {
1751 return Ok(done(format!("{who} → already {pan:+.2}"), Vec::new()));
1752 }
1753 if !s.set_clip_pan(lane, idx, pan) {
1754 return Err(refused(&who));
1755 }
1756 Ok(done(format!("{who} → {pan:+.2}"), vec![(lane, start)]))
1757}
1758
1759/// `pitch {clip, semitones}`, -12 (an octave down) to 12 (up), fractions allowed. The speed is kept.
1760fn pitch(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1761 let (lane, idx, raw, start) = clip_arg(s, op)?;
1762 let who = format!("pitch {raw}");
1763 if lane.kind != LaneKind::Audio {
1764 return Err(format!("{who}: {raw} is on a video lane, and a clip's pitch is set on its audio clip; set it on the audio clip split from the same take"));
1765 }
1766 let v = num(op, "semitones")?.ok_or_else(|| format!("{who}: missing argument `semitones` (-12 an octave down to 12 an octave up, 0 the original)"))?;
1767 let semitones = ranged(&who, "semitones", v, -12.0, 12.0)?;
1768 if s.clip_pitch_of(lane, idx) == Some(semitones) {
1769 return Ok(done(format!("{who} → already {semitones:+}"), Vec::new()));
1770 }
1771 if !s.set_clip_pitch(lane, idx, semitones) {
1772 return Err(refused(&who));
1773 }
1774 Ok(done(format!("{who} → {semitones:+} semitones"), vec![(lane, start)]))
1775}
1776
1777/// `lane_pan {lane, pan}`, -1 (left) to 1 (right). Stacks on each clip's own pan.
1778fn lane_pan(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1779 let (lane, raw) = lane_arg(s, op)?;
1780 let who = format!("lane_pan {raw}");
1781 check_unlocked(s, &[lane])?;
1782 let v = num(op, "pan")?.ok_or_else(|| format!("{who}: missing argument `pan` (-1 left to 1 right, 0 the middle)"))?;
1783 // Whole percent, which is what is stored.
1784 let pan = (ranged(&who, "pan", v, -1.0, 1.0)? * 100.0).round() as f32 / 100.0;
1785 if s.lane_pan(lane) == pan {
1786 return Ok(done(format!("{who} → already {pan:+.2}"), Vec::new()));
1787 }
1788 if !s.set_lane_pan(lane, pan) {
1789 return Err(refused(&who));
1790 }
1791 Ok(done(format!("{who} → {pan:+.2}"), Vec::new()))
1792}
1793
1794/// `duck {lane, under?, depth_db?, threshold_db?, attack_ms?, release_ms?, off?}`.
1795/// The audio lane `lane` drops by `depth_db` while the audio lane `under` (the
1796/// key) is above `threshold_db`. Defaults -12 dB, -40 dBFS, 80 ms, 400 ms.
1797/// A lane can duck under several keys: a new `under` adds a duck, the same
1798/// `under` replaces its duck. `off: true` with `under` removes only that key's
1799/// duck; `off: true` alone clears every duck on the lane. The reply lists the
1800/// ducks left on the lane. Ranges are the engine's (`engine::duck`). Like a
1801/// lane lock, a locked lane refuses the duck.
1802fn duck(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1803 let (lane, raw) = lane_arg(s, op)?;
1804 let who = format!("duck {raw}");
1805 if lane.kind != LaneKind::Audio {
1806 return Err(format!(
1807 "{who}: only audio lanes duck, and {raw} is a {} lane",
1808 kind_word(lane.kind)
1809 ));
1810 }
1811 if s.lane_locked(lane) {
1812 let n = parse::lane_name(lane);
1813 return Err(format!(
1814 "lane {n} is locked: unlock it first with lane_flags {{lane:\"{n}\", locked:false}}"
1815 ));
1816 }
1817 let under = match op.get("under") {
1818 None | Some(Value::Null) => None,
1819 Some(Value::String(u)) => Some(u.as_str()),
1820 Some(v) => return Err(format!("{who}: under must be a lane such as \"A1\", got {}", kind_of(v))),
1821 };
1822 if flag(op, "off")? {
1823 return duck_off(s, lane, &who, raw, under);
1824 }
1825 let under = under.ok_or_else(|| {
1826 format!("{who}: give under, the key audio lane such as \"A1\" (or off:true to remove the duck)")
1827 })?;
1828 let key = parse::lane(under)?;
1829 if key.kind != LaneKind::Audio {
1830 return Err(format!("{who}: the key {under} must be an audio lane (A1..)"));
1831 }
1832 if key == lane {
1833 return Err(format!("{who}: a lane is not its own key; give another audio lane as under"));
1834 }
1835 if !s.lanes().contains(&key) {
1836 return Err(format!("{who}: the key {under} is not a lane on this timeline"));
1837 }
1838 let depth_db = or_default(&who, op, "depth_db", -12.0, MIN_DEPTH_DB, MAX_DEPTH_DB)?;
1839 let threshold_db = or_default(
1840 &who,
1841 op,
1842 "threshold_db",
1843 Duck::DEFAULT_THRESHOLD_DB,
1844 MIN_THRESHOLD_DB,
1845 MAX_THRESHOLD_DB,
1846 )?;
1847 let attack_ms = or_default(&who, op, "attack_ms", Duck::DEFAULT_ATTACK_MS, MIN_TIME_MS, MAX_ATTACK_MS)?;
1848 let release_ms = or_default(
1849 &who,
1850 op,
1851 "release_ms",
1852 Duck::DEFAULT_RELEASE_MS,
1853 MIN_TIME_MS,
1854 MAX_RELEASE_MS,
1855 )?;
1856 // A duck under a key the lane already has replaces that one; a new key adds a duck.
1857 let set = Duck { under: key.ord, depth_db, threshold_db, attack_ms, release_ms };
1858 if s.lane_duck_list(lane).contains(&set) {
1859 return Ok(done(format!("{who} → already set"), Vec::new()));
1860 }
1861 if !s.set_lane_duck(lane, Some(set)) {
1862 return Err(refused(&who));
1863 }
1864 let key_name = parse::lane_name(key);
1865 Ok(done(
1866 format!(
1867 "duck {} under {key_name}: {depth_db} dB when {key_name} > {threshold_db} dBFS (attack {attack_ms} ms, release {release_ms} ms); {}",
1868 parse::lane_name(lane),
1869 ducks_now(s, lane)
1870 ),
1871 Vec::new(),
1872 ))
1873}
1874
1875/// `duck {lane, off:true}` removes the duck under `under` and keeps the lane's
1876/// other ducks; with no `under` it clears every duck on the lane. The reply
1877/// lists the ducks left on the lane.
1878fn duck_off(
1879 s: &mut PlaybackSession,
1880 lane: Lane,
1881 who: &str,
1882 raw: &str,
1883 under: Option<&str>,
1884) -> Result<Applied, String> {
1885 let Some(under) = under else {
1886 let had = s.lane_duck_list(lane);
1887 if had.is_empty() {
1888 return Ok(done(format!("{who} → already off"), Vec::new()));
1889 }
1890 if !s.set_lane_duck(lane, None) {
1891 return Err(refused(who));
1892 }
1893 let names: Vec<String> = had.iter().map(|d| parse::lane_name(Lane::new(LaneKind::Audio, d.under))).collect();
1894 return Ok(done(
1895 format!("{who} → all {} ducks removed ({})", had.len(), names.join(", ")),
1896 Vec::new(),
1897 ));
1898 };
1899 let key = parse::lane(under)?;
1900 if key.kind != LaneKind::Audio {
1901 return Err(format!("{who}: the key {under} must be an audio lane (A1..)"));
1902 }
1903 let key_name = parse::lane_name(key);
1904 if !s.lane_duck_list(lane).iter().any(|d| d.under == key.ord) {
1905 return Ok(done(format!("{who} under {key_name} → already off"), Vec::new()));
1906 }
1907 if !s.clear_lane_duck(lane, key.ord) {
1908 return Err(refused(who));
1909 }
1910 Ok(done(
1911 format!("duck {raw} under {key_name} → removed; {}", ducks_now(s, lane)),
1912 Vec::new(),
1913 ))
1914}
1915
1916/// The ducks on `lane` now, for a reply: each key with its depth and threshold,
1917/// or that the lane has none.
1918fn ducks_now(s: &PlaybackSession, lane: Lane) -> String {
1919 let ducks = s.lane_duck_list(lane);
1920 if ducks.is_empty() {
1921 return format!("{} has no ducks", parse::lane_name(lane));
1922 }
1923 let each: Vec<String> = ducks
1924 .iter()
1925 .map(|d| {
1926 format!(
1927 "{} ({} dB when over {} dBFS)",
1928 parse::lane_name(Lane::new(LaneKind::Audio, d.under)),
1929 d.depth_db,
1930 d.threshold_db
1931 )
1932 })
1933 .collect();
1934 format!("{} now ducked under {}", parse::lane_name(lane), each.join(", "))
1935}
1936
1937/// `limiter {on?, ceiling_db?}`, ceiling -24..0 dB. Merges onto the current setting.
1938fn limiter(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1939 let on = flag_opt(op, "on")?;
1940 let ceiling = num(op, "ceiling_db")?;
1941 if on.is_none() && ceiling.is_none() {
1942 return Err("limiter: give on (true or false) and/or ceiling_db (-24 to 0)".to_string());
1943 }
1944 let cur = s.limiter();
1945 let mut next = cur;
1946 if let Some(v) = ceiling {
1947 next.ceiling_db = ranged(
1948 "limiter",
1949 "ceiling_db",
1950 v,
1951 f64::from(Limiter::MIN_DB),
1952 f64::from(Limiter::MAX_DB),
1953 )?;
1954 }
1955 if let Some(b) = on {
1956 next.on = b;
1957 }
1958 let text = |l: Limiter| {
1959 format!(
1960 "limiter → {}, ceiling {:.1} dB",
1961 if l.on { "on" } else { "off" },
1962 l.ceiling_db
1963 )
1964 };
1965 if next == cur {
1966 return Ok(done(format!("{} (unchanged)", text(cur)), Vec::new()));
1967 }
1968 if !s.set_limiter(next) {
1969 return Err("limiter: the engine refused the change".to_string());
1970 }
1971 Ok(done(text(next), Vec::new()))
1972}
1973
1974/// `lane_add {kind: "video"|"audio"|"subtitle"}`. Reports the new lane's name.
1975fn lane_add(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1976 let kind = match req_str(op, "kind")? {
1977 "video" => LaneKind::Video,
1978 "audio" => LaneKind::Audio,
1979 "subtitle" => LaneKind::Subtitle,
1980 other => {
1981 return Err(format!(
1982 "lane_add: `{other}` is not a lane kind; use video, audio or subtitle"
1983 ))
1984 }
1985 };
1986 let lane = s.add_lane(kind);
1987 Ok(done(format!("lane_add → {} added", parse::lane_name(lane)), Vec::new()))
1988}
1989
1990/// `lane_remove {lane}`. The engine refuses a lane that holds clips, and the
1991/// last video or audio lane.
1992fn lane_remove(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
1993 let (lane, raw) = lane_arg(s, op)?;
1994 check_unlocked(s, &[lane])?;
1995 // A lane that holds media clips is refused here, naming each clip by the address the edit ops
1996 // take (A2@0) and its file by name, so the caller can delete exactly those.
1997 if lane.kind != LaneKind::Subtitle && !s.lane_clips(lane).is_empty() {
1998 const MAX: usize = 8;
1999 let clips = s.lane_clips(lane);
2000 let shown: Vec<String> = clips
2001 .iter()
2002 .take(MAX)
2003 .map(|c| {
2004 let file = s
2005 .sources()
2006 .get(c.source)
2007 .and_then(|src| src.path.file_name())
2008 .map_or_else(|| format!("src:{}", c.source), |f| f.to_string_lossy().into_owned());
2009 format!("{} ({file})", parse::addr(lane, c.start))
2010 })
2011 .collect();
2012 let more = if clips.len() > MAX { format!(" and {} more", clips.len() - MAX) } else { String::new() };
2013 return Err(format!(
2014 "lane_remove {raw}: {raw} still holds {} clip(s): {}{more}; delete those clips (or drag them to another track) first",
2015 clips.len(),
2016 shown.join(", ")
2017 ));
2018 }
2019 s.remove_lane(lane)
2020 .map_err(|e| format!("lane_remove {raw}: {e}"))?;
2021 Ok(done(format!("lane_remove → {raw} removed"), Vec::new()))
2022}
2023
2024/// `lane_move {lane, to}`: `to` is the 1-based display position among all lanes.
2025/// Lanes are named by position, so moving a lane renumbers every lane between the old place and
2026/// the new one: a move of V2 to position 3 renames V2 to V3 and the old V3 to V2. The reply gives
2027/// the moved lane's new name and position, then lists each renamed lane. A locked lane moves
2028/// (its lock travels with it). The moved lane's clips are touched under their new name.
2029fn lane_move(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2030 let (lane, raw) = lane_arg(s, op)?;
2031 let who = format!("lane_move {raw}");
2032 let v = num(op, "to")?.ok_or_else(|| format!("{who}: missing argument `to` (1-based position)"))?;
2033 let all = s.lanes();
2034 let n = all.len();
2035 if v.fract() != 0.0 || v < 1.0 || v > n as f64 {
2036 return Err(format!(
2037 "{who}: to {v} is out of range; the timeline has {n} lane(s), positions 1–{n}"
2038 ));
2039 }
2040 let to = v as usize;
2041 let current = all.iter().position(|l| *l == lane).map_or(0, |i| i + 1);
2042 if to == current {
2043 return Ok(done(format!("{who} → already at position {to}"), Vec::new()));
2044 }
2045 let moved = s
2046 .move_lane(lane, to - 1)
2047 .ok_or_else(|| format!("{who}: nothing moved"))?;
2048 let touched = starts_on(s, moved);
2049 let renamed = renamed_by_position(s, &all, &s.lanes(), current - 1, to - 1);
2050 Ok(done(
2051 format!("{who} → {} (position {to}){renamed}", parse::lane_name(moved)),
2052 touched,
2053 ))
2054}
2055
2056/// The lanes a move renamed. A lane's name is its kind and its place among that kind's lanes, so
2057/// the lanes between the old place and the new one shift by one and take each other's names. Each
2058/// lane whose name changed is listed with what it holds (its lock, its first clip's file), so the
2059/// name a caller used before still reads as the lane it was.
2060fn renamed_by_position(s: &PlaybackSession, before: &[Lane], after: &[Lane], from: usize, to: usize) -> String {
2061 let new_pos = |p: usize| -> usize {
2062 if p == from {
2063 to
2064 } else if from < to && p > from && p <= to {
2065 p - 1
2066 } else if to < from && p >= to && p < from {
2067 p + 1
2068 } else {
2069 p
2070 }
2071 };
2072 let mut parts = Vec::new();
2073 for (i, old) in before.iter().enumerate() {
2074 let Some(&new) = after.get(new_pos(i)) else { continue };
2075 if parse::lane_name(*old) == parse::lane_name(new) {
2076 continue;
2077 }
2078 let mut what = Vec::new();
2079 if s.lane_locked(new) {
2080 what.push("locked".to_string());
2081 }
2082 let first = if new.kind == LaneKind::Subtitle {
2083 None
2084 } else {
2085 s.lane_clips(new).first().and_then(|c| s.sources().get(c.source))
2086 };
2087 if let Some(name) = first.and_then(|src| src.path.file_name()) {
2088 what.push(name.to_string_lossy().into_owned());
2089 }
2090 let note = if what.is_empty() { String::new() } else { format!(" ({})", what.join(", ")) };
2091 parts.push(format!("{} → {}{note}", parse::lane_name(*old), parse::lane_name(new)));
2092 }
2093 if parts.is_empty() {
2094 return String::new();
2095 }
2096 format!(
2097 "; lanes renamed by position: {} — lanes are named by position, so the lanes between the two places renumber; use the new names from now on",
2098 parts.join(", ")
2099 )
2100}
2101
2102/// `lane_flags {lane, hidden?, muted?, locked?}`. `hidden` is for video and
2103/// subtitle lanes, `muted` for audio, `locked` for any. Unchanged flags are fine.
2104fn lane_flags(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2105 let (lane, raw) = lane_arg(s, op)?;
2106 let who = format!("lane_flags {raw}");
2107 let hidden = flag_opt(op, "hidden")?;
2108 let muted = flag_opt(op, "muted")?;
2109 let locked = flag_opt(op, "locked")?;
2110 if hidden.is_none() && muted.is_none() && locked.is_none() {
2111 return Err(format!("{who}: give at least one of hidden, muted, locked (true or false)"));
2112 }
2113 // Only the lock itself may change on a locked lane, and unlocking is the way out of it.
2114 // Each flag counts only on the kinds it applies to, so a wrong-kind flag keeps its own refusal.
2115 let changes_look = hidden
2116 .is_some_and(|v| v != s.lane_hidden(lane) && lane.kind != LaneKind::Audio)
2117 || muted.is_some_and(|v| v != s.lane_muted(lane) && lane.kind == LaneKind::Audio);
2118 if changes_look && locked != Some(false) {
2119 check_unlocked(s, &[lane])?;
2120 }
2121 let mut shown = Vec::new();
2122 if let Some(v) = hidden {
2123 if s.lane_hidden(lane) != v && !s.set_lane_hidden(lane, v) {
2124 return Err(format!("{who}: hidden does not apply to {} lanes", kind_word(lane.kind)));
2125 }
2126 shown.push(format!("hidden {v}"));
2127 }
2128 if let Some(v) = muted {
2129 if s.lane_muted(lane) != v && !s.set_lane_muted(lane, v) {
2130 return Err(format!("{who}: muted does not apply to {} lanes", kind_word(lane.kind)));
2131 }
2132 shown.push(format!("muted {v}"));
2133 }
2134 if let Some(v) = locked {
2135 if s.lane_locked(lane) != v && !s.set_lane_locked(lane, v) {
2136 return Err(refused(&who));
2137 }
2138 shown.push(format!("locked {v}"));
2139 }
2140 Ok(done(format!("{who} → {}", shown.join(", ")), Vec::new()))
2141}
2142
2143/// `lane_name {lane, name}`: the lane's display label; an empty name clears it. A locked lane
2144/// refuses, like any change to a lane.
2145fn lane_name(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2146 let (lane, raw) = lane_arg(s, op)?;
2147 let who = format!("lane_name {raw}");
2148 let name = op
2149 .get("name")
2150 .and_then(Value::as_str)
2151 .ok_or_else(|| format!("{who}: give name (text; \"\" clears it)"))?;
2152 check_unlocked(s, &[lane])?;
2153 match s.set_lane_name(lane, name) {
2154 Err(e) => Err(format!("{who}: {e}")),
2155 Ok(false) => Ok(done(format!("{who} → unchanged"), Vec::new())),
2156 Ok(true) => Ok(done(
2157 match s.lane_name(lane) {
2158 Some(n) => format!("{who} → \"{n}\""),
2159 None => format!("{who} → name cleared"),
2160 },
2161 Vec::new(),
2162 )),
2163 }
2164}
2165
2166/// `deinterlace {clip, mode: frame|field|off|ivtc-auto|ivtc}`.
2167fn deinterlace(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2168 let (lane, idx, raw, start) = clip_arg(s, op)?;
2169 let name = req_str(op, "mode")?;
2170 let mode = engine::project::Deinterlace::from_name(name)
2171 .ok_or_else(|| format!("deinterlace {raw}: `{name}` is not a mode; use frame, field or off (or ivtc-auto or ivtc to remove pulldown)"))?;
2172 if s.deinterlace_of(lane, idx) == mode {
2173 return Ok(done(format!("deinterlace {raw} → {name} (unchanged)"), vec![(lane, start)]));
2174 }
2175 if !s.set_deinterlace(lane, idx, mode) {
2176 return Err(refused(&format!("deinterlace {raw}")));
2177 }
2178 Ok(done(format!("deinterlace {raw} → {name}"), vec![(lane, start)]))
2179}
2180
2181/// `group {clips: [addr, ...]}`: two or more clips, each an address such as `V1@450`.
2182fn group(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2183 let arr = op
2184 .get("clips")
2185 .and_then(Value::as_array)
2186 .ok_or_else(|| "group: clips must be a list of clip addresses such as [\"V1@0\", \"A1@0\"]".to_string())?;
2187 if arr.len() < 2 {
2188 return Err(format!("group: give at least two clips, got {}", arr.len()));
2189 }
2190 let mut picks = Vec::with_capacity(arr.len());
2191 let mut raws: Vec<&str> = Vec::with_capacity(arr.len());
2192 for v in arr {
2193 let raw = v
2194 .as_str()
2195 .ok_or_else(|| format!("group: each clip is an address string, got {}", kind_of(v)))?;
2196 picks.push(super::edit::clip_addr(s, raw)?);
2197 raws.push(raw);
2198 }
2199 // Grouping relinks each pick's take, so a locked lane in any of those takes refuses.
2200 let mut lanes: Vec<Lane> = Vec::new();
2201 for &(l, i) in &picks {
2202 for t in take_lanes_of(s, l, i) {
2203 if !lanes.contains(&t) {
2204 lanes.push(t);
2205 }
2206 }
2207 }
2208 check_unlocked(s, &lanes)?;
2209 s.group_all(&picks).map_err(|e| format!("group: {e}"))?;
2210 let touched = picks
2211 .iter()
2212 .map(|&(l, i)| (l, start_of(s, l, i)))
2213 .collect();
2214 // Members of one group are often different lengths (a picture and its sound, say): the group
2215 // holds them together, but their ends do not meet, so the reply says how long each one is.
2216 let fps = parse::session_fps(s);
2217 let lens: Vec<(&str, u32)> = raws
2218 .iter()
2219 .zip(&picks)
2220 .filter_map(|(raw, &(l, i))| s.lane_clips(l).get(i).map(|c| (*raw, c.frames())))
2221 .collect();
2222 let mut text = format!("group → {} clips", picks.len());
2223 if lens.windows(2).any(|w| w[0].1 != w[1].1) {
2224 let each: Vec<String> = lens.iter().map(|(raw, f)| format!("{raw} {:.3}s", parse::secs(*f, fps))).collect();
2225 text.push_str(&format!("; the members differ in length ({}), so their ends do not meet", each.join(", ")));
2226 }
2227 Ok(done(text, touched))
2228}
2229
2230/// `ungroup {clip}`.
2231fn ungroup(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2232 let (lane, idx, raw, start) = clip_arg(s, op)?;
2233 // Taking the clip out of its take changes the whole take, so a locked lane in it refuses.
2234 check_unlocked(s, &take_lanes_of(s, lane, idx))?;
2235 if !s.ungroup(lane, idx) {
2236 return Err(format!("ungroup {raw}: nothing to ungroup (the clip is alone or not grouped)"));
2237 }
2238 Ok(done(format!("ungroup {raw} → taken out of its group"), vec![(lane, start)]))
2239}
2240
2241/// `subtitles_import {path, lang?}`. The engine puts the tracks in the timeline's
2242/// subtitle list; it does not place them on a lane (the GUI does not either, so
2243/// there is no lane to report). Captions are placed afterwards with `captions_place`.
2244/// `lang` names the tracks' language; left out, a standalone file's own name
2245/// says it (`talk.fr.srt`, `fra.srt`), and when neither does the tracks stay unset.
2246fn subtitles_import(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
2247 let raw = req_str(op, "path")?;
2248 let lang = match op.get("lang") {
2249 None | Some(Value::Null) => None,
2250 Some(v) => Some(v.as_str().ok_or("subtitles_import: `lang` must be a language code such as fra")?),
2251 };
2252 let (n, named) = s
2253 .import_subtitles_as(Path::new(raw), lang)
2254 .map_err(|e| format!("subtitles_import {raw}: {e}"))?;
2255 let lang_note = match &named {
2256 Some((code, how)) => format!(" · lang {code}, {how}"),
2257 None => " · lang unset (und on export)".to_string(),
2258 };
2259 let text = if n == 0 {
2260 format!("subtitles_import {raw}: no new track, already on the timeline")
2261 } else {
2262 // The new tracks are the last `n` in the list; their indices are what captions_place takes.
2263 let tracks = s.subtitles();
2264 let first = tracks.len().saturating_sub(n);
2265 let cues: usize = tracks[first..].iter().map(|t| t.cues.len()).sum();
2266 let noun = if n == 1 { "track" } else { "tracks" };
2267 let at = if n == 1 {
2268 format!("#{first}, {cues} cues")
2269 } else {
2270 format!("#{first}..#{}, {cues} cues", tracks.len() - 1)
2271 };
2272 let place = if n == 1 {
2273 format!("captions_place {{track:{first}}}")
2274 } else {
2275 "captions_place {track:N}, once per track".to_string()
2276 };
2277 format!("imported {n} {noun} ({at}){lang_note} — not on the timeline yet; place it with {place}")
2278 };
2279 // Cues the parser had to drop are named, so a short import is not a silent one.
2280 let skipped = engine::subtitle::skipped_cues(Path::new(raw));
2281 let text = if skipped.is_empty() {
2282 text
2283 } else {
2284 // Each skipped entry is `line N: reason`: the cues are counted as cues, named by their lines.
2285 let parts: Vec<(Option<&str>, &str)> = skipped
2286 .iter()
2287 .map(|k| match k.split_once(": ") {
2288 Some((head, why)) if head.starts_with("line ") => (Some(&head["line ".len()..]), why),
2289 _ => (None, k.as_str()),
2290 })
2291 .collect();
2292 let nums: Vec<&str> = parts.iter().filter_map(|(n, _)| *n).collect();
2293 let noun = if skipped.len() == 1 { "cue" } else { "cues" };
2294 let shown = match nums.as_slice() {
2295 [] => String::new(),
2296 [one] => format!(" (line {one})"),
2297 [a, b] => format!(" (lines {a}, {b})"),
2298 [a, b, ..] => format!(" (lines {a}, {b}, …)"),
2299 };
2300 let reasons: Vec<&str> = parts.iter().map(|(_, why)| *why).collect();
2301 format!("{text}\nskipped {} {noun}{shown}, not imported: {}", skipped.len(), reasons.join("; "))
2302 };
2303 Ok(done(text, Vec::new()))
2304}
2305
2306// ---- helpers --------------------------------------------------------------
2307
2308// ---- titles ---------------------------------------------------------------
2309
2310/// The name a title goes by: `T1` for the first in start order.
2311pub(super) fn title_name(idx: usize) -> String {
2312 format!("T{}", idx + 1)
2313}
2314
2315/// The place a title sits at, as the ops spell it.
2316pub(super) fn place_word(p: Place) -> &'static str {
2317 match p {
2318 Place::Bottom => "bottom",
2319 Place::Top => "top",
2320 Place::Centre => "centre",
2321 }
2322}
2323
2324/// The outline a title draws, as the ops spell it.
2325pub(super) fn outline_word(o: Outline) -> &'static str {
2326 match o {
2327 Outline::None => "none",
2328 Outline::Thin => "thin",
2329 Outline::Thick => "thick",
2330 }
2331}
2332
2333/// The side a block sits at or lines align to, as the ops spell it.
2334fn side_word(h: HPlace) -> &'static str {
2335 match h {
2336 HPlace::Centre => "centre",
2337 HPlace::Left => "left",
2338 HPlace::Right => "right",
2339 }
2340}
2341
2342/// One title, as a reply line: `title T1 "Episode 17" 0.000–3.000 centre size 80 outline thin fade 12f/12f`.
2343/// A newline in the text shows as `\n`. A look off the default adds ` colour #ffcc00 bold left/right
2344/// box #0a141e/78%` after the outline: only what differs from white, regular, centred, black 60%.
2345pub(super) fn title_line(name: &str, t: &Title, fps: f64) -> String {
2346 let d = TextStyle::default();
2347 let st = &t.style;
2348 let mut look = String::new();
2349 if st.ink != d.ink {
2350 look.push_str(&format!(" colour #{:02x}{:02x}{:02x}", st.ink[0], st.ink[1], st.ink[2]));
2351 }
2352 if st.weight == Weight::Bold {
2353 look.push_str(" bold");
2354 }
2355 if st.hplace != d.hplace {
2356 look.push_str(&format!(" {}", side_word(st.hplace)));
2357 }
2358 if st.align != d.align {
2359 look.push_str(&format!(" align {}", side_word(match st.align {
2360 Align::Centre => HPlace::Centre,
2361 Align::Left => HPlace::Left,
2362 Align::Right => HPlace::Right,
2363 })));
2364 }
2365 if st.boxed && st.box_color != d.box_color {
2366 let c = st.box_color;
2367 look.push_str(&format!(" box #{:02x}{:02x}{:02x}/{}%", c[0], c[1], c[2], (u32::from(c[3]) * 100 + 127) / 255));
2368 }
2369 let boxed = if t.style.boxed { " boxed" } else { "" };
2370 format!(
2371 "title {name} \"{}\" {:.3}–{:.3} {} size {} outline {}{boxed}{look} fade {}f/{}f{anim}{keys}",
2372 t.text.replace('\n', "\\n"),
2373 parse::secs(t.start, fps),
2374 parse::secs(t.end(), fps),
2375 place_word(t.style.place),
2376 t.style.size,
2377 outline_word(t.style.outline),
2378 t.fade_in,
2379 t.fade_out,
2380 anim = if t.in_anim == TitleAnim::None && t.out_anim == TitleAnim::None {
2381 String::new()
2382 } else {
2383 format!(" anim in {} out {} {}f", t.in_anim.name(), t.out_anim.name(), t.anim_frames)
2384 },
2385 keys = title_keys_text(t, fps)
2386 )
2387}
2388
2389/// The `in_anim` or `out_anim` word, when given: one of the engine's title animations.
2390fn anim_arg(op: &Value, key: &str) -> Result<Option<TitleAnim>, String> {
2391 match word_opt(op, key)? {
2392 None => Ok(None),
2393 Some(w) => TitleAnim::from_name(w).map(Some).ok_or_else(|| {
2394 format!("title {key} `{w}` is not none, fade, typewriter, slide_up, slide_left, pop, or word_by_word")
2395 }),
2396 }
2397}
2398
2399/// The animation fields an op may give, merged onto `t`: `in_anim`, `out_anim` and `anim_secs`.
2400/// A title that gains an animation and no `anim_secs` takes half a second of it.
2401fn title_anim_fields(op: &Value, t: &mut Title, fps: f64) -> Result<(), String> {
2402 let (ins, outs) = (anim_arg(op, "in_anim")?, anim_arg(op, "out_anim")?);
2403 if let Some(a) = ins {
2404 t.in_anim = a;
2405 }
2406 if let Some(a) = outs {
2407 t.out_anim = a;
2408 }
2409 // A bare number is seconds here, unlike the fades, which are frames.
2410 match op.get("anim_secs") {
2411 None | Some(Value::Null) => {}
2412 Some(v) => t.anim_frames = parse::frame(v, fps, u32::MAX).map_err(|e| format!("`anim_secs`: {e}"))?,
2413 }
2414 if t.anim_frames == 0 && (ins.is_some() || outs.is_some()) {
2415 t.anim_frames = (engine::titleanim::DEFAULT_SECS * fps).round().max(1.) as u32;
2416 }
2417 Ok(())
2418}
2419
2420/// The style fields an op may give, merged onto `st`: `size`, `outline`, `boxed`, `place`.
2421fn title_style(op: &Value, mut st: TextStyle) -> Result<TextStyle, String> {
2422 if let Some(v) = num(op, "size")? {
2423 let lo = f64::from(SIZE_RANGE.0);
2424 let hi = f64::from(SIZE_RANGE.1);
2425 st.size = ranged("title", "size", v, lo, hi)?.round() as u32;
2426 }
2427 if let Some(w) = word_opt(op, "outline")? {
2428 st.outline = match w {
2429 "none" => Outline::None,
2430 "thin" => Outline::Thin,
2431 "thick" => Outline::Thick,
2432 other => return Err(format!("title outline `{other}` is not none, thin or thick")),
2433 };
2434 }
2435 if let Some(w) = word_opt(op, "place")? {
2436 st.place = match w {
2437 "bottom" => Place::Bottom,
2438 "top" => Place::Top,
2439 "centre" | "center" => Place::Centre,
2440 other => return Err(format!("title place `{other}` is not bottom, top or centre")),
2441 };
2442 }
2443 if let Some(b) = flag_opt(op, "boxed")? {
2444 st.boxed = b;
2445 }
2446 if let Some(w) = word_opt(op, "color")?.or(word_opt(op, "colour")?) {
2447 let hex = hex_digits("color", w, 6)?;
2448 st.ink = [hex[0], hex[1], hex[2]];
2449 }
2450 if let Some(w) = word_opt(op, "weight")? {
2451 st.weight = match w {
2452 "regular" => Weight::Regular,
2453 "bold" => Weight::Bold,
2454 other => return Err(format!("title weight `{other}` is not regular or bold")),
2455 };
2456 }
2457 if let Some(w) = word_opt(op, "hplace")? {
2458 st.hplace = match w {
2459 "centre" | "center" => HPlace::Centre,
2460 "left" => HPlace::Left,
2461 "right" => HPlace::Right,
2462 other => return Err(format!("title hplace `{other}` is not left, centre or right")),
2463 };
2464 }
2465 if let Some(w) = word_opt(op, "align")? {
2466 st.align = match w {
2467 "centre" | "center" => Align::Centre,
2468 "left" => Align::Left,
2469 "right" => Align::Right,
2470 other => return Err(format!("title align `{other}` is not left, centre or right")),
2471 };
2472 }
2473 if let Some(w) = word_opt(op, "box_color")?.or(word_opt(op, "box_colour")?) {
2474 // Six digits change the colour and keep the opacity; eight set both.
2475 let hex = if w.trim().trim_start_matches('#').len() == 8 {
2476 hex_digits("box_color", w, 8)?
2477 } else {
2478 hex_digits("box_color", w, 6)?
2479 };
2480 st.box_color = [hex[0], hex[1], hex[2], hex.get(3).copied().unwrap_or(st.box_color[3])];
2481 }
2482 if let Some(v) = num(op, "box_opacity")? {
2483 st.box_color[3] = (ranged("title", "box_opacity", v, 0.0, 1.0)? * 255.0).round() as u8;
2484 }
2485 Ok(st)
2486}
2487
2488/// `#ff3366` or `ff3366` (or eight digits with an opacity) as bytes.
2489fn hex_digits(key: &str, text: &str, digits: usize) -> Result<Vec<u8>, String> {
2490 let t = text.trim().trim_start_matches('#');
2491 if t.len() != digits || !t.bytes().all(|b| b.is_ascii_hexdigit()) {
2492 let shape = if digits == 6 { "six hex digits such as \"#ffcc00\"" } else { "six or eight hex digits such as \"#000000\" or \"#000000c8\"" };
2493 return Err(format!("title {key} {text:?} is not a colour; give {shape}"));
2494 }
2495 Ok((0..digits / 2).map(|i| u8::from_str_radix(&t[i * 2..i * 2 + 2], 16).unwrap_or(0)).collect())
2496}
2497
2498/// An optional word argument; missing or null is `None`.
2499fn word_opt<'a>(op: &'a Value, key: &str) -> Result<Option<&'a str>, String> {
2500 match op.get(key) {
2501 None | Some(Value::Null) => Ok(None),
2502 Some(Value::String(t)) => Ok(Some(t.as_str())),
2503 Some(v) => Err(format!("`{key}` must be a word such as thin, got {}", kind_of(v))),
2504 }
2505}
2506
2507/// The `preset` word, when given: the engine's one-click look ([`TitlePreset`]).
2508fn title_preset_arg(op: &Value) -> Result<Option<TitlePreset>, String> {
2509 match word_opt(op, "preset")? {
2510 None => Ok(None),
2511 Some(w) => TitlePreset::from_key(w)
2512 .map(Some)
2513 .ok_or_else(|| format!("title preset `{w}` is not lower_third, centered or caption_bar")),
2514 }
2515}
2516
2517/// The `at` of a title key: a time from the title's first frame, read as `title_add` reads its
2518/// times (a bare number is seconds), `end` for the title's last frame, or a percentage of its length.
2519fn title_key_offset(n: usize, at: &Value, frames: u32, fps: f64) -> Result<u32, String> {
2520 if let Some(text) = at.as_str() {
2521 let text = text.trim();
2522 if text.eq_ignore_ascii_case("end") {
2523 return Ok(frames);
2524 }
2525 if let Some(pct) = text.strip_suffix('%') {
2526 let share: f64 = pct
2527 .trim()
2528 .parse()
2529 .map_err(|_| format!("title keys: key {n} at {text:?} is not a percentage"))?;
2530 if !(0.0..=100.0).contains(&share) {
2531 return Err(format!("title keys: key {n} at {text} is outside the title, 0% to 100%"));
2532 }
2533 return Ok((f64::from(frames) * share / 100.0).round() as u32);
2534 }
2535 }
2536 parse::frame(at, fps, u32::MAX).map_err(|e| format!("title keys: key {n}: {e}"))
2537}
2538
2539/// The `keys` of a `title_add` or `title_set`: a list of `{at, x?, y?, scale?, opacity?, ease?}`,
2540/// each `at` a time from the title's first frame. A key leaves x and y at 0 and scale and opacity
2541/// at 1 when it does not name them. `[]` takes the animation off, and `None` means the op gives no
2542/// `keys`. A key past the title's `frames` holds its value there.
2543fn title_keys_arg(op: &Value, fps: f64, frames: u32) -> Result<Option<Vec<TitleKey>>, String> {
2544 let list = match op.get("keys") {
2545 None | Some(Value::Null) => return Ok(None),
2546 Some(Value::Array(a)) => a,
2547 Some(v) => {
2548 return Err(format!(
2549 "title keys must be a list of {{at, x?, y?, scale?, opacity?, ease?}} objects, got {}",
2550 kind_of(v)
2551 ))
2552 }
2553 };
2554 if list.len() > MAX_TRANSFORM_KEYS {
2555 return Err(format!("title keys: {} keys, and at most {MAX_TRANSFORM_KEYS} fit", list.len()));
2556 }
2557 let who = "title keys";
2558 let mut keys: Vec<TitleKey> = Vec::with_capacity(list.len());
2559 for (i, k) in list.iter().enumerate() {
2560 let n = i + 1;
2561 let obj = k.as_object().ok_or_else(|| {
2562 format!("{who}: key {n} must be an object such as {{\"at\": \"0s\", \"opacity\": 0}}")
2563 })?;
2564 if let Some(bad) = obj
2565 .keys()
2566 .find(|name| !matches!(name.as_str(), "at" | "x" | "y" | "scale" | "opacity" | "ease"))
2567 {
2568 return Err(format!(
2569 "{who}: key {n} has `{bad}`, which a title key does not take: x, y, scale, opacity, ease, at"
2570 ));
2571 }
2572 let at = obj
2573 .get("at")
2574 .ok_or_else(|| format!("{who}: key {n} has no `at`, the time from the title's first frame"))?;
2575 keys.push(TitleKey {
2576 at: title_key_offset(n, at, frames, fps)?,
2577 x: or_default(who, k, "x", 0.0, -1.0, 1.0)?,
2578 y: or_default(who, k, "y", 0.0, -1.0, 1.0)?,
2579 scale: or_default(who, k, "scale", 1.0, KEY_SCALE_RANGE.0, KEY_SCALE_RANGE.1)?,
2580 opacity: or_default(who, k, "opacity", 1.0, 0.0, 1.0)?,
2581 ease: ease_of(who, n, k)?,
2582 });
2583 }
2584 keys.sort_by_key(|k| k.at);
2585 if keys.windows(2).any(|w| w[0].at == w[1].at) {
2586 return Err(format!("{who}: two keys at the same time; space them further apart"));
2587 }
2588 Ok(Some(keys))
2589}
2590
2591/// A title's keys as the JSON a listing carries: each `at` in seconds from the title's start.
2592pub(super) fn title_keys_json(t: &Title, fps: f64) -> Value {
2593 Value::Array(
2594 t.keys
2595 .iter()
2596 .map(|k| {
2597 json!({
2598 "at": parse::secs(k.at, fps),
2599 "x": k.x,
2600 "y": k.y,
2601 "scale": k.scale,
2602 "opacity": k.opacity,
2603 "ease": k.ease.name(),
2604 })
2605 })
2606 .collect(),
2607 )
2608}
2609
2610/// A title's keys as a reply fragment, ` keys 2: +0.000s x 0.00 y 0.00 scale 1.00 opacity 0.00 · …`,
2611/// at most twelve, then `(+N more)`. Empty for a title with none.
2612pub(super) fn title_keys_text(t: &Title, fps: f64) -> String {
2613 const SHOWN: usize = 12;
2614 if t.keys.is_empty() {
2615 return String::new();
2616 }
2617 let mut parts: Vec<String> = t
2618 .keys
2619 .iter()
2620 .take(SHOWN)
2621 .map(|k| {
2622 format!(
2623 "+{} x {:.2} y {:.2} scale {:.2} opacity {:.2}{}",
2624 tsec(f64::from(k.at), fps),
2625 k.x,
2626 k.y,
2627 k.scale,
2628 k.opacity,
2629 ease_suffix(k.ease)
2630 )
2631 })
2632 .collect();
2633 if t.keys.len() > SHOWN {
2634 parts.push(format!("(+{} more)", t.keys.len() - SHOWN));
2635 }
2636 format!(" keys {}: {}", t.keys.len(), parts.join(" · "))
2637}
2638
2639/// `title_add {at, duration, text, preset?, size?=80, outline?="thin", boxed?=false, place?="centre", fade_in?=0, fade_out?=0, in_anim?, out_anim?, anim_secs?=0.5, keys?}`.
2640/// `at` and `duration` are times (a bare number is seconds). Fades are frames as
2641/// an integer, or a time string. `keys` animates the title itself ([`title_keys_arg`]).
2642/// The title lands in start order; the reply gives
2643/// the `T<n>` it now holds, and says when titles after it renumber.
2644fn title_add(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
2645 let end = parse::session_end(s);
2646 let start = need(op, "at", fps, end)?;
2647 let frames = need(op, "duration", fps, u32::MAX)?;
2648 let text = req_str(op, "text")?.to_string();
2649 let base = TextStyle { size: 80, outline: Outline::Thin, boxed: false, place: Place::Centre, ..TextStyle::default() };
2650 // A preset is the look the title starts in; the fields given after it win over the preset.
2651 let mut t = Title { start, frames, text, style: base, fade_in: 0, fade_out: 0, in_anim: Default::default(), out_anim: Default::default(), anim_frames: 0, keys: Vec::new() };
2652 if let Some(p) = title_preset_arg(op)? {
2653 t.apply_preset(p, fps);
2654 }
2655 t.style = title_style(op, t.style.clone())?;
2656 t.fade_in = length(op, "fade_in", fps)?.unwrap_or(t.fade_in);
2657 t.fade_out = length(op, "fade_out", fps)?.unwrap_or(t.fade_out);
2658 title_anim_fields(op, &mut t, fps)?;
2659 if let Some(keys) = title_keys_arg(op, fps, t.frames)? {
2660 t.keys = keys;
2661 }
2662 check_title(&t).map_err(|e| format!("title_add: {e}"))?;
2663 let warnings = title_warnings(s, &t);
2664 // The new title is not in the list yet, so every title there is one it may overlap.
2665 let overlaps: String = s.titles().iter().map(|o| crate::tools::see::overlap_line(o, &t, fps)).collect();
2666 let idx = s.add_title(t.clone()).map_err(|e| format!("title_add: {e}"))?;
2667 let mut text = title_line(&title_name(idx), &t, fps);
2668 if idx + 1 < s.titles().len() {
2669 text.push_str(" · titles after it renumber");
2670 }
2671 text.push_str(&warnings);
2672 text.push_str(&overlaps);
2673 Ok(Applied { text, touched: Vec::new() })
2674}
2675
2676/// The title an op names: `"T1"`, `"t1"`, or a 1-based number. Returns its index.
2677fn title_arg(s: &PlaybackSession, op: &Value) -> Result<usize, String> {
2678 let raw = match op.get("title") {
2679 None | Some(Value::Null) => return Err("missing `title`: give a title name such as T1".into()),
2680 Some(Value::Number(x)) => x.to_string(),
2681 Some(Value::String(t)) => t.trim().to_string(),
2682 Some(v) => return Err(format!("`title` must be a name such as T1, got {}", kind_of(v))),
2683 };
2684 let n = s.titles().len();
2685 if n == 0 {
2686 return Err("the timeline has no titles yet; add one with title_add".into());
2687 }
2688 let digits = raw.strip_prefix(|c| c == 'T' || c == 't').unwrap_or(&raw);
2689 match digits.parse::<usize>() {
2690 Ok(k) if (1..=n).contains(&k) => Ok(k - 1),
2691 _ => Err(format!("title {raw} is not on this timeline; the titles are T1..T{n}")),
2692 }
2693}
2694
2695/// `title_set {title, ...}`: any of the `title_add` fields, merged onto the title's
2696/// current settings. Times and fades are as in `title_add`.
2697fn title_set(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
2698 let idx = title_arg(s, op)?;
2699 let old = s.titles()[idx].clone();
2700 let end = parse::session_end(s);
2701 let mut t = old.clone();
2702 if let Some(at) = opt_time(op, "at", fps, end)? {
2703 t.start = at;
2704 }
2705 if let Some(d) = opt_time(op, "duration", fps, u32::MAX)? {
2706 t.frames = d;
2707 }
2708 if !matches!(op.get("text"), None | Some(Value::Null)) {
2709 t.text = req_str(op, "text")?.to_string();
2710 }
2711 // A preset is applied first, so the fields given after it win over its look.
2712 if let Some(p) = title_preset_arg(op)? {
2713 t.apply_preset(p, fps);
2714 }
2715 t.style = title_style(op, t.style.clone())?;
2716 if let Some(f) = length(op, "fade_in", fps)? {
2717 t.fade_in = f;
2718 }
2719 if let Some(f) = length(op, "fade_out", fps)? {
2720 t.fade_out = f;
2721 }
2722 title_anim_fields(op, &mut t, fps)?;
2723 if let Some(keys) = title_keys_arg(op, fps, t.frames)? {
2724 t.keys = keys;
2725 }
2726 let name = title_name(idx);
2727 if t == old {
2728 return Ok(Applied { text: format!("{name} unchanged"), touched: Vec::new() });
2729 }
2730 check_title(&t).map_err(|e| format!("title_set {name}: {e}"))?;
2731 if !s.set_title(idx, t.clone()) {
2732 return Err(format!("title_set {name}: the title did not change"));
2733 }
2734 // A moved title re-sorts: report the name it has now.
2735 let now = s.titles().iter().position(|x| *x == t).unwrap_or(idx);
2736 // Every other title is checked; the title's own entry (at `now`) is skipped.
2737 let overlaps: String = s
2738 .titles()
2739 .iter()
2740 .enumerate()
2741 .filter(|&(i, _)| i != now)
2742 .map(|(_, o)| crate::tools::see::overlap_line(o, &t, fps))
2743 .collect();
2744 let text = title_line(&title_name(now), &t, fps) + &title_warnings(s, &t) + &overlaps;
2745 Ok(Applied { text, touched: Vec::new() })
2746}
2747
2748/// The warnings a title's text earns, each a reply line that starts with a newline (empty when
2749/// the title is fine). Characters neither bundled face draws show as empty boxes, so they are
2750/// named, the first ten distinct ones. A title that wraps to more than six lines, or whose lines
2751/// cover more than 40% of the frame height, fills the frame and is named as long.
2752fn title_warnings(s: &PlaybackSession, t: &Title) -> String {
2753 let lines: Vec<String> = t.text.split('\n').map(str::to_string).collect();
2754 let mut out = String::new();
2755 let missing = missing_glyphs(&lines);
2756 if !missing.is_empty() {
2757 const SHOWN: usize = 10;
2758 let shown: Vec<String> = missing.iter().take(SHOWN).map(char::to_string).collect();
2759 let more = missing.len().saturating_sub(SHOWN);
2760 let more = if more > 0 { format!(" … and {more} more") } else { String::new() };
2761 out.push_str(&format!(
2762 "\n warning: these characters have no glyph in the title font and draw as boxes: {}{more}",
2763 shown.join(" ")
2764 ));
2765 }
2766 let (width, height) = s.resolution();
2767 let (wrapped, share) = layout_share(&t.style, width, height, &lines);
2768 if wrapped > 6 || share > 0.40 {
2769 out.push_str(&format!(
2770 "\n warning: this title is long: it wraps to {wrapped} lines and covers {:.0}% of the frame height, so it fills the frame; shorten it or split it into several titles",
2771 share * 100.0
2772 ));
2773 }
2774 out
2775}
2776
2777/// `title_remove {title}`: takes the title off the picture.
2778fn title_remove(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
2779 let idx = title_arg(s, op)?;
2780 let t = s.titles()[idx].clone();
2781 let name = title_name(idx);
2782 let count = s.titles().len();
2783 if !s.remove_title(idx) {
2784 return Err(format!("title_remove {name}: the title is not on this timeline"));
2785 }
2786 // Titles are named by their start order, so every title after the removed one moves down a number.
2787 let renamed: Vec<String> = (idx..count - 1).map(|j| format!("{} is now {}", title_name(j + 1), title_name(j))).collect();
2788 let renamed = if renamed.is_empty() { String::new() } else { format!("; {}", renamed.join(", ")) };
2789 Ok(Applied { text: format!("removed {}{renamed}", title_line(&name, &t, fps)), touched: Vec::new() })
2790}
2791
2792fn done(text: String, touched: Vec<(Lane, u32)>) -> Applied {
2793 Applied { text, touched }
2794}
2795
2796fn refused(who: &str) -> String {
2797 format!("{who}: the engine refused it (is the clip or lane there, and of the right kind?)")
2798}
2799
2800fn kind_word(kind: LaneKind) -> &'static str {
2801 match kind {
2802 LaneKind::Video => "video",
2803 LaneKind::Audio => "audio",
2804 LaneKind::Subtitle => "subtitle",
2805 }
2806}
2807
2808fn kind_of(v: &Value) -> &'static str {
2809 match v {
2810 Value::Null => "null",
2811 Value::Bool(_) => "a boolean",
2812 Value::Number(_) => "a number",
2813 Value::String(_) => "a string",
2814 Value::Array(_) => "a list",
2815 Value::Object(_) => "an object",
2816 }
2817}
2818
2819/// A required string argument.
2820fn req_str<'a>(op: &'a Value, key: &str) -> Result<&'a str, String> {
2821 match op.get(key) {
2822 None | Some(Value::Null) => Err(format!("missing argument `{key}`")),
2823 Some(Value::String(s)) => Ok(s.as_str()),
2824 Some(v) => Err(format!("`{key}` must be a string, got {}", kind_of(v))),
2825 }
2826}
2827
2828/// An optional number argument; missing or null is `None`.
2829fn num(op: &Value, key: &str) -> Result<Option<f64>, String> {
2830 num_of(op, key)
2831}
2832
2833fn num_of(obj: &Value, key: &str) -> Result<Option<f64>, String> {
2834 match obj.get(key) {
2835 None | Some(Value::Null) => Ok(None),
2836 Some(v) => v
2837 .as_f64()
2838 .filter(|x| x.is_finite())
2839 .map(Some)
2840 .ok_or_else(|| format!("`{key}` must be a number, got {}", kind_of(v))),
2841 }
2842}
2843
2844/// An optional number argument, or `default` when it is missing or null; a
2845/// given value is checked against `lo..=hi`.
2846fn or_default(who: &str, op: &Value, key: &str, default: f32, lo: f32, hi: f32) -> Result<f32, String> {
2847 match num(op, key)? {
2848 Some(v) => ranged(who, key, v, f64::from(lo), f64::from(hi)),
2849 None => Ok(default),
2850 }
2851}
2852
2853fn req_num_in(obj: &Value, key: &str, who: &str, lo: f64, hi: f64) -> Result<f32, String> {
2854 match num_of(obj, key)? {
2855 Some(v) => ranged(who, key, v, lo, hi),
2856 None => Err(format!("{who}: missing `{key}` ({}–{})", fmt(lo), fmt(hi))),
2857 }
2858}
2859
2860fn num_kind(b: &Value) -> Result<Option<BandKind>, String> {
2861 let name = match b.get("kind") {
2862 None | Some(Value::Null) => return Ok(None),
2863 Some(Value::String(s)) => s.as_str(),
2864 Some(v) => return Err(format!("band `kind` must be a string, got {}", kind_of(v))),
2865 };
2866 Ok(Some(match name {
2867 "low_shelf" => BandKind::LowShelf,
2868 "peak" => BandKind::Peak,
2869 "high_shelf" => BandKind::HighShelf,
2870 "low_cut" => BandKind::LowCut,
2871 "high_cut" => BandKind::HighCut,
2872 other => {
2873 return Err(format!(
2874 "band kind `{other}` is not one of low_shelf, peak, high_shelf, low_cut, high_cut"
2875 ))
2876 }
2877 }))
2878}
2879
2880/// A boolean flag; missing or null is `false`.
2881fn flag(op: &Value, key: &str) -> Result<bool, String> {
2882 Ok(flag_opt(op, key)?.unwrap_or(false))
2883}
2884
2885/// An optional boolean; missing or null is `None`.
2886fn flag_opt(op: &Value, key: &str) -> Result<Option<bool>, String> {
2887 match op.get(key) {
2888 None | Some(Value::Null) => Ok(None),
2889 Some(Value::Bool(b)) => Ok(Some(*b)),
2890 Some(v) => Err(format!("`{key}` must be true or false, got {}", kind_of(v))),
2891 }
2892}
2893
2894/// Checks a value against `lo..=hi`, naming the who, the key and the range on refusal.
2895fn ranged(who: &str, key: &str, v: f64, lo: f64, hi: f64) -> Result<f32, String> {
2896 if v < lo || v > hi {
2897 return Err(format!("{who}: {key} {} out of range {}–{}", fmt(v), fmt(lo), fmt(hi)));
2898 }
2899 Ok(v as f32)
2900}
2901
2902/// A bound or value as the refusals print it: plain for the everyday range, scientific
2903/// beyond it so `1e308` is not echoed as three hundred digits.
2904fn fmt(v: f64) -> String {
2905 if v == 0.0 || (v.abs() >= 1e-3 && v.abs() < 1e6) { format!("{v}") } else { format!("{v:e}") }
2906}
2907
2908/// The clip argument, resolved: lane, index, the address as written, and its start frame.
2909fn clip_arg(s: &PlaybackSession, op: &Value) -> Result<(Lane, usize, String, u32), String> {
2910 let raw = req_str(op, "clip")?;
2911 let (lane, idx) = super::edit::clip_addr(s, raw)?;
2912 // Every op that takes a clip changes it (grade, placement, fit, eq, volume, keys), so a
2913 // locked lane refuses here, once, for all of them.
2914 check_unlocked(s, &[lane])?;
2915 let start = start_of(s, lane, idx);
2916 Ok((lane, idx, raw.to_string(), start))
2917}
2918
2919/// The lanes of the take `(lane, idx)` belongs to, the clip's own lane first. Just that lane when
2920/// the clip is not linked. Subtitle lanes hold no take.
2921fn take_lanes_of(s: &PlaybackSession, lane: Lane, idx: usize) -> Vec<Lane> {
2922 let mut out = vec![lane];
2923 let Some(link) = s.lane_clips(lane).get(idx).and_then(|c| c.link) else {
2924 return out;
2925 };
2926 for l in s.lanes() {
2927 if l.kind != LaneKind::Subtitle
2928 && !out.contains(&l)
2929 && s.lane_clips(l).iter().any(|c| c.link == Some(link))
2930 {
2931 out.push(l);
2932 }
2933 }
2934 out
2935}
2936
2937/// The lane argument, resolved and checked to exist: the lane and the text as written.
2938fn lane_arg<'a>(s: &PlaybackSession, op: &'a Value) -> Result<(Lane, &'a str), String> {
2939 let raw = req_str(op, "lane")?;
2940 let lane = parse::lane(raw)?;
2941 if !s.lanes().contains(&lane) {
2942 let names: Vec<String> = s.lanes().into_iter().map(parse::lane_name).collect();
2943 return Err(format!(
2944 "{raw} is not a lane on this timeline; the lanes are {}",
2945 names.join(", ")
2946 ));
2947 }
2948 Ok((lane, raw))
2949}
2950
2951fn start_of(s: &PlaybackSession, lane: Lane, idx: usize) -> u32 {
2952 if lane.kind == LaneKind::Subtitle {
2953 s.sub_lane(lane).get(idx).map_or(0, |c| c.start)
2954 } else {
2955 s.lane_clips(lane).get(idx).map_or(0, |c| c.start)
2956 }
2957}
2958
2959/// Every clip on `lane`, as (lane, start).
2960fn starts_on(s: &PlaybackSession, lane: Lane) -> Vec<(Lane, u32)> {
2961 if lane.kind == LaneKind::Subtitle {
2962 s.sub_lane(lane).iter().map(|c| (lane, c.start)).collect()
2963 } else {
2964 s.lane_clips(lane).iter().map(|c| (lane, c.start)).collect()
2965 }
2966}
2967
2968/// The waveform picture for an audio clip, for a voiceover or any sound with no picture of its
2969/// own: the same span of its file, painted from its sound by the engine, placed on the first free
2970/// video lane at the clip's start (or on a new one). Returns the video lane and start it landed
2971/// on. A clip at a speed other than 1x is refused, since the picture would be the wrong length.
2972// Wired from edit.rs op_visualizer (the owner of the visualizer op) when the clip is on an audio lane.
2973pub(crate) fn place_waveform_for_audio(
2974 s: &mut PlaybackSession,
2975 lane: Lane,
2976 idx: usize,
2977) -> Result<(Lane, u32), String> {
2978 if lane.kind != LaneKind::Audio {
2979 return Err(format!("{} is not an audio lane", parse::lane_name(lane)));
2980 }
2981 let clip = s
2982 .lane_clips(lane)
2983 .get(idx)
2984 .cloned()
2985 .ok_or_else(|| format!("no clip {idx} on {}", parse::lane_name(lane)))?;
2986 if clip.speed != engine::project::Speed::NORMAL || !clip.speed_keys.is_empty() {
2987 return Err(format!(
2988 "{} plays at a speed other than 1x, so a waveform picture would not match its length; set the speed to 1x first",
2989 parse::addr(lane, clip.start)
2990 ));
2991 }
2992 let (path, stream) = {
2993 let src = s
2994 .sources()
2995 .get(clip.source)
2996 .ok_or_else(|| format!("src:{} is not on this timeline", clip.source))?;
2997 (src.path.clone(), src.audio_stream)
2998 };
2999 let start = clip.start;
3000 let placed = s
3001 .place_visualizer(start, &path, stream, clip.in_frame, clip.out_frame, None)
3002 .map_err(|e| format!("waveform picture for {}: {e}", parse::addr(lane, start)))?;
3003 if !placed {
3004 return Err(format!("waveform picture for {}: no room on a video lane", parse::addr(lane, start)));
3005 }
3006 // Where it landed: the video clip this placement made, read back from the timeline.
3007 s.lanes()
3008 .into_iter()
3009 .filter(|l| l.kind == LaneKind::Video)
3010 .find_map(|l| {
3011 s.lane_clips(l)
3012 .iter()
3013 .any(|c| c.start == start && c.visualizer != 0 && c.in_frame == clip.in_frame)
3014 .then_some((l, start))
3015 })
3016 .ok_or_else(|| "the waveform picture was placed but not found on a video lane".to_string())
3017}
3018
3019#[cfg(test)]
3020mod tests {
3021 use super::*;
3022 use serde_json::json;
3023
3024 #[test]
3025 fn waveform_picture_for_an_audio_clip_lands_on_a_video_lane() {
3026 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_tone_48k.wav");
3027 let mut s = PlaybackSession::open(p).expect("open audio-only asset");
3028 let audio = Lane::A1;
3029 let clip = s.lane_clips(audio)[0].clone();
3030 assert!(s.lanes().iter().all(|l| l.kind != LaneKind::Video || s.lane_clips(*l).is_empty()));
3031 let (lane, start) = place_waveform_for_audio(&mut s, audio, 0).expect("placed");
3032 assert_eq!(lane.kind, LaneKind::Video);
3033 assert_eq!(start, clip.start);
3034 let pic = s.lane_clips(lane)[0].clone();
3035 assert_ne!(pic.visualizer, 0, "the picture is a visualizer clip");
3036 assert_eq!(pic.out_frame - pic.in_frame, clip.out_frame - clip.in_frame, "same span of the file");
3037 // The audio clip itself stays a plain clip.
3038 assert_eq!(s.lane_clips(audio)[0].visualizer, 0);
3039 }
3040
3041 fn session() -> PlaybackSession {
3042 engine::ao::set_silent_output();
3043 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
3044 PlaybackSession::open(p).expect("open test asset")
3045 }
3046
3047 fn run(s: &mut PlaybackSession, op: Value) -> Result<Applied, String> {
3048 apply(s, &op, 30.0).expect("the op is one of this module's")
3049 }
3050
3051 fn close(a: f32, b: f32) -> bool {
3052 (a - b).abs() < 1e-4
3053 }
3054
3055 #[test]
3056 fn color_merges_and_resets() {
3057 let mut s = session();
3058 let a = run(&mut s, json!({"op": "color", "clip": "V1#0", "brightness": 0.1})).unwrap();
3059 assert!(a.text.contains("brightness 0.10"), "{}", a.text);
3060 assert_eq!(a.touched, vec![(Lane::V1, s.lane_clips(Lane::V1)[0].start)]);
3061 let a = run(&mut s, json!({"op": "color", "clip": "V1#0", "saturation": 1.2})).unwrap();
3062 assert_eq!(a.text, "color V1#0 → saturation 1.20");
3063 let c = s.color_of(Lane::V1, 0).copied().expect("graded");
3064 assert!(close(c.saturation, 1.2));
3065 assert!(close(c.brightness, 0.1), "earlier brightness kept");
3066 run(&mut s, json!({"op": "color", "clip": "V1#0", "reset": true})).unwrap();
3067 assert!(s.color_of(Lane::V1, 0).is_none());
3068 }
3069
3070 #[test]
3071 fn color_refuses_out_of_range() {
3072 let mut s = session();
3073 let e = run(&mut s, json!({"op": "color", "clip": "V1#0", "saturation": 3.5})).unwrap_err();
3074 assert_eq!(e, "color V1#0: saturation 3.5 out of range 0–2");
3075 }
3076
3077 #[test]
3078 fn transform_sets_and_resets() {
3079 let mut s = session();
3080 run(
3081 &mut s,
3082 json!({"op": "transform", "clip": "V1#0", "x": 0.25, "scale": 1.5, "crop": [0.1, 0, 0, 0.2]}),
3083 )
3084 .unwrap();
3085 let t = s.transform_of(Lane::V1, 0).copied().expect("placed");
3086 assert!(close(t.pos_x, 0.25) && close(t.scale, 1.5));
3087 assert!(close(t.crop_l, 0.1) && close(t.crop_b, 0.2));
3088 assert!(run(&mut s, json!({"op": "transform", "clip": "V1#0", "crop": [0.6, 0, 0, 0]}))
3089 .unwrap_err()
3090 .contains("out of range 0–0.5"));
3091 run(&mut s, json!({"op": "transform", "clip": "V1#0", "reset": true})).unwrap();
3092 assert!(s.transform_of(Lane::V1, 0).is_none());
3093 }
3094
3095 #[test]
3096 fn transform_corner_places_by_the_clips_own_size() {
3097 let mut s = session();
3098 let (cw, ch) = s.resolution();
3099 let (w, h) = engine::probe_media(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4").as_path())
3100 .video
3101 .map(|v| (v.width, v.height))
3102 .expect("video size");
3103 run(&mut s, json!({"op": "transform", "clip": "V1#0", "scale": 0.3, "corner": "top-right", "margin": 32})).unwrap();
3104 let t = s.transform_of(Lane::V1, 0).copied().expect("placed");
3105 let (x, y) = engine::transform::corner_offset(engine::transform::Corner::TopRight, 0.3, 32.0 / cw as f32, (w, h), (cw, ch));
3106 assert!(close(t.pos_x, x) && close(t.pos_y, y), "{} {} vs {x} {y}", t.pos_x, t.pos_y);
3107 assert!(t.pos_x > 0.0 && t.pos_y < 0.0, "top-right is +x, -y");
3108 assert!(close(t.scale, 0.3), "the corner keeps the scale it was given");
3109 // Corner alone keeps the scale already set, and the default margin is 32 px.
3110 let r = run(&mut s, json!({"op": "transform", "clip": "V1#0", "corner": "bottom-left"})).unwrap();
3111 let t = s.transform_of(Lane::V1, 0).copied().expect("placed");
3112 let (x, y) = engine::transform::corner_offset(engine::transform::Corner::BottomLeft, 0.3, 32.0 / cw as f32, (w, h), (cw, ch));
3113 assert!(close(t.pos_x, x) && close(t.pos_y, y));
3114 assert!(r.text.contains("corner bottom-left, margin 32 px"), "{}", r.text);
3115 // Centre is the origin.
3116 run(&mut s, json!({"op": "transform", "clip": "V1#0", "corner": "centre"})).unwrap();
3117 let t = s.transform_of(Lane::V1, 0).copied().expect("placed");
3118 assert!(close(t.pos_x, 0.0) && close(t.pos_y, 0.0));
3119 }
3120
3121 #[test]
3122 fn transform_corner_measures_a_4_3_source_by_its_own_size() {
3123 // A 4:3 clip on the project canvas fits by height, so its corner is not the
3124 // width-fill answer; the op must measure the file, not assume a 16:9 picture.
3125 engine::ao::set_silent_output();
3126 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_vui_h264.mp4");
3127 let mut s = PlaybackSession::open(p).expect("open 4:3 asset");
3128 let (cw, ch) = s.resolution();
3129 run(&mut s, json!({"op": "transform", "clip": "V1#0", "scale": 0.3, "corner": "bottom-right"})).unwrap();
3130 let t = s.transform_of(Lane::V1, 0).copied().expect("placed");
3131 let (x, y) = engine::transform::corner_offset(engine::transform::Corner::BottomRight, 0.3, 32.0 / cw as f32, (640, 480), (cw, ch));
3132 assert!(close(t.pos_x, x) && close(t.pos_y, y), "{} {} vs {x} {y}", t.pos_x, t.pos_y);
3133 }
3134
3135 #[test]
3136 fn transform_corner_refuses_x_y_and_bad_names_plainly() {
3137 let mut s = session();
3138 let e = run(&mut s, json!({"op": "transform", "clip": "V1#0", "corner": "top-left", "x": 0.1})).unwrap_err();
3139 assert!(e.contains("corner sets x and y itself"), "{e}");
3140 let e = run(&mut s, json!({"op": "transform", "clip": "V1#0", "corner": "top-left", "y": 0.1})).unwrap_err();
3141 assert!(e.contains("corner sets x and y itself"), "{e}");
3142 let e = run(&mut s, json!({"op": "transform", "clip": "V1#0", "corner": "middle"})).unwrap_err();
3143 assert!(e.contains("centre, top-left, top-right, bottom-left or bottom-right"), "{e}");
3144 let e = run(&mut s, json!({"op": "transform", "clip": "V1#0", "margin": 10})).unwrap_err();
3145 assert!(e.contains("margin"), "{e}");
3146 // Refused ops leave the clip alone.
3147 assert!(s.transform_of(Lane::V1, 0).is_none());
3148 }
3149
3150 #[test]
3151 fn transform_opacity_is_0_to_1_and_shown() {
3152 let mut s = session();
3153 let reply = run(
3154 &mut s,
3155 json!({"op": "transform", "clip": "V1#0", "opacity": 0.5}),
3156 )
3157 .unwrap();
3158 let t = s.transform_of(Lane::V1, 0).copied().expect("placed");
3159 assert!(close(t.opacity, 0.5), "opacity {}", t.opacity);
3160 assert!(reply.text.contains("opacity 0.50"), "the reply shows it: {}", reply.text);
3161
3162 // Both ends are allowed; anything past them is refused by name.
3163 run(&mut s, json!({"op": "transform", "clip": "V1#0", "opacity": 0})).unwrap();
3164 assert!(close(s.transform_of(Lane::V1, 0).unwrap().opacity, 0.0));
3165 let e = run(&mut s, json!({"op": "transform", "clip": "V1#0", "opacity": 1.5}))
3166 .unwrap_err();
3167 assert_eq!(e, "transform V1#0: opacity 1.5 out of range 0–1");
3168 let e = run(&mut s, json!({"op": "transform", "clip": "V1#0", "opacity": -0.1}))
3169 .unwrap_err();
3170 assert!(e.contains("opacity -0.1 out of range"), "{e}");
3171 // A refused value leaves the clip as it was.
3172 assert!(close(s.transform_of(Lane::V1, 0).unwrap().opacity, 0.0));
3173 }
3174
3175 #[test]
3176 fn fit_sets_policy() {
3177 let mut s = session();
3178 let a = run(&mut s, json!({"op": "fit", "clip": "V1#0", "policy": "fill"})).unwrap();
3179 assert_eq!(a.text, "fit V1#0 → fill");
3180 assert_eq!(s.fit_of(Lane::V1, 0), FitPolicy::Fill);
3181 assert!(run(&mut s, json!({"op": "fit", "clip": "V1#0", "policy": "zoom"})).is_err());
3182 }
3183
3184 #[test]
3185 fn eq_sets_and_resets() {
3186 let mut s = session();
3187 run(
3188 &mut s,
3189 json!({"op": "eq", "clip": "A1#0", "bands": [{"f": 1000, "db": 3, "q": 1, "kind": "peak"}]}),
3190 )
3191 .unwrap();
3192 let eq = s.eq_of(Lane::new(LaneKind::Audio, 0), 0).expect("equalized");
3193 assert_eq!(eq.bands.len(), 1);
3194 assert!(close(eq.bands[0].gain_db, 3.0));
3195 assert_eq!(eq.bands[0].kind, BandKind::Peak);
3196 let too_many: Vec<Value> = (0..=engine::eq::MAX_BANDS).map(|_| json!({"f": 100, "db": 0})).collect();
3197 assert!(run(&mut s, json!({"op": "eq", "clip": "A1#0", "bands": too_many}))
3198 .unwrap_err()
3199 .contains("at most 20"));
3200 run(&mut s, json!({"op": "eq", "clip": "A1#0", "reset": true})).unwrap();
3201 assert!(s.eq_of(Lane::new(LaneKind::Audio, 0), 0).is_none());
3202 }
3203
3204 #[test]
3205 fn gain_sets_relative_clamps_refuses_and_undoes() {
3206 let mut s = session();
3207 let a1 = Lane::new(LaneKind::Audio, 0);
3208 let r = run(&mut s, json!({"op": "gain", "clip": "A1#0", "db": -6})).unwrap();
3209 assert_eq!(r.text, "gain A1#0 → -6.0 dB");
3210 assert!(close(s.clip_gain_of(a1, 0).unwrap(), -6.0));
3211 let r = run(&mut s, json!({"op": "gain", "clip": "A1#0", "add_db": -3})).unwrap();
3212 assert_eq!(r.text, "gain A1#0 → -9.0 dB");
3213 let r = run(&mut s, json!({"op": "gain", "clip": "A1#0", "add_db": 50})).unwrap();
3214 assert_eq!(r.text, "gain A1#0 → 24.0 dB", "relative steps clamp to the range");
3215 assert!(run(&mut s, json!({"op": "gain", "clip": "A1#0", "db": 30})).unwrap_err().contains("out of range"));
3216 assert!(run(&mut s, json!({"op": "gain", "clip": "A1#0"})).unwrap_err().contains("missing argument"));
3217 assert!(run(&mut s, json!({"op": "gain", "clip": "A1#0", "db": 1, "add_db": 1})).unwrap_err().contains("not both"));
3218 let r = run(&mut s, json!({"op": "gain", "clip": "A1#0", "db": 24})).unwrap();
3219 assert!(r.text.contains("already 24.0 dB"), "{}", r.text);
3220 let err = run(&mut s, json!({"op": "gain", "clip": "V1#0", "db": -3})).unwrap_err();
3221 assert!(err.contains("video lane"), "{err}");
3222 // three applied changes, three undo steps: back to unity
3223 for _ in 0..3 {
3224 assert!(s.undo());
3225 }
3226 assert!(close(s.clip_gain_of(a1, 0).unwrap(), 0.0));
3227 }
3228
3229 #[test]
3230 fn pan_and_lane_pan_set_clamp_refuse_and_undo() {
3231 let mut s = session();
3232 let a1 = Lane::new(LaneKind::Audio, 0);
3233 let r = run(&mut s, json!({"op": "pan", "clip": "A1#0", "pan": -0.5})).unwrap();
3234 assert!(r.text.contains("-0.50"), "{}", r.text);
3235 assert_eq!(s.clip_pan_of(a1, 0), Some(-0.5));
3236 let r = run(&mut s, json!({"op": "pan", "clip": "A1#0", "pan": -0.5})).unwrap();
3237 assert!(r.text.contains("already"), "{}", r.text);
3238 assert!(run(&mut s, json!({"op": "pan", "clip": "A1#0", "pan": 1.5})).unwrap_err().contains("out of range"));
3239 assert!(run(&mut s, json!({"op": "pan", "clip": "A1#0"})).unwrap_err().contains("missing argument `pan`"));
3240 assert!(run(&mut s, json!({"op": "pan", "clip": "V1#0", "pan": 0.2})).unwrap_err().contains("video lane"));
3241 run(&mut s, json!({"op": "lane_pan", "lane": "A1", "pan": 1})).unwrap();
3242 assert_eq!(s.lane_pan(a1), 1.0);
3243 assert!(run(&mut s, json!({"op": "lane_pan", "lane": "V1", "pan": 1})).is_err());
3244 assert!(s.undo());
3245 assert_eq!(s.lane_pan(a1), 0.0);
3246 assert!(s.undo());
3247 assert_eq!(s.clip_pan_of(a1, 0), Some(0.0));
3248 }
3249
3250 #[test]
3251 fn lane_name_and_deinterlace_ops() {
3252 let mut s = session();
3253 let v1 = Lane::new(LaneKind::Video, 0);
3254 let r = run(&mut s, json!({"op": "lane_name", "lane": "V1", "name": "Interview"})).unwrap();
3255 assert_eq!(r.text, "lane_name V1 → \"Interview\"");
3256 assert_eq!(s.lane_name(v1), Some("Interview"));
3257 assert!(run(&mut s, json!({"op": "lane_name", "lane": "V1", "name": "x".repeat(41)})).unwrap_err().contains("at most 40"));
3258 assert!(run(&mut s, json!({"op": "lane_name", "lane": "V1"})).unwrap_err().contains("give name"));
3259 assert!(run(&mut s, json!({"op": "lane_name", "lane": "V9", "name": "a"})).is_err());
3260 // ops still address by position, never by the name
3261 assert!(run(&mut s, json!({"op": "lane_flags", "lane": "Interview", "hidden": true})).is_err());
3262 let r = run(&mut s, json!({"op": "lane_name", "lane": "V1", "name": ""})).unwrap();
3263 assert!(r.text.contains("name cleared"), "{}", r.text);
3264 assert!(s.undo());
3265 assert_eq!(s.lane_name(v1), Some("Interview"));
3266 run(&mut s, json!({"op": "lane_flags", "lane": "V1", "locked": true})).unwrap();
3267 assert!(run(&mut s, json!({"op": "lane_name", "lane": "V1", "name": "b"})).unwrap_err().contains("locked"));
3268 run(&mut s, json!({"op": "lane_flags", "lane": "V1", "locked": false})).unwrap();
3269
3270 use engine::project::Deinterlace;
3271 let r = run(&mut s, json!({"op": "deinterlace", "clip": "V1#0", "mode": "field"})).unwrap();
3272 assert_eq!(r.text, "deinterlace V1#0 → field");
3273 assert_eq!(s.deinterlace_of(v1, 0), Deinterlace::Field);
3274 let r = run(&mut s, json!({"op": "deinterlace", "clip": "V1#0", "mode": "field"})).unwrap();
3275 assert!(r.text.contains("unchanged"), "{}", r.text);
3276 assert!(run(&mut s, json!({"op": "deinterlace", "clip": "V1#0", "mode": "weave"})).unwrap_err().contains("frame, field or off"));
3277 assert!(run(&mut s, json!({"op": "deinterlace", "clip": "A1#0", "mode": "off"})).is_err());
3278 assert!(s.undo());
3279 assert_eq!(s.deinterlace_of(v1, 0), Deinterlace::Frame);
3280 }
3281
3282 #[test]
3283 fn lane_gain_and_limiter() {
3284 let mut s = session();
3285 let a1 = Lane::new(LaneKind::Audio, 0);
3286 run(&mut s, json!({"op": "lane_gain", "lane": "A1", "db": -6})).unwrap();
3287 assert!(close(s.lane_gain_db(a1), -6.0));
3288 assert!(run(&mut s, json!({"op": "lane_gain", "lane": "A1", "db": 20}))
3289 .unwrap_err()
3290 .contains("out of range -60–12"));
3291 run(&mut s, json!({"op": "limiter", "on": false, "ceiling_db": -3})).unwrap();
3292 let l = s.limiter();
3293 assert!(!l.on && close(l.ceiling_db, -3.0));
3294 assert!(run(&mut s, json!({"op": "limiter", "ceiling_db": 2}))
3295 .unwrap_err()
3296 .contains("out of range -24–0"));
3297 }
3298
3299 #[test]
3300 fn lane_move_to_a_number_moves_that_lane_and_the_reply_says_where() {
3301 let mut s = session();
3302 run(&mut s, json!({"op": "lane_add", "kind": "video"})).unwrap();
3303 let v1 = Lane::new(LaneKind::Video, 0);
3304 let v2 = Lane::new(LaneKind::Video, 1);
3305 // Mark V2 so the test can tell which lane ended up at position 1.
3306 run(&mut s, json!({"op": "lane_flags", "lane": "V2", "hidden": true})).unwrap();
3307 assert!(s.lane_hidden(v2) && !s.lane_hidden(v1));
3308 // The number form, and a whole number written as a float: both are `to:1`.
3309 let r = run(&mut s, json!({"op": "lane_move", "lane": "V2", "to": 1})).unwrap();
3310 assert!(r.text.contains("(position 1)"), "{}", r.text);
3311 assert_eq!(s.lanes()[0], v1, "the lane at position 1 is the first video lane again");
3312 assert!(s.lane_hidden(v1), "the moved lane (the hidden one) is now at position 1");
3313 assert!(!s.lane_hidden(v2));
3314 // Already there: a true no-op reply, not a second move.
3315 let again = run(&mut s, json!({"op": "lane_move", "lane": "V1", "to": 1.0})).unwrap();
3316 assert!(again.text.contains("already at position 1"), "{}", again.text);
3317 assert!(run(&mut s, json!({"op": "lane_move", "lane": "V1", "to": 1.5}))
3318 .unwrap_err()
3319 .contains("out of range"));
3320 }
3321
3322 #[test]
3323 fn lanes_add_move_remove_and_flags() {
3324 let mut s = session();
3325 let before = s.lanes().len();
3326 let added = run(&mut s, json!({"op": "lane_add", "kind": "video"})).unwrap();
3327 assert_eq!(s.lanes().len(), before + 1);
3328 assert!(added.text.contains("V2"), "{}", added.text);
3329
3330 run(&mut s, json!({"op": "lane_move", "lane": "V2", "to": 1})).unwrap();
3331 assert_eq!(s.lanes()[0].kind, LaneKind::Video);
3332 assert_eq!(s.lanes()[0].ord, 0);
3333 assert!(run(&mut s, json!({"op": "lane_move", "lane": "V1", "to": 99}))
3334 .unwrap_err()
3335 .contains("out of range"));
3336
3337 // The empty video lane is now V1 at position 1; take it off again.
3338 run(&mut s, json!({"op": "lane_remove", "lane": "V1"})).unwrap();
3339 assert_eq!(s.lanes().len(), before);
3340 let a1 = Lane::new(LaneKind::Audio, 0);
3341 run(&mut s, json!({"op": "lane_flags", "lane": "A1", "muted": true, "locked": true})).unwrap();
3342 assert!(s.lane_muted(a1));
3343 assert!(s.lane_locked(a1));
3344 assert!(run(&mut s, json!({"op": "lane_flags", "lane": "A1", "hidden": true}))
3345 .unwrap_err()
3346 .contains("hidden does not apply to audio lanes"));
3347 }
3348
3349 #[test]
3350 fn group_and_ungroup() {
3351 let mut s = session();
3352 let a = run(&mut s, json!({"op": "group", "clips": ["V1#0", "A1#0"]})).unwrap();
3353 assert_eq!(a.touched.len(), 2);
3354 run(&mut s, json!({"op": "ungroup", "clip": "V1#0"})).unwrap();
3355 }
3356
3357 /// Grouping a take's picture with a loose clip on V2 and then ungrouping the
3358 /// picture leaves the take (V1 with its sound on A1) linked: the loose clip
3359 /// is the only half that comes apart.
3360 #[test]
3361 fn ungroup_after_grouping_a_take_member_keeps_the_take() {
3362 let mut s = session();
3363 run(&mut s, json!({"op": "lane_add", "kind": "video"})).unwrap();
3364 let v2 = Lane::new(LaneKind::Video, 1);
3365 let mut loose = s.lane_clips(Lane::V1)[0].clone();
3366 loose.link = None;
3367 // A later start than the take: a loose copy at the same frames would be a third half of it.
3368 assert!(s.place_at(v2, 1.0, loose));
3369 run(&mut s, json!({"op": "group", "clips": ["V1#0", "V2#0"]})).unwrap();
3370 assert_eq!(s.lane_clips(Lane::V1)[0].link, s.lane_clips(v2)[0].link, "one group");
3371 run(&mut s, json!({"op": "ungroup", "clip": "V1#0"})).unwrap();
3372 let v1_link = s.lane_clips(Lane::V1)[0].link;
3373 assert!(v1_link.is_some());
3374 assert_eq!(v1_link, s.lane_clips(Lane::A1)[0].link, "the take is still linked");
3375 assert_ne!(s.lane_clips(v2)[0].link, v1_link, "only the loose clip came apart");
3376 }
3377
3378 #[test]
3379 fn subtitles_import_adds_tracks() {
3380 let mut s = session();
3381 let srt = Path::new(env!("CARGO_MANIFEST_DIR")).join("../engine/tests/data/test_subs.srt");
3382 let a = run(&mut s, json!({"op": "subtitles_import", "path": srt.to_str().unwrap()})).unwrap();
3383 assert!(a.text.starts_with("imported 1 track (#0, "), "{}", a.text);
3384 assert!(a.text.contains("not on the timeline yet"), "{}", a.text);
3385 assert!(a.text.contains("captions_place {track:0}"), "{}", a.text);
3386 assert!(a.touched.is_empty());
3387 }
3388
3389 #[test]
3390 fn subtitles_import_takes_the_language_from_the_file_name_or_lang() {
3391 let td = crate::testutil::TestDir::new("r30b_fx_lang");
3392 let body = "1\n00:00:01,000 --> 00:00:02,000\nBonjour\n";
3393 let fra = td.path().join("fra.srt");
3394 std::fs::write(&fra, body).unwrap();
3395 let mut s = session();
3396 let a = run(&mut s, json!({"op": "subtitles_import", "path": fra.to_str().unwrap()})).unwrap();
3397 assert!(a.text.contains(" · lang fra, from the file name"), "{}", a.text);
3398 let mut s = session();
3399 let a = run(&mut s, json!({"op": "subtitles_import", "path": fra.to_str().unwrap(), "lang": "deu"})).unwrap();
3400 assert!(a.text.contains(" · lang deu, as given"), "{}", a.text);
3401 assert!(!a.text.contains("lang fra"), "{}", a.text);
3402 }
3403
3404 #[test]
3405 fn subtitles_import_names_the_cues_it_skipped() {
3406 let td = crate::testutil::TestDir::new("f17_skipped_cues");
3407 let srt = td.path().join("bad.srt");
3408 std::fs::write(
3409 &srt,
3410 "1\n00:00:01,000 --> 00:00:02,000\nOne\n\n\
3411 2\n00:00:08,500 --> 00:00:08,000\nReversed\n\n\
3412 3\n00:00:06,000 --> 00:00:07,000\nFive\n",
3413 )
3414 .unwrap();
3415 let mut s = session();
3416 let a = run(&mut s, json!({"op": "subtitles_import", "path": srt.to_str().unwrap()})).unwrap();
3417 assert!(a.text.contains("imported 1 track"), "{}", a.text);
3418 assert!(
3419 a.text.ends_with("skipped 1 cue (line 6), not imported: end before start"),
3420 "{}",
3421 a.text
3422 );
3423 }
3424
3425 #[test]
3426 fn several_skipped_cues_are_counted_as_cues_and_named_by_line() {
3427 let td = crate::testutil::TestDir::new("r27_skipped_cues");
3428 let srt = td.path().join("bad2.srt");
3429 std::fs::write(
3430 &srt,
3431 "1\n00:00:01,000 --> 00:00:02,000\nOne\n\n\
3432 2\n00:00:08,500 --> 00:00:08,000\nReversed\n\n\
3433 3\n00:00:07,000 --> 00:00:06,000\nAlso reversed\n\n\
3434 4\n00:00:09,000 --> 00:00:10,000\nFour\n",
3435 )
3436 .unwrap();
3437 let mut s = session();
3438 let a = run(&mut s, json!({"op": "subtitles_import", "path": srt.to_str().unwrap()})).unwrap();
3439 assert!(a.text.ends_with("skipped 2 cues (lines 6, 10), not imported: end before start; end before start"), "{}", a.text);
3440 }
3441
3442 /// A title over another in the same place is named as overlapping, by the window they share;
3443 /// a title in another place is not.
3444 #[test]
3445 fn a_title_overlapping_another_in_the_same_place_is_named() {
3446 let mut srv = open_server();
3447 let r = titles_ed(&mut srv, json!([{ "op": "title_add", "at": "0s", "duration": "3s", "text": "one", "place": "centre" }]));
3448 assert!(!r.is_error, "{}", r.text);
3449 assert!(!r.text.contains("overlap"), "{}", r.text);
3450 let r = titles_ed(&mut srv, json!([{ "op": "title_add", "at": "1s", "duration": "2s", "text": "two", "place": "centre" }]));
3451 assert!(!r.is_error, "{}", r.text);
3452 assert!(r.text.contains("warning: two titles overlap at centre"), "{}", r.text);
3453 let r = titles_ed(&mut srv, json!([{ "op": "title_add", "at": "1s", "duration": "2s", "text": "three", "place": "bottom" }]));
3454 assert!(!r.is_error, "{}", r.text);
3455 assert!(!r.text.contains("overlap"), "{}", r.text);
3456 // title_set on the first title skips its own entry, and names the second (overlapping) one.
3457 let r = titles_ed(&mut srv, json!([{ "op": "title_set", "title": "T1", "duration": "4s" }]));
3458 assert!(!r.is_error, "{}", r.text);
3459 assert!(r.text.matches("two titles overlap").count() >= 1, "{}", r.text);
3460 assert!(!r.text.contains("T1 overlap"), "{}", r.text);
3461 }
3462
3463 #[test]
3464 fn a_second_key_on_a_lane_adds_a_duck() {
3465 let mut s = session();
3466 for _ in 0..3 {
3467 run(&mut s, json!({"op": "lane_add", "kind": "audio"})).unwrap();
3468 }
3469 let a4 = Lane::new(LaneKind::Audio, 3);
3470 let first = run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2"})).unwrap();
3471 assert!(first.text.contains("now ducked under A2 (-12 dB"), "{}", first.text);
3472 let second = run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A3", "depth_db": -6})).unwrap();
3473 assert!(
3474 second.text.contains("now ducked under A2 (-12 dB when over -40 dBFS), A3 (-6 dB"),
3475 "{}",
3476 second.text
3477 );
3478 let unders: Vec<usize> = s.lane_duck_list(a4).iter().map(|d| d.under).collect();
3479 assert_eq!(unders, vec![1, 2], "both ducks stand, in the order set");
3480 // The same key again replaces its duck; the other stays.
3481 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2", "depth_db": -20})).unwrap();
3482 let d = s.lane_duck_list(a4);
3483 assert_eq!(d.len(), 2);
3484 assert!(close(d[0].depth_db, -20.0) && d[1].under == 2, "replaced in place, the other kept");
3485 }
3486
3487 #[test]
3488 fn duck_off_removes_only_its_key_and_off_alone_clears_all() {
3489 let mut s = session();
3490 for _ in 0..3 {
3491 run(&mut s, json!({"op": "lane_add", "kind": "audio"})).unwrap();
3492 }
3493 let a4 = Lane::new(LaneKind::Audio, 3);
3494 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2"})).unwrap();
3495 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A3"})).unwrap();
3496 let one = run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2", "off": true})).unwrap();
3497 assert!(one.text.contains("A4 under A2 → removed; A4 now ducked under A3"), "{}", one.text);
3498 assert_eq!(s.lane_duck_list(a4).iter().map(|d| d.under).collect::<Vec<_>>(), vec![2]);
3499 assert_eq!(
3500 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2", "off": true})).unwrap().text,
3501 "duck A4 under A2 → already off"
3502 );
3503 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A1"})).unwrap();
3504 let all = run(&mut s, json!({"op": "duck", "lane": "A4", "off": true})).unwrap();
3505 assert!(all.text.contains("all 2 ducks removed (A3, A1)"), "{}", all.text);
3506 assert!(s.lane_duck_list(a4).is_empty());
3507 assert_eq!(run(&mut s, json!({"op": "duck", "lane": "A4", "off": true})).unwrap().text, "duck A4 → already off");
3508 }
3509
3510 #[test]
3511 fn two_ducks_undo_as_one_step_each() {
3512 let mut s = session();
3513 for _ in 0..3 {
3514 run(&mut s, json!({"op": "lane_add", "kind": "audio"})).unwrap();
3515 }
3516 let a4 = Lane::new(LaneKind::Audio, 3);
3517 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2"})).unwrap();
3518 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A3"})).unwrap();
3519 run(&mut s, json!({"op": "duck", "lane": "A4", "under": "A2", "off": true})).unwrap();
3520 assert_eq!(s.lane_duck_list(a4).len(), 1);
3521 assert!(s.undo());
3522 assert_eq!(s.lane_duck_list(a4).len(), 2, "undo restores the removed key");
3523 assert!(s.undo());
3524 assert_eq!(s.lane_duck_list(a4).len(), 1, "undo takes the second key off");
3525 }
3526
3527 #[test]
3528 fn duck_sets_defaults_and_custom_values() {
3529 let mut s = session();
3530 run(&mut s, json!({"op": "lane_add", "kind": "audio"})).unwrap();
3531 let a2 = Lane::new(LaneKind::Audio, 1);
3532 let a = run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1"})).unwrap();
3533 assert_eq!(
3534 a.text,
3535 "duck A2 under A1: -12 dB when A1 > -40 dBFS (attack 80 ms, release 400 ms); A2 now ducked under A1 (-12 dB when over -40 dBFS)"
3536 );
3537 let d = s.lane_duck(a2).expect("ducked");
3538 assert_eq!(d.under, 0);
3539 assert!(close(d.depth_db, -12.0) && close(d.threshold_db, -40.0));
3540 assert!(close(d.attack_ms, 80.0) && close(d.release_ms, 400.0));
3541 assert_eq!(run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1"})).unwrap().text, "duck A2 → already set");
3542 run(
3543 &mut s,
3544 json!({"op": "duck", "lane": "A2", "under": "A1", "depth_db": -6, "threshold_db": -30, "attack_ms": 10, "release_ms": 900}),
3545 )
3546 .unwrap();
3547 let d = s.lane_duck(a2).expect("re-ducked");
3548 assert!(close(d.depth_db, -6.0) && close(d.threshold_db, -30.0));
3549 assert!(close(d.attack_ms, 10.0) && close(d.release_ms, 900.0));
3550
3551 run(&mut s, json!({"op": "duck", "lane": "A2", "off": true})).unwrap();
3552 assert!(s.lane_duck(a2).is_none(), "off removes the duck");
3553 assert_eq!(run(&mut s, json!({"op": "duck", "lane": "A2", "off": true})).unwrap().text, "duck A2 → already off");
3554 }
3555
3556 #[test]
3557 fn duck_refusals_name_the_rule() {
3558 let mut s = session();
3559 run(&mut s, json!({"op": "lane_add", "kind": "audio"})).unwrap();
3560 let self_key = run(&mut s, json!({"op": "duck", "lane": "A1", "under": "A1"})).unwrap_err();
3561 assert!(self_key.contains("not its own key"), "{self_key}");
3562 let video = run(&mut s, json!({"op": "duck", "lane": "V1", "under": "A1"})).unwrap_err();
3563 assert!(video.contains("only audio lanes duck"), "{video}");
3564 let no_key = run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A9"})).unwrap_err();
3565 assert!(no_key.contains("A9 is not a lane"), "{no_key}");
3566 let no_under = run(&mut s, json!({"op": "duck", "lane": "A2"})).unwrap_err();
3567 assert!(no_under.contains("give under"), "{no_under}");
3568 let deep = run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1", "depth_db": -50})).unwrap_err();
3569 assert!(deep.contains("depth_db -50 out of range -40–0"), "{deep}");
3570 let slow = run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1", "attack_ms": 5000})).unwrap_err();
3571 assert!(slow.contains("attack_ms 5000 out of range 1–2000"), "{slow}");
3572 let loud = run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1", "threshold_db": 3})).unwrap_err();
3573 assert!(loud.contains("threshold_db 3 out of range -90–0"), "{loud}");
3574 assert!(s.lane_duck(Lane::new(LaneKind::Audio, 1)).is_none(), "no refusal changed the lane");
3575 }
3576
3577 #[test]
3578 fn duck_refuses_a_locked_lane_and_undoes() {
3579 let mut s = session();
3580 run(&mut s, json!({"op": "lane_add", "kind": "audio"})).unwrap();
3581 let a2 = Lane::new(LaneKind::Audio, 1);
3582 run(&mut s, json!({"op": "lane_flags", "lane": "A2", "locked": true})).unwrap();
3583 let e = run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1"})).unwrap_err();
3584 assert!(e.contains("lane A2 is locked"), "{e}");
3585 run(&mut s, json!({"op": "lane_flags", "lane": "A2", "locked": false})).unwrap();
3586 run(&mut s, json!({"op": "duck", "lane": "A2", "under": "A1"})).unwrap();
3587 assert!(s.lane_duck(a2).is_some());
3588 assert!(s.undo(), "the duck is one undo step");
3589 assert!(s.lane_duck(a2).is_none(), "undo takes the duck off");
3590 }
3591
3592 #[test]
3593 fn every_op_that_changes_a_locked_lane_refuses_and_names_it() {
3594 let mut s = session();
3595 run(&mut s, json!({"op": "lane_flags", "lane": "V1", "locked": true})).unwrap();
3596 let clips_before = s.lane_clips(Lane::V1).len();
3597 let on_v1 = [
3598 json!({"op": "color", "clip": "V1#0", "brightness": 0.1}),
3599 json!({"op": "color", "clip": "V1#0", "reset": true}),
3600 json!({"op": "transform", "clip": "V1#0", "x": 0.1}),
3601 json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "0s", "scale": 1}]}),
3602 json!({"op": "fit", "clip": "V1#0", "policy": "fill"}),
3603 json!({"op": "eq", "clip": "V1#0", "reset": true}),
3604 json!({"op": "ungroup", "clip": "V1#0"}),
3605 json!({"op": "group", "clips": ["V1#0", "A1#0"]}),
3606 json!({"op": "lane_remove", "lane": "V1"}),
3607 json!({"op": "lane_flags", "lane": "V1", "hidden": true}),
3608 json!({"op": "lane_gain", "lane": "V1", "db": 3}),
3609 ];
3610 for op in on_v1 {
3611 let e = run(&mut s, op.clone()).unwrap_err();
3612 assert!(e.contains("lane V1 is locked") && e.contains("lane_flags"), "{op}: {e}");
3613 }
3614 assert!(s.color_of(Lane::V1, 0).is_none(), "no refused op changed the clip");
3615 assert_eq!(s.lane_clips(Lane::V1).len(), clips_before);
3616 assert!(s.lanes().contains(&Lane::V1));
3617 // Unlocking is the way out, and a locked lane's own lock may still be changed.
3618 run(&mut s, json!({"op": "lane_flags", "lane": "V1", "locked": false})).unwrap();
3619 run(&mut s, json!({"op": "color", "clip": "V1#0", "brightness": 0.1})).unwrap();
3620 run(&mut s, json!({"op": "lane_flags", "lane": "V1", "locked": true})).unwrap();
3621 // Audio: a volume edit on a locked audio lane refuses, and so does ungrouping a take
3622 // whose audio partner is locked.
3623 run(&mut s, json!({"op": "lane_flags", "lane": "V1", "locked": false})).unwrap();
3624 run(&mut s, json!({"op": "lane_flags", "lane": "A1", "locked": true})).unwrap();
3625 for op in [
3626 json!({"op": "gain", "clip": "A1#0", "db": -3}),
3627 json!({"op": "gain_keys", "clip": "A1#0", "keys": [["0s", -3]]}),
3628 json!({"op": "ungroup", "clip": "V1#0"}),
3629 ] {
3630 let e = run(&mut s, op.clone()).unwrap_err();
3631 assert!(e.contains("lane A1 is locked"), "{op}: {e}");
3632 }
3633 }
3634
3635 #[test]
3636 fn unknown_op_is_not_ours() {
3637 let mut s = session();
3638 assert!(apply(&mut s, &json!({"op": "split", "at": "5s"}), 30.0).is_none());
3639 assert!(apply(&mut s, &json!({"clip": "V1#0"}), 30.0).is_none());
3640 }
3641
3642 fn audio_clip(srv: &crate::server::Server) -> (Lane, Clip) {
3643 let s = srv.session.as_ref().unwrap();
3644 let a1 = Lane::new(LaneKind::Audio, 0);
3645 (a1, s.lane_clips(a1)[0].clone())
3646 }
3647
3648 /// The test asset is 5 s long. A1 moved to 2 s and trimmed in to 3 s starts at
3649 /// 3 s on the timeline with its in point 1 s into the source, so the envelope's
3650 /// timeline and source frames differ and a conversion mistake shows.
3651 fn trimmed_audio(srv: &mut crate::server::Server) {
3652 let r = titles_ed(
3653 srv,
3654 json!([
3655 {"op": "move", "clip": "A1#0", "at": "2s"},
3656 {"op": "trim", "clip": "A1#0", "edge": "in", "to": "3s"}
3657 ]),
3658 );
3659 assert!(!r.is_error, "{}", r.text);
3660 let (_, c) = audio_clip(srv);
3661 assert!(c.start > 0 && c.in_frame > 0, "start {} in {}", c.start, c.in_frame);
3662 }
3663
3664 fn fps_of(srv: &crate::server::Server) -> f64 {
3665 parse::session_fps(srv.session.as_ref().unwrap())
3666 }
3667
3668 fn frame_at(fps: f64, secs: f64) -> u32 {
3669 (secs * fps).round() as u32
3670 }
3671
3672 fn db_at(srv: &crate::server::Server, secs: f64) -> f32 {
3673 let s = srv.session.as_ref().unwrap();
3674 let fps = parse::session_fps(s);
3675 s.gain_db_at(Lane::new(LaneKind::Audio, 0), 0, frame_at(fps, secs)).unwrap()
3676 }
3677
3678 fn points(srv: &crate::server::Server) -> Vec<GainKey> {
3679 srv.session.as_ref().unwrap().gain_keys_of(Lane::new(LaneKind::Audio, 0), 0).to_vec()
3680 }
3681
3682 #[test]
3683 fn a_huge_bound_echoes_in_scientific_notation() {
3684 let mut s = session();
3685 let err = run(&mut s, json!({"op": "gain", "clip": "A1#0", "db": 1e308})).unwrap_err();
3686 assert!(err.contains("1e308") && err.len() < 200, "{err}");
3687 assert_eq!(fmt(0.0), "0");
3688 assert_eq!(fmt(0.5), "0.5");
3689 assert_eq!(fmt(-1e-5), "-1e-5");
3690 }
3691
3692 #[test]
3693 fn gain_keys_takes_timeline_times_converts_and_undoes() {
3694 let mut srv = open_server();
3695 trimmed_audio(&mut srv);
3696 let (_, c) = audio_clip(&srv);
3697 let fps = fps_of(&srv);
3698 let r = titles_ed(&mut srv, json!([{"op": "gain_keys", "clip": "A1#0", "keys": [["3.5s", -12.0], ["4s", -3]]}]));
3699 assert!(!r.is_error, "{}", r.text);
3700 assert!(r.text.contains("2 point(s)") && r.text.contains("3.500s -12.0 dB"), "{}", r.text);
3701 // The points land on the timeline times asked for, through the clip's in point.
3702 assert!(close(db_at(&srv, 3.5), -12.0));
3703 assert!(close(db_at(&srv, 4.0), -3.0));
3704 // Held beyond the last point, and the envelope is stored on source frames.
3705 assert!(close(db_at(&srv, 4.9), -3.0));
3706 let keys = points(&srv);
3707 assert_eq!(keys[0].at, c.in_frame + (frame_at(fps, 3.5) - c.start));
3708 // Outside the clip is refused, naming the clip's span.
3709 let bad = titles_ed(&mut srv, json!([{"op": "gain_keys", "clip": "A1#0", "keys": [["1s", -3]]}]));
3710 assert!(bad.is_error && bad.text.contains("outside") && bad.text.contains("3.000s"), "{}", bad.text);
3711 // A video clip refuses by name.
3712 let v = titles_ed(&mut srv, json!([{"op": "gain_keys", "clip": "V1#0", "keys": []}]));
3713 assert!(v.is_error && v.text.contains("video lane"), "{}", v.text);
3714 // An empty list clears; undo brings the two points back.
3715 let clr = titles_ed(&mut srv, json!([{"op": "gain_keys", "clip": "A1#0", "keys": []}]));
3716 assert!(!clr.is_error && clr.text.contains("cleared"), "{}", clr.text);
3717 assert!(points(&srv).is_empty());
3718 super::super::edit::run_undo(&mut srv, &json!({}));
3719 assert_eq!(points(&srv).len(), 2);
3720 }
3721
3722 #[test]
3723 fn gain_key_adds_replaces_removes_and_names_misses() {
3724 let mut srv = open_server();
3725 trimmed_audio(&mut srv);
3726 let r = titles_ed(&mut srv, json!([{"op": "gain_key", "clip": "A1#0", "at": "4s", "db": -6}]));
3727 assert!(!r.is_error, "{}", r.text);
3728 assert!(close(db_at(&srv, 4.0), -6.0));
3729 // The same frame is replaced, not doubled.
3730 let r = titles_ed(&mut srv, json!([{"op": "gain_key", "clip": "A1#0", "at": "4s", "db": -9}]));
3731 assert!(!r.is_error && points(&srv).len() == 1, "{}", r.text);
3732 assert!(close(db_at(&srv, 4.0), -9.0));
3733 // A time a frame off the point still removes it.
3734 let rm = titles_ed(&mut srv, json!([{"op": "gain_key_remove", "clip": "A1#0", "at": "4.02s"}]));
3735 assert!(!rm.is_error && rm.text.contains("removed 4.000s -9.0 dB"), "{}", rm.text);
3736 assert!(points(&srv).is_empty());
3737 // Nothing near: the refusal says so.
3738 let none = titles_ed(&mut srv, json!([{"op": "gain_key_remove", "clip": "A1#0", "at": "4s"}]));
3739 assert!(none.is_error && none.text.contains("no gain keys"), "{}", none.text);
3740 // With points present, a miss lists them.
3741 titles_ed(&mut srv, json!([{"op": "gain_key", "clip": "A1#0", "at": "4s", "db": -6}]));
3742 let miss = titles_ed(&mut srv, json!([{"op": "gain_key_remove", "clip": "A1#0", "at": "3.5s"}]));
3743 assert!(miss.is_error && miss.text.contains("4.000s -6.0 dB"), "{}", miss.text);
3744 // A bad dB is refused by name.
3745 let bad = titles_ed(&mut srv, json!([{"op": "gain_key", "clip": "A1#0", "at": "4s", "db": 30}]));
3746 assert!(bad.is_error && bad.text.contains("out of range"), "{}", bad.text);
3747 }
3748
3749 #[test]
3750 fn gain_ramp_replaces_inside_and_keeps_outside() {
3751 let mut srv = open_server();
3752 trimmed_audio(&mut srv);
3753 titles_ed(
3754 &mut srv,
3755 json!([{"op": "gain_keys", "clip": "A1#0", "keys": [["3.5s", -3], ["4s", -3], ["4.5s", -3]]}]),
3756 );
3757 // from_db defaults to the level at 3.8 s (-3 dB here); the 4 s point is inside and goes.
3758 let r = titles_ed(
3759 &mut srv,
3760 json!([{"op": "gain_ramp", "clip": "A1#0", "from": "3.8s", "to": "4.2s", "to_db": -18}]),
3761 );
3762 assert!(!r.is_error, "{}", r.text);
3763 assert!(close(db_at(&srv, 3.8), -3.0));
3764 assert!(close(db_at(&srv, 4.2), -18.0));
3765 assert!(close(db_at(&srv, 4.0), -10.5), "midpoint of the ramp: {}", db_at(&srv, 4.0));
3766 assert_eq!(points(&srv).len(), 4, "3.5, 3.8, 4.2, 4.5");
3767 // An explicit from_db wins over the level there.
3768 titles_ed(&mut srv, json!([{"op": "gain_ramp", "clip": "A1#0", "from": "3.8s", "to": "4.2s", "from_db": -6, "to_db": -18}]));
3769 assert!(close(db_at(&srv, 3.8), -6.0));
3770 // from must come before to.
3771 let back = titles_ed(&mut srv, json!([{"op": "gain_ramp", "clip": "A1#0", "from": "4s", "to": "3.5s", "to_db": -3}]));
3772 assert!(back.is_error && back.text.contains("must be after"), "{}", back.text);
3773 let v = titles_ed(&mut srv, json!([{"op": "gain_ramp", "clip": "V1#0", "from": "3.5s", "to": "4s", "to_db": -3}]));
3774 assert!(v.is_error && v.text.contains("video lane"), "{}", v.text);
3775 }
3776
3777 #[test]
3778 fn gain_dip_shapes_its_ramps_and_clamps_to_the_clip() {
3779 let mut srv = open_server();
3780 trimmed_audio(&mut srv);
3781 let r = titles_ed(
3782 &mut srv,
3783 json!([{"op": "gain_dip", "clip": "A1#0", "from": "3.5s", "to": "4.5s", "db": -18, "ramp": "0.2s"}]),
3784 );
3785 assert!(!r.is_error, "{}", r.text);
3786 assert!(r.text.contains("3.500–4.500s") && r.text.contains("(ramps 0.2s), 4 points"), "{}", r.text);
3787 // Level now at the ramp start and end (0 dB), the dip itself, and the ramps between.
3788 let fps = fps_of(&srv);
3789 let at = |f: u32| {
3790 let s = srv.session.as_ref().unwrap();
3791 s.gain_db_at(Lane::new(LaneKind::Audio, 0), 0, f).unwrap()
3792 };
3793 let from = frame_at(fps, 3.5);
3794 let to = frame_at(fps, 4.5);
3795 let ramp = frame_at(fps, 0.2);
3796 assert!(close(at(from - ramp), 0.0), "ramp start");
3797 assert!(close(at(from), -18.0), "dip starts");
3798 assert!(close(at(from - ramp / 2), -9.0), "halfway down the ramp");
3799 assert!(close(at(from + (to - from) / 2), -18.0), "mid dip");
3800 assert!(close(at(to), -18.0), "dip ends");
3801 assert!(close(at(to + ramp), 0.0), "ramp end");
3802 assert!(close(at(to + ramp + 10), 0.0), "held after");
3803 // Ramps reaching past the clip start are clamped to it: the first ramp point is the clip start.
3804 let mut srv2 = open_server();
3805 trimmed_audio(&mut srv2);
3806 let r = titles_ed(
3807 &mut srv2,
3808 json!([{"op": "gain_dip", "clip": "A1#0", "from": "3s", "to": "3.5s", "db": -18}]),
3809 );
3810 assert!(!r.is_error, "{}", r.text);
3811 assert!(r.text.contains("3 points"), "the ramp in starts at the clip start, so only three points: {}", r.text);
3812 // Undo takes the dip back off.
3813 super::super::edit::run_undo(&mut srv, &json!({}));
3814 assert!(points(&srv).is_empty());
3815 }
3816
3817 #[test]
3818 fn gain_ops_accept_the_clip_start_and_its_displayed_end() {
3819 let mut srv = open_server();
3820 trimmed_audio(&mut srv);
3821 let (_, c) = audio_clip(&srv);
3822 // The end is the time the clip's last frame plays to, so it is a valid time.
3823 let start = format!("{}f", c.start);
3824 let end = format!("{}f", c.end());
3825 let dip = titles_ed(
3826 &mut srv,
3827 json!([{"op": "gain_dip", "clip": "A1#0", "from": start, "to": end, "db": -12, "ramp": "0.2s"}]),
3828 );
3829 assert!(!dip.is_error && dip.text.contains("2 points"), "{}", dip.text);
3830 let key = titles_ed(&mut srv, json!([{"op": "gain_key", "clip": "A1#0", "at": end, "db": -6}]));
3831 assert!(!key.is_error, "{}", key.text);
3832 let rm = titles_ed(&mut srv, json!([{"op": "gain_key_remove", "clip": "A1#0", "at": end}]));
3833 assert!(!rm.is_error && rm.text.contains("removed"), "{}", rm.text);
3834 let keys = titles_ed(&mut srv, json!([{"op": "gain_keys", "clip": "A1#0", "keys": [[&end, -3], [&start, -1]]}]));
3835 assert!(!keys.is_error, "{}", keys.text);
3836 let ramp = titles_ed(
3837 &mut srv,
3838 json!([{"op": "gain_ramp", "clip": "A1#0", "from": start, "to": end, "to_db": -18}]),
3839 );
3840 assert!(!ramp.is_error, "{}", ramp.text);
3841 // One frame past the end is still outside the clip, and refused by name.
3842 let past = format!("{}f", c.end() + 1);
3843 let bad = titles_ed(&mut srv, json!([{"op": "gain_key", "clip": "A1#0", "at": past, "db": -6}]));
3844 assert!(bad.is_error && bad.text.contains("outside"), "{}", bad.text);
3845 }
3846
3847 #[test]
3848 fn gain_dip_names_a_ramp_the_clip_bounds_shorten() {
3849 let mut srv = open_server();
3850 trimmed_audio(&mut srv);
3851 let (_, c) = audio_clip(&srv);
3852 let fps = fps_of(&srv);
3853 // Both ends sit 0.1 s inside the clip, so the default 0.5 s ramps can only be 0.1 s.
3854 let from = c.start + frame_at(fps, 0.1);
3855 let to = c.end() - frame_at(fps, 0.1);
3856 let r = titles_ed(
3857 &mut srv,
3858 json!([{"op": "gain_dip", "clip": "A1#0", "from": format!("{from}f"), "to": format!("{to}f"), "db": -18}]),
3859 );
3860 assert!(!r.is_error, "{}", r.text);
3861 assert!(r.text.contains("(note:"), "the cut ramps are named: {}", r.text);
3862 assert!(r.text.contains("ramp in shortened to 0.1s: the clip starts at"), "{}", r.text);
3863 assert!(r.text.contains("ramp out shortened to 0.1s: the clip ends at"), "{}", r.text);
3864 // The shortened ramps are still applied: the dip itself holds at its level.
3865 assert!(close(db_at(&srv, f64::from(to) / fps), -18.0), "the dip still lands");
3866 }
3867
3868 fn open_server() -> crate::server::Server {
3869 engine::ao::set_silent_output();
3870 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
3871 let mut srv = crate::server::Server::new();
3872 srv.session = Some(PlaybackSession::open(p).expect("open test asset"));
3873 srv
3874 }
3875
3876 fn titles_ed(srv: &mut crate::server::Server, ops: Value) -> crate::server::Reply {
3877 super::super::edit::run_edit(srv, &json!({ "ops": ops }))
3878 }
3879
3880 fn texts(srv: &crate::server::Server) -> Vec<String> {
3881 srv.session.as_ref().unwrap().titles().iter().map(|t| t.text.clone()).collect()
3882 }
3883
3884 #[test]
3885 fn a_title_animation_is_set_by_title_add_and_title_set() {
3886 let mut srv = open_server();
3887 let fps = srv.session.as_ref().unwrap().meta().frame_rate.round() as u32;
3888 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "1s", "duration": 3, "text": "Hi there", "in_anim": "typewriter"}]));
3889 assert!(!r.is_error && r.text.contains("anim in typewriter out none"), "{}", r.text);
3890 // A bare number is seconds, so `anim_secs: 1` is a second of frames, not one frame.
3891 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T1", "out_anim": "slide_up", "anim_secs": 1}]));
3892 assert!(!r.is_error, "{}", r.text);
3893 {
3894 let t = &srv.session.as_ref().unwrap().titles()[0];
3895 assert_eq!((t.in_anim, t.out_anim, t.anim_frames), (engine::titleanim::TitleAnim::Typewriter, engine::titleanim::TitleAnim::SlideUp, fps));
3896 }
3897 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T1", "in_anim": "wobble"}]));
3898 assert!(r.is_error && r.text.contains("wobble"), "{}", r.text);
3899 }
3900
3901 #[test]
3902 fn title_add_set_remove_and_undo_through_edit() {
3903 let mut srv = open_server();
3904 let r = titles_ed(
3905 &mut srv,
3906 json!([{"op": "title_add", "at": "1s", "duration": 3, "text": "Episode 17", "fade_in": 12, "fade_out": 12}]),
3907 );
3908 assert!(!r.is_error, "{}", r.text);
3909 assert!(r.text.contains("title T1 \"Episode 17\" 1.000–4.000 centre size 80 outline thin fade 12f/12f"), "{}", r.text);
3910
3911 // set by name, by lower-case name, and by number; fields merge onto the old ones
3912 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T1", "size": 120}]));
3913 assert!(!r.is_error && r.text.contains("size 120"), "{}", r.text);
3914 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": 1, "boxed": true, "place": "bottom"}]));
3915 assert!(!r.is_error, "{}", r.text);
3916 {
3917 let t = &srv.session.as_ref().unwrap().titles()[0];
3918 assert_eq!(t.style.size, 120);
3919 assert!(t.style.boxed);
3920 assert_eq!(t.style.place, engine::text::Place::Bottom);
3921 assert_eq!(t.text, "Episode 17");
3922 }
3923
3924 // a title that lands before T1 takes the name T1; the old one is T2
3925 let r = titles_ed(
3926 &mut srv,
3927 json!([{"op": "title_add", "at": "0", "duration": 1, "text": "Cold open"}]),
3928 );
3929 assert!(!r.is_error && r.text.contains("title T1 \"Cold open\""), "{}", r.text);
3930 assert!(r.text.contains("titles after it renumber"), "{}", r.text);
3931 assert_eq!(texts(&srv), vec!["Cold open", "Episode 17"]);
3932
3933 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "t2", "text": "Episode 18"}]));
3934 assert!(!r.is_error && r.text.contains("\"Episode 18\""), "{}", r.text);
3935 let r = titles_ed(&mut srv, json!([{"op": "title_remove", "title": "T1"}]));
3936 assert!(!r.is_error && r.text.contains("removed title T1 \"Cold open\""), "{}", r.text);
3937 assert_eq!(texts(&srv), vec!["Episode 18"]);
3938
3939 // six batches, six undo steps: back to no titles at all
3940 let u = super::super::edit::run_undo(&mut srv, &json!({ "steps": 6 }));
3941 assert!(!u.is_error, "{}", u.text);
3942 assert!(srv.session.as_ref().unwrap().titles().is_empty());
3943 }
3944
3945 #[test]
3946 fn title_presets_give_the_app_look_and_the_fields_given_win() {
3947 use engine::project::TitlePreset;
3948 let mut srv = open_server();
3949 let fps = srv.session.as_ref().unwrap().meta().frame_rate;
3950 // A lower third is the app's look: bold, bottom-left, boxed, 45 size, half-second fades.
3951 let r = titles_ed(
3952 &mut srv,
3953 json!([{"op": "title_add", "at": "1s", "duration": "3s", "text": "Jane Doe", "preset": "lower_third"}]),
3954 );
3955 assert!(!r.is_error, "{}", r.text);
3956 {
3957 let t = &srv.session.as_ref().unwrap().titles()[0];
3958 assert_eq!(t.text, "Jane Doe");
3959 assert_eq!((t.start, t.frames), (fps as u32, (3.0 * fps).round() as u32));
3960 assert_eq!(t.style.size, 45);
3961 assert_eq!((t.style.place, t.style.hplace, t.style.align, t.style.weight), (Place::Bottom, HPlace::Left, Align::Left, Weight::Bold));
3962 assert!(t.style.boxed);
3963 assert_eq!((t.fade_in, t.fade_out), ((0.5 * fps).round() as u32, (0.5 * fps).round() as u32));
3964 }
3965 // a field given with the preset wins over the preset's look
3966 let r = titles_ed(
3967 &mut srv,
3968 json!([{"op": "title_add", "at": "6s", "duration": "2s", "text": "Centre", "preset": "centered", "size": 60, "fade_in": 0}]),
3969 );
3970 assert!(!r.is_error, "{}", r.text);
3971 {
3972 let t = &srv.session.as_ref().unwrap().titles()[1];
3973 assert_eq!(t.style.size, 60, "the size given wins");
3974 assert_eq!((t.style.place, t.style.outline, t.style.boxed), (Place::Centre, Outline::Thin, false));
3975 assert_eq!((t.fade_in, t.fade_out), (0, (0.5 * fps).round() as u32), "fade_in given wins, fade_out keeps the preset's");
3976 }
3977 // title_set applies a preset to an existing title: its words and timing stay
3978 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T1", "preset": "caption_bar"}]));
3979 assert!(!r.is_error, "{}", r.text);
3980 {
3981 let t = &srv.session.as_ref().unwrap().titles()[0];
3982 assert_eq!((t.text.as_str(), t.start), ("Jane Doe", fps as u32));
3983 assert_eq!((t.style.size, t.style.boxed, t.style.place, t.fade_in), (40, true, Place::Bottom, 0));
3984 }
3985 // the engine's own definition agrees with what MCP stored
3986 let (look, _) = TitlePreset::CaptionBar.look();
3987 assert_eq!(srv.session.as_ref().unwrap().titles()[0].style, look);
3988 // an unknown preset is refused by name and adds nothing
3989 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "9s", "duration": "1s", "text": "x", "preset": "fancy"}]));
3990 assert!(r.is_error && r.text.contains("title preset `fancy` is not lower_third, centered or caption_bar"), "{}", r.text);
3991 assert_eq!(srv.session.as_ref().unwrap().titles().len(), 2);
3992 }
3993
3994 #[test]
3995 fn title_past_the_end_extends_the_timeline() {
3996 let mut srv = open_server();
3997 let end = parse::session_end(srv.session.as_ref().unwrap());
3998 let at = format!("{}f", end + 30);
3999 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": at, "duration": "2.0s", "text": "The end"}]));
4000 assert!(!r.is_error, "{}", r.text);
4001 let s = srv.session.as_ref().unwrap();
4002 let t = s.titles()[0].clone();
4003 assert_eq!(t.start, end + 30);
4004 assert_eq!(parse::session_end(s), t.end(), "the timeline runs to the title's last frame");
4005 }
4006
4007 #[test]
4008 fn a_title_warns_about_glyphs_the_font_cannot_draw_and_about_a_long_text() {
4009 let mut srv = open_server();
4010 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "\u{10FFFD}"}]));
4011 assert!(!r.is_error, "{}", r.text);
4012 assert!(r.text.contains("no glyph in the title font") && r.text.contains("draw as boxes"), "{}", r.text);
4013 assert!(r.text.contains("\u{10FFFD}"), "{}", r.text);
4014 // In another place, so it does not overlap the first title and earns no overlap warning.
4015 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "Hello", "place": "bottom"}]));
4016 assert!(!r.text.contains("warning"), "{}", r.text);
4017 let long = "word ".repeat(100);
4018 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T2", "text": long}]));
4019 assert!(!r.is_error && r.text.contains("this title is long"), "{}", r.text);
4020 }
4021
4022 #[test]
4023 fn title_remove_says_which_titles_renumber() {
4024 let mut srv = open_server();
4025 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "One"}, {"op": "title_add", "at": "3", "duration": 2, "text": "Two"}]));
4026 assert!(!r.is_error, "{}", r.text);
4027 let r = titles_ed(&mut srv, json!([{"op": "title_remove", "title": "T1"}]));
4028 assert!(!r.is_error && r.text.contains("T2 is now T1"), "{}", r.text);
4029 assert_eq!(texts(&srv), vec!["Two"]);
4030 }
4031
4032 #[test]
4033 fn title_refusals_name_what_to_do() {
4034 let mut srv = open_server();
4035 let r = titles_ed(&mut srv, json!([{"op": "title_remove", "title": "T1"}]));
4036 assert!(r.is_error && r.text.contains("no titles yet"), "{}", r.text);
4037 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": " "}]));
4038 assert!(r.is_error && r.text.contains("needs some text"), "{}", r.text);
4039 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "Hi", "size": 500}]));
4040 assert!(r.is_error && r.text.contains("size"), "{}", r.text);
4041 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "Hi", "outline": "wide"}]));
4042 assert!(r.is_error && r.text.contains("outline"), "{}", r.text);
4043 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "Hi", "fade_in": 90}]));
4044 assert!(r.is_error && r.text.contains("fades"), "{}", r.text);
4045 let r = titles_ed(&mut srv, json!([{"op": "title_add", "at": "0", "duration": 2, "text": "Hi"}]));
4046 assert!(!r.is_error, "{}", r.text);
4047 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T9", "size": 60}]));
4048 assert!(r.is_error && r.text.contains("T1..T1"), "{}", r.text);
4049 // a batch with a refused title rolls back
4050 let r = titles_ed(
4051 &mut srv,
4052 json!([{"op": "title_add", "at": "1s", "duration": 2, "text": "Two"}, {"op": "title_remove", "title": "T7"}]),
4053 );
4054 assert!(r.is_error, "{}", r.text);
4055 assert_eq!(texts(&srv), vec!["Hi"]);
4056 }
4057
4058 /// `T@<frame>` names a title by its start frame, the form `timeline` and the title replies
4059 /// print. The number after `T@` is frames, so `T@1200` on a 30 fps timeline is the title at
4060 /// 1200 frames (40 s), not at 1200 seconds. Bare numbers are seconds everywhere else.
4061 #[test]
4062 fn title_addresses_by_start_frame_resolve_to_the_title_they_name() {
4063 let mut srv = open_server();
4064 let r = titles_ed(
4065 &mut srv,
4066 json!([
4067 {"op": "title_add", "at": "30f", "duration": "60f", "text": "early"},
4068 {"op": "title_add", "at": "1200f", "duration": "60f", "text": "late"}
4069 ]),
4070 );
4071 assert!(!r.is_error, "{}", r.text);
4072
4073 let r = titles_ed(&mut srv, json!([{"op": "title_set", "title": "T@1200", "size": 60}]));
4074 assert!(!r.is_error && r.text.contains("size 60"), "{}", r.text);
4075 assert_eq!(srv.session.as_ref().unwrap().titles()[1].style.size, 60);
4076
4077 let r = titles_ed(&mut srv, json!([{"op": "title_remove", "title": "T@1200"}]));
4078 assert!(!r.is_error && r.text.contains("removed title T2 \"late\""), "{}", r.text);
4079 assert_eq!(texts(&srv), vec!["early"]);
4080
4081 let r = titles_ed(&mut srv, json!([{"op": "title_remove", "title": "T@30"}]));
4082 assert!(!r.is_error && r.text.contains("removed title T1 \"early\""), "{}", r.text);
4083 assert!(texts(&srv).is_empty());
4084 }
4085}
4086
4087#[cfg(test)]
4088mod transform_keys_tests {
4089 use super::*;
4090 use serde_json::json;
4091
4092 /// Envelope times are stored in source frames, so a ramped clip's timeline-to-source
4093 /// conversion is the ramp's integral and `timeline_of` its inverse.
4094 #[test]
4095 fn source_and_timeline_conversions_follow_a_ramp() {
4096 let mut c = Clip::source_range(0, 10, 400);
4097 c.start = 100;
4098 c.speed_keys = vec![
4099 engine::project::SpeedKey { at: 0, speed: engine::project::Speed::NORMAL },
4100 engine::project::SpeedKey { at: 60, speed: engine::project::Speed::from_permille(2000) },
4101 ];
4102 // 60 frames in the ramp has read 90 source frames.
4103 assert!((src_of(&c, 160.0) - 100.0).abs() < 1e-9);
4104 assert_eq!(src_at(&c, 160), 100);
4105 assert!((timeline_of(&c, 100) - 160.0).abs() < 1e-6);
4106 }
4107
4108 fn session() -> PlaybackSession {
4109 engine::ao::set_silent_output();
4110 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
4111 PlaybackSession::open(p).expect("open test asset")
4112 }
4113
4114 fn run(s: &mut PlaybackSession, op: Value) -> Result<Applied, String> {
4115 apply(s, &op, 30.0).expect("the op is one of this module's")
4116 }
4117
4118 #[test]
4119 fn keys_sort_on_clip_time_and_hold_the_fields_they_do_not_name() {
4120 let mut s = session();
4121 let applied = run(
4122 &mut s,
4123 json!({"op": "transform_keys", "clip": "V1#0", "keys": [
4124 {"at": "end", "scale": 1.2, "ease": "ease"},
4125 {"at": "0s", "scale": 1.0, "x": 0.1},
4126 {"at": "50%", "rotate": 10}
4127 ]}),
4128 )
4129 .expect("keys applied");
4130 let keys = s.transform_keys_of(Lane::V1, 0).to_vec();
4131 assert_eq!(keys.len(), 3);
4132 assert_eq!(keys.iter().map(|k| k.at).collect::<Vec<_>>(), vec![0, 75, 150], "0s, 50%, end");
4133 assert_eq!(keys[1].params.scale, 1.0, "scale held from the 0s key");
4134 assert_eq!(keys[1].params.pos_x, 0.1, "x held from the 0s key");
4135 assert_eq!(keys[1].params.rotate, 10.0);
4136 assert_eq!(keys[2].params.scale, 1.2);
4137 assert_eq!(keys[2].params.rotate, 10.0, "rotate held from the 50% key");
4138 assert_eq!(keys[2].ease, engine::transform::KeyEase::Ease);
4139 assert_eq!(keys[0].ease, engine::transform::KeyEase::Linear, "default ease");
4140 assert!(applied.text.contains("3 key(s)"), "{}", applied.text);
4141 assert!(applied.text.contains("0.000s") && applied.text.contains("5.000s"), "timeline times: {}", applied.text);
4142 }
4143
4144 #[test]
4145 fn a_keyed_clip_refuses_transform_until_its_keys_are_cleared() {
4146 let mut s = session();
4147 run(
4148 &mut s,
4149 json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "0s", "scale": 1.0}, {"at": "end", "scale": 1.2}]}),
4150 )
4151 .expect("keys");
4152 let err = run(&mut s, json!({"op": "transform", "clip": "V1#0", "x": 0.2})).expect_err("refused");
4153 assert!(err.contains("transform key"), "{err}");
4154 run(&mut s, json!({"op": "transform_keys", "clip": "V1#0", "clear": true})).expect("clear");
4155 assert!(s.transform_keys_of(Lane::V1, 0).is_empty());
4156 run(&mut s, json!({"op": "transform", "clip": "V1#0", "x": 0.2})).expect("plain again");
4157 }
4158
4159 #[test]
4160 fn two_keys_at_one_time_say_so_at_normal_speed() {
4161 let mut s = session();
4162 let err = run(
4163 &mut s,
4164 json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "1s"}, {"at": "1s", "scale": 1.2}]}),
4165 )
4166 .expect_err("two keys at 1 s");
4167 assert!(err.contains("two keys at the same time (1.000s)"), "{err}");
4168 assert!(!err.contains("speed"), "no speed talk at 1x: {err}");
4169 }
4170
4171 #[test]
4172 fn a_key_past_the_clip_names_its_place_in_the_list() {
4173 let mut s = session();
4174 let err = run(
4175 &mut s,
4176 json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "0s"}, {"at": "9s"}]}),
4177 )
4178 .expect_err("9 s past a 5 s clip");
4179 assert!(err.contains("the 2nd key, at 9.000s, is past the clip"), "{err}");
4180 }
4181
4182 #[test]
4183 fn ordinals_read_as_english_for_any_list_position() {
4184 assert_eq!(ordinal(1), "1st");
4185 assert_eq!(ordinal(2), "2nd");
4186 assert_eq!(ordinal(3), "3rd");
4187 assert_eq!(ordinal(4), "4th");
4188 assert_eq!(ordinal(11), "11th");
4189 assert_eq!(ordinal(12), "12th");
4190 assert_eq!(ordinal(13), "13th");
4191 assert_eq!(ordinal(21), "21st");
4192 assert_eq!(ordinal(111), "111th");
4193 assert_eq!(ordinal(242), "242nd");
4194 }
4195
4196 #[test]
4197 fn keys_are_refused_on_audio_past_the_clip_and_with_bad_fields() {
4198 let mut s = session();
4199 assert!(run(&mut s, json!({"op": "transform_keys", "clip": "A1#0", "keys": [{"at": "0s"}]})).is_err());
4200 assert!(run(&mut s, json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "9s"}]})).is_err(), "past a 5 s clip");
4201 assert!(run(&mut s, json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "0s", "spin": 1}]})).is_err());
4202 assert!(run(&mut s, json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"scale": 1}]})).is_err(), "no at");
4203 assert!(run(&mut s, json!({"op": "transform_keys", "clip": "V1#0", "keys": []})).is_err(), "empty list");
4204 assert!(run(&mut s, json!({"op": "transform_keys", "clip": "V1#0"})).is_err(), "no keys at all");
4205 }
4206
4207 #[test]
4208 fn every_ease_name_is_taken_and_a_bad_one_lists_them() {
4209 use engine::transform::KeyEase;
4210 let mut s = session();
4211 for (name, want) in [
4212 ("linear", KeyEase::Linear),
4213 ("ease_in", KeyEase::EaseIn),
4214 ("ease_out", KeyEase::EaseOut),
4215 ("ease_in_out", KeyEase::Ease),
4216 ("ease", KeyEase::Ease),
4217 ("hold", KeyEase::Hold),
4218 ] {
4219 run(
4220 &mut s,
4221 json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "0s", "ease": name}, {"at": "end", "scale": 1.2}]}),
4222 )
4223 .unwrap_or_else(|e| panic!("{name}: {e}"));
4224 assert_eq!(s.transform_keys_of(Lane::V1, 0)[0].ease, want, "{name}");
4225 }
4226 let err = run(
4227 &mut s,
4228 json!({"op": "transform_keys", "clip": "V1#0", "keys": [{"at": "0s", "ease": "bounce"}]}),
4229 )
4230 .expect_err("bad ease");
4231 assert!(err.contains("ease_in") && err.contains("hold") && err.contains("\"bounce\""), "{err}");
4232 }
4233
4234 #[test]
4235 fn opacity_keys_set_clear_refuse_and_hold_what_a_key_leaves_out() {
4236 use engine::transform::KeyEase;
4237 let mut s = session();
4238 let reply = run(
4239 &mut s,
4240 json!({"op": "opacity_keys", "clip": "V1#0", "keys": [
4241 {"at": "0s", "opacity": 0, "ease": "ease_in_out"}, {"at": "2s"}, {"at": "end", "opacity": 1}]}),
4242 )
4243 .expect("opacity_keys");
4244 assert!(reply.text.contains("3 key(s)") && reply.text.contains("ease_in_out"), "{}", reply.text);
4245 let keys = s.opacity_keys_of(Lane::V1, 0).to_vec();
4246 assert_eq!(keys.len(), 3);
4247 assert_eq!((keys[0].opacity, keys[1].opacity, keys[2].opacity), (0.0, 0.0, 1.0), "a missing opacity holds");
4248 assert_eq!(keys[0].ease, KeyEase::Ease);
4249 let again = run(
4250 &mut s,
4251 json!({"op": "opacity_keys", "clip": "V1#0", "keys": [
4252 {"at": "0s", "opacity": 0, "ease": "ease_in_out"}, {"at": "2s"}, {"at": "end", "opacity": 1}]}),
4253 )
4254 .expect("repeat");
4255 assert!(again.text.contains("already"), "{}", again.text);
4256 // The constant opacity is refused while keys give it.
4257 let err = run(&mut s, json!({"op": "transform", "clip": "V1#0", "opacity": 0.5})).expect_err("keyed");
4258 assert!(err.contains("opacity key"), "{err}");
4259 run(&mut s, json!({"op": "transform", "clip": "V1#0", "x": 0.1})).expect("other fields are fine");
4260 // Refusals.
4261 for bad in [
4262 json!({"op": "opacity_keys", "clip": "A1#0", "keys": [{"at": "0s", "opacity": 1}]}),
4263 json!({"op": "opacity_keys", "clip": "V1#0", "keys": [{"at": "0s", "opacity": 1.5}]}),
4264 json!({"op": "opacity_keys", "clip": "V1#0", "keys": [{"at": "0s", "scale": 1}]}),
4265 json!({"op": "opacity_keys", "clip": "V1#0", "keys": []}),
4266 json!({"op": "opacity_keys", "clip": "V1#0"}),
4267 json!({"op": "opacity_keys", "clip": "V1#0", "keys": [{"at": "1s"}, {"at": "1s"}]}),
4268 ] {
4269 assert!(run(&mut s, bad.clone()).is_err(), "{bad}");
4270 }
4271 run(&mut s, json!({"op": "opacity_keys", "clip": "V1#0", "clear": true})).expect("clear");
4272 assert!(s.opacity_keys_of(Lane::V1, 0).is_empty());
4273 assert!(s.undo(), "the clear is one undo step");
4274 assert_eq!(s.opacity_keys_of(Lane::V1, 0).len(), 3);
4275 }
4276
4277 #[test]
4278 fn color_keys_start_from_the_clips_grade_and_refuse_the_constant_color() {
4279 let mut s = session();
4280 run(&mut s, json!({"op": "color", "clip": "V1#0", "contrast": 1.5})).expect("a grade");
4281 run(
4282 &mut s,
4283 json!({"op": "color_keys", "clip": "V1#0", "keys": [
4284 {"at": "0s", "brightness": -0.5}, {"at": "end", "brightness": 0.5, "tint": 0.25, "ease": "hold"}]}),
4285 )
4286 .expect("color_keys");
4287 let keys = s.color_keys_of(Lane::V1, 0).to_vec();
4288 assert_eq!(keys[0].params.contrast, 1.5, "the first key starts from the grade");
4289 assert_eq!(keys[1].params.contrast, 1.5, "a key holds what it leaves out");
4290 assert_eq!(keys[1].params.tint, 0.25);
4291 assert_eq!(keys[0].ease, engine::transform::KeyEase::Linear);
4292 let err = run(&mut s, json!({"op": "color", "clip": "V1#0", "brightness": 0.1})).expect_err("keyed");
4293 assert!(err.contains("colour key") && err.contains("color_keys"), "{err}");
4294 assert!(run(&mut s, json!({"op": "color_keys", "clip": "V1#0", "keys": [{"at": "0s", "contrast": 3}]})).is_err());
4295 assert!(run(&mut s, json!({"op": "color_keys", "clip": "A1#0", "keys": [{"at": "0s", "tint": 0.1}]})).is_err());
4296 run(&mut s, json!({"op": "color_keys", "clip": "V1#0", "clear": true})).expect("clear");
4297 run(&mut s, json!({"op": "color", "clip": "V1#0", "brightness": 0.1})).expect("plain again");
4298 }
4299
4300 #[test]
4301 fn gain_points_take_an_ease() {
4302 use engine::transform::KeyEase;
4303 let mut s = session();
4304 run(
4305 &mut s,
4306 json!({"op": "gain_keys", "clip": "A1#0", "keys": [["0s", 0, "ease_out"], ["2s", -12], ["3s", -6, "hold"]]}),
4307 )
4308 .expect("gain_keys with eases");
4309 let g = s.gain_keys_of(Lane::A1, 0).to_vec();
4310 assert_eq!((g[0].ease, g[1].ease, g[2].ease), (KeyEase::EaseOut, KeyEase::Linear, KeyEase::Hold));
4311 run(&mut s, json!({"op": "gain_key", "clip": "A1#0", "at": "1s", "db": -3, "ease": "ease_in"})).expect("gain_key");
4312 assert!(s.gain_keys_of(Lane::A1, 0).iter().any(|k| k.ease == KeyEase::EaseIn));
4313 assert!(run(&mut s, json!({"op": "gain_keys", "clip": "A1#0", "keys": [["0s", 0, "wobble"]]})).is_err());
4314 }
4315}
4316
4317#[cfg(test)]
4318mod look_ops_tests {
4319 use super::*;
4320 use serde_json::json;
4321
4322 fn session() -> PlaybackSession {
4323 engine::ao::set_silent_output();
4324 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
4325 PlaybackSession::open(p).expect("open test asset")
4326 }
4327
4328 fn run(s: &mut PlaybackSession, op: Value) -> Result<Applied, String> {
4329 apply(s, &op, 30.0).expect("the op is one of this module's")
4330 }
4331
4332 fn cube(name: &str, text: &str) -> std::path::PathBuf {
4333 let dir = std::env::temp_dir().join(format!("edith-mcp-lut-{}", std::process::id()));
4334 std::fs::create_dir_all(&dir).expect("dir");
4335 let p = dir.join(name);
4336 std::fs::write(&p, text).expect("write");
4337 p
4338 }
4339
4340 const WARM: &str = "LUT_3D_SIZE 2\n0.05 0 0\n1 0 0\n0.05 1 0\n1 1 0\n0.05 0 0.85\n1 0 0.85\n0.05 1 0.85\n1 1 0.85\n";
4341
4342 #[test]
4343 fn lut_sets_mixes_clears_and_refuses_a_broken_file_by_name() {
4344 let mut s = session();
4345 let warm = cube("warm.cube", WARM);
4346 let r = run(&mut s, json!({"op": "lut", "clip": "V1#0", "path": warm.display().to_string(), "mix": 0.8})).expect("set");
4347 assert!(r.text.contains("LUT warm.cube, 3D 2 at 80%"), "{}", r.text);
4348 let c = *s.color_of(Lane::V1, 0).expect("graded");
4349 assert_eq!(c.look.lut.map(|l| l.path()), Some(warm.clone()));
4350 assert_eq!(c.look.lut_mix, 0.8);
4351 run(&mut s, json!({"op": "lut", "clip": "V1#0", "mix": 0.5})).expect("mix only");
4352 assert_eq!(s.color_of(Lane::V1, 0).expect("graded").look.lut_mix, 0.5);
4353 let bad = cube("bad.cube", "LUT_3D_SIZE 2\n0 0 0\n");
4354 let e = run(&mut s, json!({"op": "lut", "clip": "V1#0", "path": bad.display().to_string()})).unwrap_err();
4355 assert!(e.contains("cannot use that LUT") && e.contains("entries"), "{e}");
4356 let e = run(&mut s, json!({"op": "lut", "clip": "V1#0", "path": "/nonexistent/x.cube"})).unwrap_err();
4357 assert!(e.contains("cannot read"), "{e}");
4358 assert!(run(&mut s, json!({"op": "lut", "clip": "V1#0", "mix": 2})).is_err());
4359 assert!(run(&mut s, json!({"op": "lut", "clip": "A1#0", "path": warm.display().to_string()})).is_err(), "picture only");
4360 // Relink: every clip naming the file moves to the new one.
4361 let other = cube("other.cube", WARM);
4362 let r = run(&mut s, json!({"op": "lut", "relink": warm.display().to_string(), "path": other.display().to_string()})).expect("relink");
4363 assert!(r.text.contains("1 clip(s)"), "{}", r.text);
4364 assert_eq!(s.color_of(Lane::V1, 0).and_then(|c| c.look.lut).map(|l| l.path()), Some(other.clone()));
4365 assert!(run(&mut s, json!({"op": "lut", "relink": "/no/such.cube", "path": other.display().to_string()})).unwrap_err().contains("no clip names"));
4366 run(&mut s, json!({"op": "lut", "clip": "V1#0", "clear": true})).expect("clear");
4367 assert!(s.color_of(Lane::V1, 0).is_none(), "nothing left: no grade");
4368 }
4369
4370 #[test]
4371 fn wheels_and_curves_merge_onto_the_grade() {
4372 let mut s = session();
4373 run(&mut s, json!({"op": "color", "clip": "V1#0", "contrast": 1.2})).expect("grade");
4374 let r = run(&mut s, json!({"op": "wheels", "clip": "V1#0", "lift": [0, 0.1, 0, -0.05], "gain": 0.2})).expect("wheels");
4375 assert!(r.text.contains("lift m+0.00 r+0.10 g+0.00 b-0.05") && r.text.contains("gain m+0.20"), "{}", r.text);
4376 run(&mut s, json!({"op": "curves", "clip": "V1#0", "master": [[0.25, 0.2], [0.75, 0.8]], "blue": [[0.5, 0.45]]})).expect("curves");
4377 let c = *s.color_of(Lane::V1, 0).expect("graded");
4378 assert_eq!(c.contrast, 1.2, "the sliders stay");
4379 assert_eq!(c.look.wheels.lift, [0.0, 0.1, 0.0, -0.05]);
4380 assert_eq!(c.look.wheels.gain, [0.2, 0.0, 0.0, 0.0]);
4381 assert_eq!(c.look.curves[0].points(), &[[0.25, 0.2], [0.75, 0.8]]);
4382 assert_eq!(c.look.curves[3].points(), &[[0.5, 0.45]]);
4383 assert!(run(&mut s, json!({"op": "wheels", "clip": "V1#0", "lift": [2, 0, 0, 0]})).is_err());
4384 assert!(run(&mut s, json!({"op": "wheels", "clip": "V1#0", "lift": [0, 0]})).is_err());
4385 assert!(run(&mut s, json!({"op": "curves", "clip": "V1#0", "red": [[0.5, 0.2], [0.4, 0.3]]})).unwrap_err().contains("strictly increase"));
4386 assert!(run(&mut s, json!({"op": "curves", "clip": "V1#0"})).is_err());
4387 run(&mut s, json!({"op": "curves", "clip": "V1#0", "reset": true})).expect("straight");
4388 run(&mut s, json!({"op": "wheels", "clip": "V1#0", "reset": true})).expect("neutral");
4389 assert_eq!(s.color_of(Lane::V1, 0).expect("graded").look, engine::color::Look::default());
4390 }
4391
4392 #[test]
4393 fn look_applies_a_builtin_in_one_step_and_names_the_choices_when_unknown() {
4394 let mut s = session();
4395 run(&mut s, json!({"op": "color", "clip": "V1#0", "contrast": 1.2})).expect("grade");
4396 let r = run(&mut s, json!({"op": "look", "clip": "V1#0", "name": "warm"})).expect("look");
4397 assert_eq!(r.text, "look V1#0 → warm");
4398 let c = *s.color_of(Lane::V1, 0).expect("graded");
4399 assert_eq!(c, engine::looks::builtin("Warm").expect("built-in"), "the look replaces the grade");
4400 let e = run(&mut s, json!({"op": "look", "clip": "V1#0", "name": "Nope"})).unwrap_err();
4401 assert!(e.contains("Looks: Warm, Cool") && e.contains("Vintage"), "{e}");
4402 run(&mut s, json!({"op": "look", "clip": "V1#0", "name": "Black & white"})).expect("bw");
4403 assert_eq!(s.color_of(Lane::V1, 0).expect("graded").saturation, 0.0);
4404 }
4405
4406 #[test]
4407 fn auto_color_writes_a_correction_and_reports_it() {
4408 let mut s = session();
4409 let r = run(&mut s, json!({"op": "auto_color", "clip": "V1#0"})).expect("auto");
4410 assert!(r.text.starts_with("auto_color V1#0 → wheels gain red"), "{}", r.text);
4411 let c = *s.color_of(Lane::V1, 0).copied().as_ref().unwrap_or(&engine::color::ColorParams::default());
4412 assert_eq!(c.saturation, 1.0, "saturation is kept");
4413 assert!(run(&mut s, json!({"op": "color", "clip": "V1#0", "brightness": 0.1})).is_ok());
4414 assert!(run(&mut s, json!({"op": "auto_color", "clip": "A1#0"})).is_err(), "a sound clip has no picture");
4415 assert_eq!(super::fit_to(1920, 1080, 640), (640, 360));
4416 }
4417}
4418
4419#[cfg(test)]
4420mod pitch_op_tests {
4421 use super::*;
4422 use serde_json::json;
4423
4424 fn session() -> PlaybackSession {
4425 engine::ao::set_silent_output();
4426 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
4427 PlaybackSession::open(p).expect("open test asset")
4428 }
4429
4430 fn run(s: &mut PlaybackSession, op: Value) -> Result<Applied, String> {
4431 apply(s, &op, 30.0).expect("the op is one of this module's")
4432 }
4433
4434 /// `pitch` sets whole semitones on an audio clip, keeps its length, undoes in one step,
4435 /// and refuses a fraction, an out-of-range value, a missing value and a video clip.
4436 #[test]
4437 fn pitch_sets_whole_semitones_keeps_length_and_refuses_bad_input() {
4438 let mut s = session();
4439 let len = s.lane_clips(Lane::A1)[0].len();
4440 run(&mut s, json!({"op": "pitch", "clip": "A1#0", "semitones": 12})).expect("pitch up an octave");
4441 assert_eq!(s.clip_pitch_of(Lane::A1, 0), Some(12.0));
4442 assert_eq!(s.lane_clips(Lane::A1)[0].len(), len, "pitch keeps the clip's length");
4443 assert!(s.undo(), "pitch is one undo step");
4444 assert_eq!(s.clip_pitch_of(Lane::A1, 0), Some(0.0));
4445 run(&mut s, json!({"op": "pitch", "clip": "A1#0", "semitones": 0.37})).expect("a fraction sets");
4446 assert_eq!(s.clip_pitch_of(Lane::A1, 0), Some(0.37));
4447 assert!(s.undo());
4448 assert!(run(&mut s, json!({"op": "pitch", "clip": "A1#0", "semitones": 12.5})).is_err());
4449 assert!(run(&mut s, json!({"op": "pitch", "clip": "A1#0", "semitones": 13})).is_err());
4450 assert!(run(&mut s, json!({"op": "pitch", "clip": "A1#0"})).is_err());
4451 assert!(run(&mut s, json!({"op": "pitch", "clip": "V1#0", "semitones": 2})).is_err());
4452 assert_eq!(s.clip_pitch_of(Lane::A1, 0), Some(0.0), "refusals change nothing");
4453 }
4454}