edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | //! Generated clips and clip marks for the batched `edit` verb: `generator_add` (also a test tone on an audio lane) and |
| 2 | //! `generator_set` (a solid, gradient, countdown or colour bars as a clip), `adjustment_add` |
| 3 | //! (an adjustment layer), and `label` / `enable` (a clip's colour label and on/off switch). |
| 4 | //! |
| 5 | //! A generator is an ordinary clip on a video lane, so trim, move, grade and effects reach it |
| 6 | //! through the existing ops. [`apply`] returns `None` for an op that is not one of these. |
| 7 | |
| 8 | use engine::generate::{Form, Gen, Kind}; |
| 9 | use engine::project::{label_by_name, label_name, Lane, LaneKind, LABELS}; |
| 10 | use engine::PlaybackSession; |
| 11 | use serde_json::Value; |
| 12 | |
| 13 | use super::edit::{check_unlocked, clip_addr, length}; |
| 14 | use super::edit_fx::Applied; |
| 15 | use crate::parse; |
| 16 | |
| 17 | |
| 18 | pub fn apply(s: &mut PlaybackSession, op: &Value, fps: f64, tones: Option<&std::path::Path>) -> Option<Result<Applied, String>> { |
| 19 | let name = op.get("op")?.as_str()?; |
| 20 | Some(match name { |
| 21 | "generator_add" => generator_add(s, op, fps, tones), |
| 22 | "generator_set" => generator_set(s, op), |
| 23 | "adjustment_add" => adjustment_add(s, op, fps), |
| 24 | "label" => label(s, op), |
| 25 | "enable" => enable(s, op), |
| 26 | _ => return None, |
| 27 | }) |
| 28 | } |
| 29 | |
| 30 | fn str_arg<'a>(op: &'a Value, key: &str) -> Result<Option<&'a str>, String> { |
| 31 | match op.get(key) { |
| 32 | None | Some(Value::Null) => Ok(None), |
| 33 | Some(Value::String(t)) => Ok(Some(t.as_str())), |
| 34 | Some(v) => Err(format!("`{key}` must be a string, got {}", parse::kind_of(v))), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// `#ff3366` or `ff3366` as 0xRRGGBB. |
| 39 | fn colour(who: &str, key: &str, text: &str) -> Result<u32, String> { |
| 40 | let t = text.trim().trim_start_matches('#'); |
| 41 | if t.len() == 6 |
| 42 | && let Ok(v) = u32::from_str_radix(t, 16) |
| 43 | { |
| 44 | return Ok(v); |
| 45 | } |
| 46 | Err(format!("{who}: `{key}` {text:?} is not a colour; give six hex digits such as \"#ff3366\"")) |
| 47 | } |
| 48 | |
| 49 | fn hex(v: u32) -> String { |
| 50 | format!("#{v:06x}") |
| 51 | } |
| 52 | |
| 53 | /// Plain words for a generator, as the listings show it. |
| 54 | pub fn describe(g: &Gen) -> String { |
| 55 | match g.kind { |
| 56 | Kind::Solid { rgb } => format!("generator solid {}", hex(rgb)), |
| 57 | Kind::Gradient { a, b, angle } => format!("generator gradient {} to {} at {angle} degrees", hex(a), hex(b)), |
| 58 | Kind::Countdown { from, .. } => format!("generator countdown from {from} s"), |
| 59 | Kind::Bars => "generator bars".to_string(), |
| 60 | Kind::Adjust => "adjustment layer".to_string(), |
| 61 | Kind::Shape(sh) => { |
| 62 | let paint = |c: Option<u32>| c.map_or("none".to_string(), hex); |
| 63 | match sh.form { |
| 64 | Form::Rectangle => format!("shape rectangle fill {} stroke {} width {} radius {}", paint(sh.fill), paint(sh.stroke), sh.width, sh.radius), |
| 65 | Form::Ellipse => format!("shape ellipse fill {} stroke {} width {}", paint(sh.fill), paint(sh.stroke), sh.width), |
| 66 | Form::Line | Form::Arrow => format!("shape {} stroke {} width {}", sh.form.name(), paint(sh.stroke), sh.width), |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Which of the params a kind takes; any other given param is refused by name. |
| 73 | fn takes(kind: &str) -> &'static [&'static str] { |
| 74 | match kind { |
| 75 | "solid" => &["color"], |
| 76 | "gradient" => &["color", "color2", "angle"], |
| 77 | "countdown" => &["from"], |
| 78 | "rectangle" => &["fill", "stroke", "width", "radius"], |
| 79 | "ellipse" => &["fill", "stroke", "width"], |
| 80 | "line" | "arrow" => &["stroke", "width"], |
| 81 | _ => &[], |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// Merges the params in `op` onto `g`, refusing a param the kind does not take. |
| 86 | fn with_params(who: &str, op: &Value, mut g: Gen) -> Result<(Gen, usize), String> { |
| 87 | let kind = g.kind.name(); |
| 88 | let mut n = 0; |
| 89 | for key in ["color", "color2", "angle", "from", "fill", "stroke", "width", "radius"] { |
| 90 | if matches!(op.get(key), None | Some(Value::Null)) { |
| 91 | continue; |
| 92 | } |
| 93 | if !takes(kind).contains(&key) { |
| 94 | let ok = takes(kind); |
| 95 | let hint = if ok.is_empty() { format!("{kind} takes no params") } else { format!("{kind} takes {}", ok.join(", ")) }; |
| 96 | return Err(format!("{who}: `{key}` does not apply to {kind}; {hint}")); |
| 97 | } |
| 98 | n += 1; |
| 99 | } |
| 100 | match &mut g.kind { |
| 101 | Kind::Solid { rgb } => { |
| 102 | if let Some(c) = str_arg(op, "color")? { |
| 103 | *rgb = colour(who, "color", c)?; |
| 104 | } |
| 105 | } |
| 106 | Kind::Gradient { a, b, angle } => { |
| 107 | if let Some(c) = str_arg(op, "color")? { |
| 108 | *a = colour(who, "color", c)?; |
| 109 | } |
| 110 | if let Some(c) = str_arg(op, "color2")? { |
| 111 | *b = colour(who, "color2", c)?; |
| 112 | } |
| 113 | if let Some(v) = op.get("angle").filter(|v| !v.is_null()) { |
| 114 | let d = v.as_f64().ok_or_else(|| format!("{who}: `angle` must be a number of degrees, got {}", parse::kind_of(v)))?; |
| 115 | if !(0.0..360.0).contains(&d) { |
| 116 | return Err(format!("{who}: `angle` {d} is out of range 0–359 (0 is left to right, 90 top to bottom)")); |
| 117 | } |
| 118 | *angle = d.round() as u16 % 360; |
| 119 | } |
| 120 | } |
| 121 | Kind::Countdown { from, .. } => { |
| 122 | if let Some(v) = op.get("from").filter(|v| !v.is_null()) { |
| 123 | let f = v.as_f64().ok_or_else(|| format!("{who}: `from` must be a number of seconds, got {}", parse::kind_of(v)))?; |
| 124 | if f.fract() != 0.0 || !(1.0..=3600.0).contains(&f) { |
| 125 | return Err(format!("{who}: `from` {f} must be a whole number of seconds, 1–3600")); |
| 126 | } |
| 127 | *from = f as u16; |
| 128 | } |
| 129 | } |
| 130 | Kind::Shape(sh) => { |
| 131 | let paint = |key: &str| -> Result<Option<Option<u32>>, String> { |
| 132 | Ok(match str_arg(op, key)? { |
| 133 | None => None, |
| 134 | Some(t) if t.trim().eq_ignore_ascii_case("none") => Some(None), |
| 135 | Some(t) => Some(Some(colour(who, key, t)?)), |
| 136 | }) |
| 137 | }; |
| 138 | let whole = |key: &str, max: f64| -> Result<Option<u16>, String> { |
| 139 | let Some(v) = op.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; |
| 140 | let f = v.as_f64().ok_or_else(|| format!("{who}: `{key}` must be a number of pixels, got {}", parse::kind_of(v)))?; |
| 141 | if f.fract() != 0.0 || !(0.0..=max).contains(&f) { |
| 142 | return Err(format!("{who}: `{key}` {f} must be a whole number of pixels, 0–{max}")); |
| 143 | } |
| 144 | Ok(Some(f as u16)) |
| 145 | }; |
| 146 | if let Some(p) = paint("fill")? { |
| 147 | sh.fill = p; |
| 148 | } |
| 149 | if let Some(p) = paint("stroke")? { |
| 150 | sh.stroke = p; |
| 151 | } |
| 152 | if let Some(v) = whole("width", 400.0)? { |
| 153 | sh.width = v; |
| 154 | } |
| 155 | if let Some(v) = whole("radius", 2000.0)? { |
| 156 | sh.radius = v; |
| 157 | } |
| 158 | if sh.fill.is_none() && (sh.stroke.is_none() || sh.width == 0 && sh.form.fills()) { |
| 159 | return Err(format!("{who}: a shape needs something to paint: a fill, or a stroke with a width above 0")); |
| 160 | } |
| 161 | if !sh.form.fills() && sh.stroke.is_none() { |
| 162 | return Err(format!("{who}: a {} is all stroke; `stroke` cannot be none", sh.form.name())); |
| 163 | } |
| 164 | if !sh.form.fills() && sh.width == 0 { |
| 165 | return Err(format!("{who}: a {} needs a `width` above 0", sh.form.name())); |
| 166 | } |
| 167 | } |
| 168 | Kind::Bars | Kind::Adjust => {} |
| 169 | } |
| 170 | Ok((g, n)) |
| 171 | } |
| 172 | |
| 173 | /// The video lane an op names; `None` when it does not name one. |
| 174 | fn named_video_lane(s: &PlaybackSession, who: &str, op: &Value) -> Result<Option<Lane>, String> { |
| 175 | let Some(raw) = str_arg(op, "lane")? else { return Ok(None) }; |
| 176 | let lane = parse::lane(raw)?; |
| 177 | if lane.kind != LaneKind::Video { |
| 178 | return Err(format!("{who}: {raw} is not a video lane; a generated clip goes on a video lane (V1..)")); |
| 179 | } |
| 180 | if !s.lanes().contains(&lane) { |
| 181 | let names: Vec<String> = s.lanes().into_iter().map(parse::lane_name).collect(); |
| 182 | return Err(format!("{who}: {raw} is not a lane on this timeline; the lanes are {}; add one with lane_add {{kind:\"video\"}}", names.join(", "))); |
| 183 | } |
| 184 | check_unlocked(s, &[lane])?; |
| 185 | Ok(Some(lane)) |
| 186 | } |
| 187 | |
| 188 | /// Places `g` on `lane` and returns the reply line and the new clip. |
| 189 | fn place(s: &mut PlaybackSession, who: &str, op: &Value, fps: f64, lane: Lane, g: Gen, note: &str) -> Result<Applied, String> { |
| 190 | let end = parse::session_end(s); |
| 191 | let at = match super::edit::opt_time(op, "at", fps, end)? { |
| 192 | Some(a) => a, |
| 193 | None => s.lane_clips(lane).last().map_or(0, |c| c.end()), |
| 194 | }; |
| 195 | let frames = match length(op, "duration", fps)? { |
| 196 | Some(0) => return Err(format!("{who}: `duration` must be more than 0")), |
| 197 | Some(f) => Some(f), |
| 198 | None => None, |
| 199 | }; |
| 200 | let secs = frames.map(|f| parse::secs(f, fps)); |
| 201 | let placed = s.place_generated(g, parse::secs(at, fps), secs, Some(lane)).map_err(|e| format!("{who}: {e}"))?; |
| 202 | if !placed { |
| 203 | return Err(format!("{who}: the clip did not place at {} on {}", parse::tc(at, fps), parse::lane_name(lane))); |
| 204 | } |
| 205 | let idx = s |
| 206 | .lane_clips(lane) |
| 207 | .iter() |
| 208 | .position(|c| c.start == at) |
| 209 | .ok_or_else(|| format!("{who}: the new clip is not at {}", parse::tc(at, fps)))?; |
| 210 | if let Some(scale) = g.default_scale() { |
| 211 | s.set_transform(lane, idx, Some(engine::transform::TransformParams { scale, ..Default::default() })); |
| 212 | } |
| 213 | let c = &s.lane_clips(lane)[idx]; |
| 214 | let (start, len) = (c.start, c.end() - c.start); |
| 215 | let addr = parse::addr(lane, start); |
| 216 | Ok(Applied { text: format!("{who} → {addr} ({}) for {}{note}", describe(&g), parse::tc(len, fps)), touched: vec![(lane, start)] }) |
| 217 | } |
| 218 | |
| 219 | /// `generator_add {kind: solid|gradient|countdown|bars|rectangle|ellipse|line|arrow, color?, color2?, angle?, from?, fill?, stroke?, width?, radius?, lane?=V1, at?, duration?=5s}`. |
| 220 | fn generator_add(s: &mut PlaybackSession, op: &Value, fps: f64, tones: Option<&std::path::Path>) -> Result<Applied, String> { |
| 221 | let kind = str_arg(op, "kind")?.ok_or("generator_add: missing `kind`: solid, gradient, countdown, bars, tone, rectangle, ellipse, line or arrow")?; |
| 222 | if kind == "tone" { |
| 223 | return tone_add(s, op, fps, tones); |
| 224 | } |
| 225 | let who = format!("generator_add {kind}"); |
| 226 | if !matches!(kind, "solid" | "gradient" | "countdown" | "bars" | "rectangle" | "ellipse" | "line" | "arrow") { |
| 227 | return Err(format!("generator_add: `{kind}` is not a kind; use solid, gradient, countdown, bars, tone, rectangle, ellipse, line or arrow (adjustment_add makes an adjustment layer)")); |
| 228 | } |
| 229 | let base = s.generator_named(kind).ok_or_else(|| format!("generator_add: `{kind}` is not a kind"))?; |
| 230 | let (g, _) = with_params(&who, op, base)?; |
| 231 | let lane = named_video_lane(s, &who, op)?.unwrap_or(Lane::V1); |
| 232 | place(s, &who, op, fps, lane, g, "") |
| 233 | } |
| 234 | |
| 235 | /// `generator_add {kind: "tone", hz?=1000, level?=-20, lane?=A1, at?, duration?=10s}`: a test tone, |
| 236 | /// a sine at `hz` whose RMS is `level` dBFS, on an audio lane. The length is a whole number of seconds, rounded up; the default is ten. |
| 237 | fn tone_add(s: &mut PlaybackSession, op: &Value, fps: f64, tones: Option<&std::path::Path>) -> Result<Applied, String> { |
| 238 | let who = "generator_add tone"; |
| 239 | for key in ["color", "color2", "angle", "from", "fill", "stroke", "width", "radius"] { |
| 240 | if !matches!(op.get(key), None | Some(Value::Null)) { |
| 241 | return Err(format!("{who}: `{key}` does not apply to tone; tone takes hz and level")); |
| 242 | } |
| 243 | } |
| 244 | let number = |key: &str, default: f64| -> Result<f64, String> { |
| 245 | match op.get(key) { |
| 246 | None | Some(Value::Null) => Ok(default), |
| 247 | Some(v) => v.as_f64().ok_or_else(|| format!("{who}: `{key}` must be a number, got {}", parse::kind_of(v))), |
| 248 | } |
| 249 | }; |
| 250 | let hz = number("hz", 1000.0)?; |
| 251 | let level = number("level", -20.0)?; |
| 252 | if !(20.0..=20_000.0).contains(&hz) { |
| 253 | return Err(format!("{who}: `hz` {hz} is out of range 20–20000")); |
| 254 | } |
| 255 | if !(-60.0..=-3.0).contains(&level) { |
| 256 | return Err(format!("{who}: `level` {level} is out of range −60 to −3 dBFS")); |
| 257 | } |
| 258 | let lane = match str_arg(op, "lane")? { |
| 259 | None => Lane::A1, |
| 260 | Some(raw) => { |
| 261 | let lane = parse::lane(raw)?; |
| 262 | if lane.kind != LaneKind::Audio { |
| 263 | return Err(format!("{who}: {raw} is not an audio lane; a tone goes on an audio lane (A1..)")); |
| 264 | } |
| 265 | if !s.lanes().contains(&lane) { |
| 266 | return Err(format!("{who}: {raw} is not a lane on this timeline")); |
| 267 | } |
| 268 | check_unlocked(s, &[lane])?; |
| 269 | lane |
| 270 | } |
| 271 | }; |
| 272 | let end = parse::session_end(s); |
| 273 | let at = match super::edit::opt_time(op, "at", fps, end)? { |
| 274 | Some(a) => a, |
| 275 | None => s.lane_clips(lane).last().map_or(0, |c| c.end()), |
| 276 | }; |
| 277 | let secs = match length(op, "duration", fps)? { |
| 278 | Some(0) => return Err(format!("{who}: `duration` must be more than 0")), |
| 279 | Some(f) => (f as f64 / fps).ceil().clamp(1.0, 600.0) as u32, |
| 280 | None => engine::generate::TONE_SECS, |
| 281 | }; |
| 282 | let tone = engine::generate::Tone::new(hz.round() as u32, level.round() as i32); |
| 283 | let dir = tones.ok_or_else(|| format!("{who}: there is no data folder to keep the tone in"))?; |
| 284 | let placed = s.place_tone(tone, parse::secs(at, fps), secs, Some(lane), dir).map_err(|e| format!("{who}: {e}"))?; |
| 285 | if !placed { |
| 286 | return Err(format!("{who}: the clip did not place at {} on {}", parse::tc(at, fps), parse::lane_name(lane))); |
| 287 | } |
| 288 | let idx = s |
| 289 | .lane_clips(lane) |
| 290 | .iter() |
| 291 | .position(|c| c.start == at) |
| 292 | .ok_or_else(|| format!("{who}: the new clip is not at {}", parse::tc(at, fps)))?; |
| 293 | let c = &s.lane_clips(lane)[idx]; |
| 294 | let (start, len) = (c.start, c.end() - c.start); |
| 295 | let addr = parse::addr(lane, start); |
| 296 | Ok(Applied { |
| 297 | text: format!("{who} → {addr} (sine {} Hz at {} dBFS RMS) for {}", tone.hz, tone.dbfs, parse::tc(len, fps)), |
| 298 | touched: vec![(lane, start)], |
| 299 | }) |
| 300 | } |
| 301 | |
| 302 | /// `adjustment_add {lane?=V2, at?, duration?=5s}`. With no lane, V2 -- added when the timeline has only V1. |
| 303 | fn adjustment_add(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> { |
| 304 | let who = "adjustment_add"; |
| 305 | let (lane, note) = match named_video_lane(s, who, op)? { |
| 306 | Some(l) => (l, String::new()), |
| 307 | None => { |
| 308 | let v2 = Lane::new(LaneKind::Video, 1); |
| 309 | if s.lanes().contains(&v2) { |
| 310 | check_unlocked(s, &[v2])?; |
| 311 | (v2, String::new()) |
| 312 | } else { |
| 313 | let l = s.add_lane(LaneKind::Video); |
| 314 | let note = format!("; added lane {} for it", parse::lane_name(l)); |
| 315 | (l, note) |
| 316 | } |
| 317 | } |
| 318 | }; |
| 319 | let g = s.generator_named("adjust").ok_or("adjustment_add: no adjustment layer")?; |
| 320 | place(s, who, op, fps, lane, g, ¬e) |
| 321 | } |
| 322 | |
| 323 | /// `generator_set {clip, color?, color2?, angle?, from?, fill?, stroke?, width?, radius?}`: params merged onto the generator clip. |
| 324 | fn generator_set(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 325 | let raw = str_arg(op, "clip")?.ok_or("generator_set: missing `clip`: a generator clip address such as V2@0")?; |
| 326 | let who = format!("generator_set {raw}"); |
| 327 | let (lane, idx) = clip_addr(s, raw)?; |
| 328 | check_unlocked(s, &[lane])?; |
| 329 | let Some(cur) = s.generator_of(lane, idx) else { |
| 330 | return Err(format!("{who}: {raw} is not a generator clip; it plays a file. generator_set changes a clip made by generator_add")); |
| 331 | }; |
| 332 | let (g, n) = with_params(&who, op, cur)?; |
| 333 | if n == 0 { |
| 334 | let ok = takes(cur.kind.name()); |
| 335 | return Err(if ok.is_empty() { |
| 336 | format!("{who}: {} has no params to change", describe(&cur)) |
| 337 | } else { |
| 338 | format!("{who}: give at least one of {}", ok.join(", ")) |
| 339 | }); |
| 340 | } |
| 341 | let start = s.lane_clips(lane)[idx].start; |
| 342 | if g == cur { |
| 343 | return Ok(Applied { text: format!("{who} → {} (unchanged)", describe(&g)), touched: vec![(lane, start)] }); |
| 344 | } |
| 345 | if !s.set_generator(lane, idx, g) { |
| 346 | return Err(format!("{who}: the engine refused it")); |
| 347 | } |
| 348 | Ok(Applied { text: format!("{who} → {}", describe(&g)), touched: vec![(lane, start)] }) |
| 349 | } |
| 350 | |
| 351 | /// The clip addresses of `clip` or `clips`, resolved to (lane, index, address as written). |
| 352 | fn clips_arg(s: &PlaybackSession, who: &str, op: &Value) -> Result<Vec<(Lane, usize, String)>, String> { |
| 353 | let raws: Vec<String> = match (op.get("clip"), op.get("clips")) { |
| 354 | (Some(Value::String(c)), None | Some(Value::Null)) => vec![c.clone()], |
| 355 | (None | Some(Value::Null), Some(Value::Array(a))) => { |
| 356 | let mut v = Vec::new(); |
| 357 | for x in a { |
| 358 | v.push(x.as_str().ok_or_else(|| format!("{who}: `clips` lists addresses such as V1@0"))?.to_string()); |
| 359 | } |
| 360 | v |
| 361 | } |
| 362 | (Some(_), Some(c)) if !c.is_null() => return Err(format!("{who}: give clip or clips, not both")), |
| 363 | _ => return Err(format!("{who}: missing `clip` (an address such as V1@0) or `clips` (a list of them)")), |
| 364 | }; |
| 365 | if raws.is_empty() { |
| 366 | return Err(format!("{who}: `clips` is empty")); |
| 367 | } |
| 368 | let mut out = Vec::new(); |
| 369 | for raw in raws { |
| 370 | let (lane, idx) = clip_addr(s, &raw)?; |
| 371 | if lane.kind == LaneKind::Subtitle { |
| 372 | return Err(format!("{who}: {raw} is a caption; labels and the on/off switch are for picture and sound clips")); |
| 373 | } |
| 374 | check_unlocked(s, &[lane])?; |
| 375 | out.push((lane, idx, raw)); |
| 376 | } |
| 377 | Ok(out) |
| 378 | } |
| 379 | |
| 380 | fn label_list() -> String { |
| 381 | LABELS.iter().map(|l| l.0).collect::<Vec<_>>().join(", ") |
| 382 | } |
| 383 | |
| 384 | /// `label {clip | clips, value: <name>|1..8|none}`. |
| 385 | fn label(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 386 | let who = "label"; |
| 387 | let text = match op.get("value") { |
| 388 | Some(Value::String(t)) => t.clone(), |
| 389 | Some(Value::Number(n)) => n.to_string(), |
| 390 | None | Some(Value::Null) => return Err(format!("label: missing `value`: a label name ({}), a number 1–8, or none", label_list())), |
| 391 | Some(v) => return Err(format!("label: `value` must be a name or a number, got {}", parse::kind_of(v))), |
| 392 | }; |
| 393 | let n = label_by_name(&text).ok_or_else(|| format!("label: `{text}` is not a label; use one of {}, a number 1–8, or none", label_list()))?; |
| 394 | let clips = clips_arg(s, who, op)?; |
| 395 | let shown = label_name(n).unwrap_or("none"); |
| 396 | let mut touched = Vec::new(); |
| 397 | let mut addrs = Vec::new(); |
| 398 | for (lane, idx, raw) in &clips { |
| 399 | let start = s.lane_clips(*lane)[*idx].start; |
| 400 | if s.mark_of(*lane, *idx).label != n && !s.set_label(*lane, *idx, n) { |
| 401 | return Err(format!("label {raw}: the engine refused it")); |
| 402 | } |
| 403 | touched.push((*lane, start)); |
| 404 | addrs.push(raw.clone()); |
| 405 | } |
| 406 | Ok(Applied { text: format!("label {} → {shown}", addrs.join(", ")), touched }) |
| 407 | } |
| 408 | |
| 409 | /// `enable {clip | clips, on: true|false}`. |
| 410 | fn enable(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 411 | let who = "enable"; |
| 412 | let on = match op.get("on") { |
| 413 | Some(Value::Bool(b)) => *b, |
| 414 | None | Some(Value::Null) => return Err("enable: missing `on`: true to play the clip, false to switch it off".into()), |
| 415 | Some(v) => return Err(format!("enable: `on` must be true or false, got {}", parse::kind_of(v))), |
| 416 | }; |
| 417 | let clips = clips_arg(s, who, op)?; |
| 418 | let mut touched = Vec::new(); |
| 419 | let mut addrs = Vec::new(); |
| 420 | for (lane, idx, raw) in &clips { |
| 421 | let start = s.lane_clips(*lane)[*idx].start; |
| 422 | if s.mark_of(*lane, *idx).off == on && !s.set_enabled(*lane, *idx, on) { |
| 423 | return Err(format!("enable {raw}: the engine refused it")); |
| 424 | } |
| 425 | touched.push((*lane, start)); |
| 426 | addrs.push(raw.clone()); |
| 427 | } |
| 428 | Ok(Applied { text: format!("enable {} → {}", addrs.join(", "), if on { "on" } else { "off (disabled)" }), touched }) |
| 429 | } |
| 430 | |
| 431 | #[cfg(test)] |
| 432 | mod tests { |
| 433 | use serde_json::json; |
| 434 | |
| 435 | use super::*; |
| 436 | use crate::server::{Reply, Server}; |
| 437 | use crate::testutil::TestDir; |
| 438 | |
| 439 | fn server() -> Server { |
| 440 | engine::ao::set_silent_output(); |
| 441 | let mut srv = Server::new(); |
| 442 | srv.session = Some(PlaybackSession::empty(320, 180, 30.0).expect("empty timeline")); |
| 443 | srv |
| 444 | } |
| 445 | |
| 446 | fn call(srv: &mut Server, name: &str, args: Value) -> Reply { |
| 447 | let tool = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool exists"); |
| 448 | (tool.run)(srv, &args) |
| 449 | } |
| 450 | |
| 451 | fn ed(srv: &mut Server, ops: Value) -> Reply { |
| 452 | call(srv, "edit", json!({ "ops": ops })) |
| 453 | } |
| 454 | |
| 455 | fn ok(srv: &mut Server, ops: Value) -> String { |
| 456 | let r = ed(srv, ops); |
| 457 | assert!(!r.is_error, "{}", r.text); |
| 458 | r.text |
| 459 | } |
| 460 | |
| 461 | fn err(srv: &mut Server, ops: Value) -> String { |
| 462 | let r = ed(srv, ops); |
| 463 | assert!(r.is_error, "expected a refusal, got {}", r.text); |
| 464 | r.text |
| 465 | } |
| 466 | |
| 467 | fn sess(srv: &Server) -> &PlaybackSession { |
| 468 | srv.session.as_ref().unwrap() |
| 469 | } |
| 470 | |
| 471 | fn frame(srv: &mut Server, at: &str) -> String { |
| 472 | let r = call(srv, "frame", json!({"at": at})); |
| 473 | assert!(!r.is_error, "{}", r.text); |
| 474 | r.images.first().expect("a picture").1.clone() |
| 475 | } |
| 476 | |
| 477 | #[test] |
| 478 | fn generator_add_places_each_kind_and_lists_it() { |
| 479 | let mut srv = server(); |
| 480 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "solid", "color": "#ff3366"}])); |
| 481 | assert!(t.contains("V1@0") && t.contains("generator solid #ff3366") && t.contains("150f (5.000s)"), "{t}"); |
| 482 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "gradient", "color": "000000", "color2": "#ffffff", "angle": 45, "duration": "2s"}])); |
| 483 | assert!(t.contains("V1@150") && t.contains("gradient #000000 to #ffffff at 45 degrees") && t.contains("60f"), "{t}"); |
| 484 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "countdown", "from": 3}])); |
| 485 | assert!(t.contains("V1@210") && t.contains("countdown from 3 s") && t.contains("90f"), "{t}"); |
| 486 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "bars", "at": "20s", "duration": 1}])); |
| 487 | assert!(t.contains("V1@600") && t.contains("generator bars"), "{t}"); |
| 488 | assert_eq!(sess(&srv).generator_of(Lane::V1, 0).unwrap().kind, Kind::Solid { rgb: 0xff3366 }); |
| 489 | |
| 490 | let tl = call(&mut srv, "timeline", json!({})); |
| 491 | assert!(!tl.is_error, "{}", tl.text); |
| 492 | assert!(tl.text.contains("generator solid #ff3366") && tl.text.contains("generator countdown from 3 s"), "{}", tl.text); |
| 493 | assert!(!tl.text.contains("OFFLINE"), "{}", tl.text); |
| 494 | let info = call(&mut srv, "clip_info", json!({"clip": "V1@0"})); |
| 495 | assert!(info.text.contains("generator solid #ff3366") && !info.text.contains("edith-gen"), "{}", info.text); |
| 496 | let st = call(&mut srv, "project_status", json!({})); |
| 497 | assert!(!st.text.contains("OFFLINE") && !st.text.contains("offline"), "{}", st.text); |
| 498 | let ml = call(&mut srv, "media_list", json!({})); |
| 499 | assert!(!ml.text.contains("OFFLINE"), "{}", ml.text); |
| 500 | } |
| 501 | |
| 502 | #[test] |
| 503 | fn a_tone_goes_on_an_audio_lane_ten_seconds_long() { |
| 504 | // The tone's file goes under a temporary data folder, never the user's own. |
| 505 | let data = TestDir::new("tone-data"); |
| 506 | let mut srv = server(); |
| 507 | srv.data_home = Some(data.path().to_path_buf()); |
| 508 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "tone"}])); |
| 509 | assert!(t.contains("A1@0") && t.contains("1000 Hz") && t.contains("-20 dBFS") && t.contains("300f"), "{t}"); |
| 510 | assert!(sess(&srv).lane_clips(Lane::A1).len() == 1 && sess(&srv).lane_clips(Lane::V1).is_empty()); |
| 511 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "tone", "hz": 440, "level": -12, "at": "12s", "duration": "2s"}])); |
| 512 | assert!(t.contains("A1@360") && t.contains("440 Hz") && t.contains("-12 dBFS") && t.contains("60f"), "{t}"); |
| 513 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "tone", "lane": "V1"}])).contains("not an audio lane")); |
| 514 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "tone", "level": 0}])).contains("out of range")); |
| 515 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "tone", "hz": 5}])).contains("out of range")); |
| 516 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "tone", "color": "#ffffff"}])).contains("does not apply to tone")); |
| 517 | } |
| 518 | |
| 519 | #[test] |
| 520 | fn templates_are_listed_and_project_new_starts_from_one() { |
| 521 | // Templates are read from a temporary data folder, never the user's own. |
| 522 | let dir = crate::testutil::TestDir::new("generated-template-new"); |
| 523 | let mut listing = Server::new(); |
| 524 | listing.data_home = Some(dir.path().to_path_buf()); |
| 525 | let listed = call(&mut listing, "templates", json!({})); |
| 526 | assert!(!listed.is_error, "{}", listed.text); |
| 527 | assert!(listed.text.contains("YouTube 1080p 30 (built-in)") && listed.text.contains("Square 1080 30 (built-in)"), "{}", listed.text); |
| 528 | let path = dir.path().join("short.edith"); |
| 529 | let r = call(&mut Server::new(), "project_new", json!({"path": path, "template": "Vertical 1080×1920 30"})); |
| 530 | assert!(!r.is_error, "{}", r.text); |
| 531 | assert!(r.text.contains("1080x1920 @30") && r.text.contains("started from template Vertical 1080×1920 30"), "{}", r.text); |
| 532 | assert!(r.text.contains("shorts_reels"), "{}", r.text); |
| 533 | let refused = call(&mut Server::new(), "project_new", json!({"path": dir.path().join("b.edith"), "template": "Square 1080 30", "fps": 25})); |
| 534 | assert!(refused.is_error && refused.text.contains("leave out resolution and fps"), "{}", refused.text); |
| 535 | let missing = call(&mut Server::new(), "project_new", json!({"path": dir.path().join("c.edith"), "template": "No such one"})); |
| 536 | assert!(missing.is_error && missing.text.contains("no template named"), "{}", missing.text); |
| 537 | } |
| 538 | |
| 539 | #[test] |
| 540 | fn shapes_are_added_set_and_refused_by_name() { |
| 541 | let mut srv = server(); |
| 542 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "rectangle", "fill": "#ff0000", "stroke": "#ffffff", "width": 6, "radius": 40, "duration": "2s"}])); |
| 543 | assert!(t.contains("shape rectangle fill #ff0000 stroke #ffffff width 6 radius 40"), "{t}"); |
| 544 | assert!(sess(&srv).transform_of(Lane::V1, 0).is_some_and(|t| t.scale < 1.0), "a shape lands smaller than the frame"); |
| 545 | let t = ok(&mut srv, json!([{"op": "generator_set", "clip": "V1@0", "fill": "none"}])); |
| 546 | assert!(t.contains("fill none stroke #ffffff"), "{t}"); |
| 547 | let t = ok(&mut srv, json!([{"op": "generator_add", "kind": "arrow", "stroke": "#ffd600", "width": 20}])); |
| 548 | assert!(t.contains("shape arrow stroke #ffd600 width 20"), "{t}"); |
| 549 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "line", "fill": "#fff"}])).contains("does not apply to line")); |
| 550 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "ellipse", "radius": 5}])).contains("does not apply to ellipse")); |
| 551 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "arrow", "width": 0}])).contains("above 0")); |
| 552 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "rectangle", "fill": "none"}])).contains("something to paint")); |
| 553 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "rectangle", "width": 401}])).contains("0–400")); |
| 554 | } |
| 555 | |
| 556 | #[test] |
| 557 | fn generator_add_refusals() { |
| 558 | let mut srv = server(); |
| 559 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "plasma"}])).contains("not a kind")); |
| 560 | assert!(err(&mut srv, json!([{"op": "generator_add"}])).contains("missing `kind`")); |
| 561 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "solid", "color": "pink"}])).contains("not a colour")); |
| 562 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "gradient", "color2": "#12345"}])).contains("color2")); |
| 563 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "gradient", "angle": 360}])).contains("out of range")); |
| 564 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "solid", "angle": 10}])).contains("does not apply to solid")); |
| 565 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "countdown", "from": 0}])).contains("1–3600")); |
| 566 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "bars", "duration": 0}])).contains("more than 0")); |
| 567 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "bars", "lane": "V7"}])).contains("not a lane")); |
| 568 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "bars", "lane": "A1"}])).contains("not a video lane")); |
| 569 | assert!(err(&mut srv, json!([{"op": "generator_add", "kind": "adjust"}])).contains("not a kind")); |
| 570 | assert!(sess(&srv).lane_clips(Lane::V1).is_empty(), "refusals change nothing"); |
| 571 | } |
| 572 | |
| 573 | #[test] |
| 574 | fn generator_set_changes_params_and_refuses_what_is_not_a_generator() { |
| 575 | let mut srv = server(); |
| 576 | ok(&mut srv, json!([{"op": "generator_add", "kind": "solid", "color": "#112233"}, {"op": "adjustment_add"}])); |
| 577 | let t = ok(&mut srv, json!([{"op": "generator_set", "clip": "V1@0", "color": "#ff0000"}])); |
| 578 | assert!(t.contains("generator solid #ff0000"), "{t}"); |
| 579 | assert_eq!(sess(&srv).lane_clips(Lane::V1)[0].end(), 150, "place and length kept"); |
| 580 | let t = ok(&mut srv, json!([{"op": "generator_set", "clip": "V1@0", "color": "#ff0000"}])); |
| 581 | assert!(t.contains("unchanged"), "{t}"); |
| 582 | assert!(err(&mut srv, json!([{"op": "generator_set", "clip": "V1@0"}])).contains("give at least one of color")); |
| 583 | assert!(err(&mut srv, json!([{"op": "generator_set", "clip": "V1@0", "from": 4}])).contains("does not apply")); |
| 584 | assert!(err(&mut srv, json!([{"op": "generator_set", "clip": "V2@0", "color": "#fff000"}])).contains("does not apply")); |
| 585 | assert!(err(&mut srv, json!([{"op": "generator_set", "clip": "V1@0", "color": "nope"}])).contains("not a colour")); |
| 586 | // a clip that plays a file is not a generator: audio lanes have none, so A1 is refused as a lane |
| 587 | let r = call(&mut srv, "edit", json!({"ops": [{"op": "generator_set", "clip": "A1@0", "color": "#fff000"}]})); |
| 588 | assert!(r.is_error, "{}", r.text); |
| 589 | } |
| 590 | |
| 591 | #[test] |
| 592 | fn adjustment_add_makes_v2_and_grades_what_is_beneath() { |
| 593 | let mut srv = server(); |
| 594 | ok(&mut srv, json!([{"op": "generator_add", "kind": "solid", "color": "#808080"}])); |
| 595 | let before = frame(&mut srv, "1s"); |
| 596 | let t = ok(&mut srv, json!([{"op": "adjustment_add", "at": "0s", "duration": "3s"}])); |
| 597 | assert!(t.contains("V2@0") && t.contains("adjustment layer") && t.contains("added lane V2"), "{t}"); |
| 598 | assert!(sess(&srv).generator_of(Lane::new(LaneKind::Video, 1), 0).unwrap().is_adjust()); |
| 599 | let flat = frame(&mut srv, "1s"); |
| 600 | assert_eq!(before, flat, "an ungraded adjustment layer changes nothing"); |
| 601 | ok(&mut srv, json!([{"op": "color", "clip": "V2@0", "brightness": -0.6}])); |
| 602 | let graded = frame(&mut srv, "1s"); |
| 603 | assert_ne!(before, graded, "the layer grades the clip under it"); |
| 604 | ok(&mut srv, json!([{"op": "enable", "clip": "V2@0", "on": false}])); |
| 605 | assert_eq!(frame(&mut srv, "1s"), before, "off, the layer adjusts nothing"); |
| 606 | let t = ok(&mut srv, json!([{"op": "adjustment_add", "lane": "V2", "at": "5s", "duration": "1s"}])); |
| 607 | assert!(t.contains("V2@150") && !t.contains("added lane"), "{t}"); |
| 608 | assert!(err(&mut srv, json!([{"op": "adjustment_add", "lane": "V5"}])).contains("not a lane")); |
| 609 | let tl = call(&mut srv, "timeline", json!({})); |
| 610 | assert!(tl.text.contains("adjustment layer"), "{}", tl.text); |
| 611 | } |
| 612 | |
| 613 | #[test] |
| 614 | fn a_generator_clip_renders_and_a_disabled_clip_drops_out() { |
| 615 | let mut srv = server(); |
| 616 | ok(&mut srv, json!([{"op": "generator_add", "kind": "solid", "color": "#000000"}])); |
| 617 | let base = frame(&mut srv, "1s"); |
| 618 | ok(&mut srv, json!([{"op": "lane_add", "kind": "video"}, {"op": "generator_add", "kind": "solid", "color": "#ff0000", "lane": "V2", "at": "0s"}])); |
| 619 | let red = frame(&mut srv, "1s"); |
| 620 | assert_ne!(red, base, "the solid shows"); |
| 621 | ok(&mut srv, json!([{"op": "enable", "clip": "V2@0", "on": false}])); |
| 622 | assert_eq!(frame(&mut srv, "1s"), base, "a disabled clip is not drawn"); |
| 623 | let tl = call(&mut srv, "timeline", json!({})); |
| 624 | assert!(tl.text.contains("disabled"), "{}", tl.text); |
| 625 | let info = call(&mut srv, "clip_info", json!({"clip": "V2@0"})); |
| 626 | assert!(info.text.contains("disabled"), "{}", info.text); |
| 627 | ok(&mut srv, json!([{"op": "enable", "clip": "V2@0", "on": true}])); |
| 628 | assert_eq!(frame(&mut srv, "1s"), red); |
| 629 | } |
| 630 | |
| 631 | #[test] |
| 632 | fn label_and_enable_are_one_undo_step_each() { |
| 633 | let mut srv = server(); |
| 634 | ok(&mut srv, json!([ |
| 635 | {"op": "generator_add", "kind": "solid", "color": "#112233"}, |
| 636 | {"op": "generator_add", "kind": "bars"} |
| 637 | ])); |
| 638 | let depth = sess(&srv).undo_depth(); |
| 639 | let t = ok(&mut srv, json!([{"op": "label", "clips": ["V1@0", "V1#1"], "value": "rose"}])); |
| 640 | assert!(t.contains("V1@0, V1#1 → Rose"), "{t}"); |
| 641 | assert_eq!(sess(&srv).mark_of(Lane::V1, 1).label, 7); |
| 642 | ok(&mut srv, json!([{"op": "label", "clip": "V1@0", "value": 3}])); |
| 643 | assert_eq!(sess(&srv).mark_of(Lane::V1, 0).label, 3); |
| 644 | ok(&mut srv, json!([{"op": "label", "clip": "V1@0", "value": "none"}])); |
| 645 | assert_eq!(sess(&srv).mark_of(Lane::V1, 0).label, 0); |
| 646 | assert!(!call(&mut srv, "undo", json!({})).is_error); |
| 647 | assert_eq!(sess(&srv).mark_of(Lane::V1, 0).label, 3, "undo restores the label"); |
| 648 | assert!(!call(&mut srv, "undo", json!({})).is_error); |
| 649 | assert!(!call(&mut srv, "undo", json!({})).is_error); |
| 650 | assert_eq!(sess(&srv).mark_of(Lane::V1, 1).label, 0, "one undo took both labels off"); |
| 651 | assert_eq!(sess(&srv).undo_depth(), depth); |
| 652 | ok(&mut srv, json!([{"op": "label", "clip": "V1@0", "value": "Caribbean"}])); |
| 653 | let tl = call(&mut srv, "timeline", json!({})); |
| 654 | assert!(tl.text.contains("label Caribbean"), "{}", tl.text); |
| 655 | |
| 656 | let t = ok(&mut srv, json!([{"op": "enable", "clips": ["V1@0", "V1@150"], "on": false}])); |
| 657 | assert!(t.contains("V1@0, V1@150 → off"), "{t}"); |
| 658 | assert!(sess(&srv).mark_of(Lane::V1, 1).off); |
| 659 | assert!(!call(&mut srv, "undo", json!({})).is_error); |
| 660 | assert!(!sess(&srv).mark_of(Lane::V1, 0).off && !sess(&srv).mark_of(Lane::V1, 1).off, "one undo switched both back on"); |
| 661 | assert!(!call(&mut srv, "redo", json!({})).is_error); |
| 662 | assert!(sess(&srv).mark_of(Lane::V1, 0).off); |
| 663 | } |
| 664 | |
| 665 | #[test] |
| 666 | fn label_and_enable_refusals() { |
| 667 | let mut srv = server(); |
| 668 | ok(&mut srv, json!([{"op": "generator_add", "kind": "bars"}])); |
| 669 | let t = err(&mut srv, json!([{"op": "label", "clip": "V1@0", "value": "teal"}])); |
| 670 | assert!(t.contains("not a label") && t.contains("Violet"), "{t}"); |
| 671 | assert!(err(&mut srv, json!([{"op": "label", "clip": "V1@0", "value": 9}])).contains("not a label")); |
| 672 | assert!(err(&mut srv, json!([{"op": "label", "clip": "V1@0"}])).contains("missing `value`")); |
| 673 | assert!(err(&mut srv, json!([{"op": "label", "value": 1}])).contains("missing `clip`")); |
| 674 | assert!(err(&mut srv, json!([{"op": "label", "clip": "V1@99", "value": 1}])).contains("V1")); |
| 675 | assert!(err(&mut srv, json!([{"op": "enable", "clip": "V1@0"}])).contains("missing `on`")); |
| 676 | assert!(err(&mut srv, json!([{"op": "enable", "clip": "V1@0", "on": "no"}])).contains("true or false")); |
| 677 | assert!(err(&mut srv, json!([{"op": "enable", "clip": "V1@0", "clips": ["V1@0"], "on": true}])).contains("not both")); |
| 678 | assert_eq!(sess(&srv).mark_of(Lane::V1, 0).label, 0); |
| 679 | } |
| 680 | |
| 681 | #[test] |
| 682 | fn save_and_reopen_keep_generator_label_and_off() { |
| 683 | let td = TestDir::new("gens-roundtrip"); |
| 684 | let path = td.path().join("gens.edith"); |
| 685 | let mut srv = Server::new(); |
| 686 | let r = call(&mut srv, "project_new", json!({"path": path, "resolution": "320x180"})); |
| 687 | assert!(!r.is_error, "{}", r.text); |
| 688 | ok(&mut srv, json!([ |
| 689 | {"op": "generator_add", "kind": "gradient", "color": "#ff7a18", "color2": "#3a1c71", "angle": 90}, |
| 690 | {"op": "generator_add", "kind": "countdown", "from": 4}, |
| 691 | {"op": "adjustment_add", "at": "0s", "duration": "2s"}, |
| 692 | {"op": "label", "clip": "V1@0", "value": "Rose"}, |
| 693 | {"op": "enable", "clip": "V1@150", "on": false} |
| 694 | ])); |
| 695 | let r = call(&mut srv, "project_save", json!({})); |
| 696 | assert!(!r.is_error, "{}", r.text); |
| 697 | |
| 698 | let mut fresh = Server::new(); |
| 699 | let r = call(&mut fresh, "project_open", json!({"path": path})); |
| 700 | assert!(!r.is_error, "{}", r.text); |
| 701 | let s = fresh.session.as_ref().unwrap(); |
| 702 | assert_eq!(s.generator_of(Lane::V1, 0).unwrap().kind, Kind::Gradient { a: 0xff7a18, b: 0x3a1c71, angle: 90 }); |
| 703 | assert!(matches!(s.generator_of(Lane::V1, 1).unwrap().kind, Kind::Countdown { from: 4, .. })); |
| 704 | assert!(s.generator_of(Lane::new(LaneKind::Video, 1), 0).unwrap().is_adjust()); |
| 705 | assert_eq!(s.mark_of(Lane::V1, 0).label, 7); |
| 706 | assert!(s.mark_of(Lane::V1, 1).off && !s.mark_of(Lane::V1, 0).off); |
| 707 | let tl = call(&mut fresh, "timeline", json!({})); |
| 708 | assert!(tl.text.contains("label Rose") && tl.text.contains("disabled") && !tl.text.contains("OFFLINE"), "{}", tl.text); |
| 709 | } |
| 710 | } |