| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use engine::PlaybackSession; |
| 7 | use engine::project::Lane; |
| 8 | use serde_json::{Value, json}; |
| 9 | |
| 10 | use super::edit_fx::Applied; |
| 11 | use crate::parse; |
| 12 | use crate::server::{Reply, Server, Tool}; |
| 13 | |
| 14 | pub const NEST_OP_DOC: &str = "nest {clips:[addr,...], name?} — folds the picked clips (and their linked partners) into a new sequence and puts one compound clip where they were, on the lowest picked video lane and the lowest picked sound lane, linked when both exist; the picture and sound are unchanged. The clips keep their lanes (compacted) and their timing relative to the first. Refuses when a clip that is not picked sits between picked ones on a lane. One undo step. The new sequence is named `name` or Compound N; open it with sequence {action:\"switch\"}."; |
| 15 | pub const BREAK_APART_OP_DOC: &str = "break_apart {clips:[addr,...]} — the opposite of nest: each picked compound clip (and its linked partner) is replaced by the clips of its sequence, trimmed to the stretch the compound played, on the same lanes (extra lanes are made as needed). The sequence itself stays. Refuses when other clips are in the way. One undo step."; |
| 16 | pub const PLACE_SEQUENCE_OP_DOC: &str = "place_sequence {sequence, at, lane?=V1} — puts a sequence on a video lane at `at` as a compound clip (its sound goes on the first sound lane, linked). A sequence cannot hold itself or one that holds it (cycle: refused). A compound clip has no speed, ramp or reverse (refused); trims, splits, moves, fades and gain work as for any clip."; |
| 17 | |
| 18 | const DOC: &str = "Sequences: a project holds several named sequences (timelines) that share its size and frame rate; one is active and every other tool works on it. action: list (default) · new {name?} · rename {sequence, new_name} · duplicate {sequence, name?} · delete {sequence} · switch {sequence}. `sequence` is a name or the number list shows. new and duplicate do not switch; delete refuses the last sequence and one a compound clip plays; switching is not an undo step but new, rename, duplicate and delete are. A sequence can play inside another as a compound clip (edit ops nest, break_apart, place_sequence). timeline, edit, export_start and clip_info take an optional `sequence` to act on another one (edit leaves it active). The frame rate cannot change once there is more than one sequence."; |
| 19 | |
| 20 | pub fn tools() -> Vec<Tool> { |
| 21 | vec![Tool { name: "sequence", description: DOC, schema, run }] |
| 22 | } |
| 23 | |
| 24 | |
| 25 | pub fn prop() -> Value { |
| 26 | json!({ "type": ["string", "number"], "description": "A sequence by name or number (sequence {action:\"list\"}). Default: the active one." }) |
| 27 | } |
| 28 | |
| 29 | fn schema() -> Value { |
| 30 | json!({ |
| 31 | "type": "object", |
| 32 | "properties": { |
| 33 | "action": { "type": "string", "enum": ["list", "new", "rename", "duplicate", "delete", "switch"], "description": "Default list." }, |
| 34 | "sequence": { "type": ["string", "number"], "description": "The sequence to act on, by name or number." }, |
| 35 | "name": { "type": "string", "maxLength": 100, "description": "new and duplicate: the new sequence's name." }, |
| 36 | "new_name": { "type": "string", "maxLength": 100, "description": "rename: the new name." } |
| 37 | } |
| 38 | }) |
| 39 | } |
| 40 | |
| 41 | |
| 42 | pub fn resolve(s: &PlaybackSession, v: &Value) -> Result<u32, String> { |
| 43 | let all = s.sequences(); |
| 44 | let list = || all.iter().map(|q| format!("{} {}", q.id, q.name)).collect::<Vec<_>>().join(", "); |
| 45 | let by_id = |n: u64| u32::try_from(n).ok().filter(|n| all.iter().any(|q| q.id == *n)); |
| 46 | let found = match v { |
| 47 | Value::Number(n) => n.as_u64().and_then(by_id), |
| 48 | Value::String(t) => s.sequence_named(t).or_else(|| t.trim().parse::<u64>().ok().and_then(by_id)), |
| 49 | _ => return Err(format!("`sequence` must be a name or a number, got {}", parse::kind_of(v))), |
| 50 | }; |
| 51 | found.ok_or_else(|| format!("no sequence {v}; the sequences are: {}", list())) |
| 52 | } |
| 53 | |
| 54 | fn line(q: &engine::project::SequenceInfo, fps: f64) -> String { |
| 55 | let used = if q.used > 0 { format!(", played by {} compound clip(s)", q.used) } else { String::new() }; |
| 56 | format!("{}{} {} \"{}\" {}{used}", if q.active { "*" } else { " " }, "seq", q.id, q.name, parse::clock(q.frames, fps)) |
| 57 | } |
| 58 | |
| 59 | fn listing(s: &PlaybackSession) -> String { |
| 60 | let fps = parse::session_fps(s); |
| 61 | let rows: Vec<String> = s.sequences().iter().map(|q| line(q, fps)).collect(); |
| 62 | format!("{} sequence(s), * is active:\n{}", rows.len(), rows.join("\n")) |
| 63 | } |
| 64 | |
| 65 | fn run(srv: &mut Server, args: &Value) -> Reply { |
| 66 | let before = match srv.session_ref() { |
| 67 | Ok(s) => s.history_pushes(), |
| 68 | Err(r) => return r, |
| 69 | }; |
| 70 | let action = args.get("action").and_then(Value::as_str).unwrap_or("list"); |
| 71 | let text = |k: &str| args.get(k).and_then(Value::as_str); |
| 72 | let s = match srv.session() { |
| 73 | Ok(s) => s, |
| 74 | Err(r) => return r, |
| 75 | }; |
| 76 | let which = |s: &PlaybackSession| match args.get("sequence").filter(|v| !v.is_null()) { |
| 77 | Some(v) => resolve(s, v), |
| 78 | None => Err("missing argument `sequence`: a name or a number from sequence {action:\"list\"}".into()), |
| 79 | }; |
| 80 | let done: Result<String, String> = match action { |
| 81 | "list" => return Reply::ok(listing(s)), |
| 82 | "new" => s.new_sequence(text("name")).map_err(|e| e.to_string()).map(|id| { |
| 83 | format!("new sequence {id} \"{}\" (not switched to; sequence {{action:\"switch\", sequence:{id}}} opens it)", s.sequence_name(id).unwrap_or_default()) |
| 84 | }), |
| 85 | "rename" => which(s).and_then(|id| { |
| 86 | let name = text("new_name").ok_or("missing argument `new_name`")?; |
| 87 | s.rename_sequence(id, name).map_err(|e| e.to_string())?; |
| 88 | Ok(format!("sequence {id} is now \"{}\"", s.sequence_name(id).unwrap_or_default())) |
| 89 | }), |
| 90 | "duplicate" => which(s).and_then(|id| { |
| 91 | let copy = s.duplicate_sequence(id).map_err(|e| e.to_string())?; |
| 92 | if let Some(n) = text("name") { |
| 93 | s.rename_sequence(copy, n).map_err(|e| e.to_string())?; |
| 94 | } |
| 95 | Ok(format!("sequence {id} copied to {copy} \"{}\"", s.sequence_name(copy).unwrap_or_default())) |
| 96 | }), |
| 97 | "delete" => which(s).and_then(|id| { |
| 98 | let now = s.delete_sequence(id).map_err(|e| e.to_string())?; |
| 99 | Ok(format!("sequence {id} deleted; sequence {now} is active")) |
| 100 | }), |
| 101 | "switch" => which(s).and_then(|id| { |
| 102 | s.switch_sequence(id).map_err(|e| e.to_string())?; |
| 103 | Ok(format!("sequence {id} \"{}\" is active", s.sequence_name(id).unwrap_or_default())) |
| 104 | }), |
| 105 | other => Err(format!("unknown action `{other}`; list, new, rename, duplicate, delete or switch")), |
| 106 | }; |
| 107 | match done { |
| 108 | Ok(t) => { |
| 109 | super::project::note_pushes_as(srv, before, &format!("sequence {action}")); |
| 110 | Reply::ok(t) |
| 111 | } |
| 112 | Err(e) => Reply::err(format!("sequence {action}: {e}")), |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | pub fn enter(srv: &mut Server, args: &Value, keep: bool) -> Result<Option<u32>, Reply> { |
| 119 | let Some(v) = args.get("sequence").filter(|v| !v.is_null()) else { |
| 120 | return Ok(None); |
| 121 | }; |
| 122 | let s = srv.session()?; |
| 123 | let id = resolve(s, v).map_err(Reply::err)?; |
| 124 | let was = s.active_sequence(); |
| 125 | if id == was { |
| 126 | return Ok(None); |
| 127 | } |
| 128 | s.switch_sequence(id).map_err(|e| Reply::err(e.to_string()))?; |
| 129 | Ok(keep.then_some(was)) |
| 130 | } |
| 131 | |
| 132 | |
| 133 | pub fn leave(srv: &mut Server, back: Option<u32>) { |
| 134 | if let (Some(id), Some(s)) = (back, srv.session.as_mut()) { |
| 135 | let _ = s.switch_sequence(id); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | fn clips_arg(s: &PlaybackSession, op: &Value, who: &str) -> Result<Vec<(Lane, usize)>, String> { |
| 140 | let list = match op.get("clips") { |
| 141 | Some(Value::Array(a)) if !a.is_empty() => a, |
| 142 | None | Some(Value::Null) => return Err("missing argument `clips`".into()), |
| 143 | Some(_) => return Err(format!("{who}: `clips` must be a non-empty list of addresses such as [\"V1@0\", \"V1@90\"]")), |
| 144 | }; |
| 145 | let mut out = Vec::new(); |
| 146 | for v in list { |
| 147 | let raw = v.as_str().ok_or_else(|| format!("{who}: each clip is an address string, got {}", parse::kind_of(v)))?; |
| 148 | let (lane, idx) = super::edit::clip_addr(s, raw)?; |
| 149 | super::edit::check_unlocked(s, &[lane])?; |
| 150 | out.push((lane, idx)); |
| 151 | } |
| 152 | Ok(out) |
| 153 | } |
| 154 | |
| 155 | fn touched(s: &PlaybackSession, clips: &[(Lane, usize)]) -> Vec<(Lane, u32)> { |
| 156 | clips.iter().filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start))).collect() |
| 157 | } |
| 158 | |
| 159 | fn names(s: &PlaybackSession, t: &[(Lane, u32)]) -> String { |
| 160 | let _ = s; |
| 161 | t.iter().map(|&(l, st)| parse::addr(l, st)).collect::<Vec<_>>().join(", ") |
| 162 | } |
| 163 | |
| 164 | |
| 165 | pub fn nest(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 166 | let picks = clips_arg(s, op, "nest")?; |
| 167 | let name = op.get("name").and_then(Value::as_str); |
| 168 | let made = s.nest(&picks, name).map_err(|e| format!("nest: {e}"))?; |
| 169 | let t = touched(s, &made.clips); |
| 170 | let title = s.sequence_name(made.sequence).unwrap_or_default(); |
| 171 | Ok(Applied { text: format!("nest → sequence {} \"{title}\" as {}", made.sequence, names(s, &t)), touched: t }) |
| 172 | } |
| 173 | |
| 174 | |
| 175 | pub fn break_apart(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 176 | let picks = clips_arg(s, op, "break_apart")?; |
| 177 | let out = s.break_apart(&picks).map_err(|e| format!("break_apart: {e}"))?; |
| 178 | let t = touched(s, &out); |
| 179 | Ok(Applied { text: format!("break_apart → {} clip(s): {}", t.len(), names(s, &t)), touched: t }) |
| 180 | } |
| 181 | |
| 182 | |
| 183 | pub fn place_sequence(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 184 | let seq = resolve(s, op.get("sequence").ok_or("missing argument `sequence`")?)?; |
| 185 | let fps = parse::session_fps(s); |
| 186 | let end = parse::session_end(s); |
| 187 | let at = super::edit::opt_time(op, "at", fps, end)?.ok_or("missing argument `at`")?; |
| 188 | let lane = match op.get("lane") { |
| 189 | None | Some(Value::Null) => Lane::V1, |
| 190 | Some(Value::String(t)) => parse::lane(t)?, |
| 191 | Some(v) => return Err(format!("`lane` must be a lane name such as \"V1\", got {}", parse::kind_of(v))), |
| 192 | }; |
| 193 | super::edit::check_unlocked(s, &[lane])?; |
| 194 | s.place_sequence_at(seq, lane, parse::secs(at, fps)).map_err(|e| format!("place_sequence: {e}"))?; |
| 195 | Ok(Applied { |
| 196 | text: format!("place_sequence → sequence {seq} at {}", parse::addr(lane, at)), |
| 197 | touched: vec![(lane, at)], |
| 198 | }) |
| 199 | } |
| 200 | |
| 201 | #[cfg(test)] |
| 202 | mod tests { |
| 203 | use super::*; |
| 204 | use std::path::Path; |
| 205 | |
| 206 | fn open() -> Server { |
| 207 | engine::ao::set_silent_output(); |
| 208 | let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4"); |
| 209 | Server { session: Some(PlaybackSession::open(p).expect("open test asset")), ..Server::default() } |
| 210 | } |
| 211 | |
| 212 | #[test] |
| 213 | fn docs_name_their_arguments() { |
| 214 | for (doc, words) in [ |
| 215 | (NEST_OP_DOC, &["clips", "name", "undo step"][..]), |
| 216 | (BREAK_APART_OP_DOC, &["clips", "undo step"][..]), |
| 217 | (PLACE_SEQUENCE_OP_DOC, &["sequence", "at", "cycle"][..]), |
| 218 | (DOC, &["list", "new", "rename", "duplicate", "delete", "switch"][..]), |
| 219 | ] { |
| 220 | for w in words { |
| 221 | assert!(doc.contains(w), "{w}"); |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn the_tool_manages_sequences_with_undo() { |
| 228 | let mut srv = open(); |
| 229 | let first = run(&mut srv, &json!({})); |
| 230 | assert!(first.text.contains("1 sequence(s)"), "{}", first.text); |
| 231 | assert!(!run(&mut srv, &json!({"action": "new", "name": "Scratch"})).is_error); |
| 232 | assert!(run(&mut srv, &json!({"action": "list"})).text.contains("\"Scratch\"")); |
| 233 | assert!(!run(&mut srv, &json!({"action": "rename", "sequence": "Scratch", "new_name": "B"})).is_error); |
| 234 | assert!(!run(&mut srv, &json!({"action": "duplicate", "sequence": "B", "name": "C"})).is_error); |
| 235 | assert!(!run(&mut srv, &json!({"action": "switch", "sequence": "C"})).is_error); |
| 236 | assert!(run(&mut srv, &json!({"action": "list"})).text.contains("*seq")); |
| 237 | let gone = run(&mut srv, &json!({"action": "delete", "sequence": "nope"})); |
| 238 | assert!(gone.is_error && gone.text.contains("the sequences are"), "{}", gone.text); |
| 239 | assert!(!run(&mut srv, &json!({"action": "delete", "sequence": "C"})).is_error); |
| 240 | assert!(!run(&mut srv, &json!({"action": "delete", "sequence": 1})).is_error); |
| 241 | let last = run(&mut srv, &json!({"action": "delete", "sequence": 0})); |
| 242 | assert!(last.is_error, "{}", last.text); |
| 243 | assert_eq!(srv.session.as_ref().unwrap().sequences().len(), 1); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn nest_and_break_apart_are_edit_ops_and_one_undo_each() { |
| 248 | let mut srv = open(); |
| 249 | let r = crate::tools::edit::run_edit(&mut srv, &json!({"ops": [{"op": "nest", "clips": ["V1#0"], "name": "Inner"}]})); |
| 250 | assert!(!r.is_error, "{}", r.text); |
| 251 | assert!(r.text.contains("Inner"), "{}", r.text); |
| 252 | assert_eq!(srv.session.as_ref().unwrap().sequences().len(), 2); |
| 253 | let r = crate::tools::edit::run_edit(&mut srv, &json!({"ops": [{"op": "break_apart", "clips": ["V1#0"]}]})); |
| 254 | assert!(!r.is_error, "{}", r.text); |
| 255 | let r = crate::tools::edit::run_edit(&mut srv, &json!({"ops": [{"op": "nest", "clips": []}]})); |
| 256 | assert!(r.is_error); |
| 257 | let cyc = crate::tools::edit::run_edit(&mut srv, &json!({"ops": [{"op": "place_sequence", "sequence": 0, "at": 0}]})); |
| 258 | assert!(cyc.is_error, "{}", cyc.text); |
| 259 | } |
| 260 | |
| 261 | #[test] |
| 262 | fn the_sequence_argument_reads_another_and_comes_back() { |
| 263 | let mut srv = open(); |
| 264 | run(&mut srv, &json!({"action": "new", "name": "B"})); |
| 265 | let back = enter(&mut srv, &json!({"sequence": "B"}), true).ok().expect("enter"); |
| 266 | assert_eq!(srv.session.as_ref().unwrap().sequence_name(srv.session.as_ref().unwrap().active_sequence()).as_deref(), Some("B")); |
| 267 | leave(&mut srv, back); |
| 268 | assert_eq!(srv.session.as_ref().unwrap().active_sequence(), 0); |
| 269 | assert!(enter(&mut srv, &json!({"sequence": "zzz"}), true).is_err()); |
| 270 | let _ = run(&mut srv, &json!({"action": "duplicate", "sequence": 0})); |
| 271 | let r = crate::tools::project::project_settings(&mut srv, &json!({"fps": 5})).text; |
| 272 | assert!(r.contains("several sequences"), "{r}"); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn the_timeline_names_a_compound_clip_and_reads_another_sequence() { |
| 277 | let mut srv = open(); |
| 278 | let r = crate::tools::edit::run_edit(&mut srv, &json!({"ops": [{"op": "nest", "clips": ["V1#0"], "name": "Inner"}]})); |
| 279 | assert!(!r.is_error, "{}", r.text); |
| 280 | let call = |srv: &mut Server, args: Value| { |
| 281 | let msg = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "timeline", "arguments": args}}); |
| 282 | crate::rpc::handle(srv, msg).expect("a reply")["result"]["content"][0]["text"].as_str().unwrap_or("").to_string() |
| 283 | }; |
| 284 | let tl = call(&mut srv, json!({})); |
| 285 | assert!(tl.contains("compound \"Inner\""), "{tl}"); |
| 286 | let inner = call(&mut srv, json!({"sequence": "Inner"})); |
| 287 | assert!(inner.contains(".mp4"), "{inner}"); |
| 288 | assert_eq!(srv.session.as_ref().unwrap().active_sequence(), 0, "a read leaves the active sequence"); |
| 289 | } |
| 290 | } |