forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

multicam.rs396 lines, 20.2 KiBHistoryRawDownload
1//! Multicam: the `multicam_create` and `multicam_flatten` tools and the `angle` edit op. The model
2//! (angles as lanes of a compound clip's sequence, sync by sound) is `engine::project::multicam`
3//! and `engine::multisync`; this is the argument handling and the replies.
4
5use engine::project::{Lane, LaneKind};
6use engine::{AngleSync, MulticamSync, PlaybackSession};
7use serde_json::{Value, json};
8
9use super::edit_fx::Applied;
10use crate::parse;
11use crate::server::{Reply, Server, Tool};
12
13pub const ANGLE_OP_DOC: &str = "angle {clip, at?, angle?, audio?} — switches the angle of a multicam clip (made by multicam_create) from `at` on: the clip is cut there (no cut when `at` is its first frame or left out) and the part after the cut shows `angle`, a number from 1 or an angle name; the cut is one undo step. The sound follows the picture unless `audio` says otherwise: audio:\"follow\" makes it follow again, audio:2 (or a name) keeps it on that angle whatever the picture shows. Give `angle`, `audio` or both. `clip` is the picture clip (or its linked sound clip) of the multicam. Refused when the clip is not a multicam clip, the angle does not exist, or nothing would change. e.g. edit {ops:[{op:\"angle\", clip:\"V1@0\", at:\"12s\", angle:2}]}";
14
15const CREATE_DOC: &str = "Makes a multicam clip from several cameras of one event and puts it on the timeline. sources: 2 to 9 imported files (src:N as media_import reports them; the first is the reference). sync: \"audio\" (default) lines every camera up with the first one that has sound by the shape of its loudness over the first four minutes (a clap, a voice or a song both cameras heard; accurate to 20 ms; a camera that cannot be matched, or has no sound, starts with the others and the reply says so) or \"start\" (all cameras start together). The result is a compound clip of a multicam sequence with one lane per camera: it plays angle 1 until you switch angles with edit {op:\"angle\"}. name? names the sequence (default Multicam); at? where the clip goes (default 0); lane? the video lane (default V1; the sound goes on the audio lane of the same number, linked). It overwrites what is on those lanes there, like place. One undo step. multicam_flatten turns the clips back into plain camera clips.";
16
17const FLATTEN_DOC: &str = "Replaces a multicam clip (give the picture or sound clip as `clip`, e.g. \"V1@0\"), every other piece of the same multicam on this timeline and their linked sound with the plain camera clips they play: each segment becomes the trimmed clip of the angle it showed, the sound of the angle it used. The render does not change. The multicam sequence itself stays (delete it with sequence {action:\"delete\"} once nothing plays it). Refused when another clip is in the way. One undo step.";
18
19pub fn tools() -> Vec<Tool> {
20 vec![
21 Tool { name: "multicam_create", description: CREATE_DOC, schema: create_schema, run: create },
22 Tool { name: "multicam_flatten", description: FLATTEN_DOC, schema: flatten_schema, run: flatten },
23 ]
24}
25
26fn create_schema() -> Value {
27 json!({
28 "type": "object",
29 "properties": {
30 "sources": { "type": "array", "minItems": 2, "maxItems": 9, "items": { "type": ["string", "number"] }, "description": "The cameras: src:N or N for each imported file, 2 to 9. The first is the sync reference." },
31 "sync": { "type": "string", "enum": ["audio", "start"], "description": "audio (default): line up by the sound the cameras share. start: all start together." },
32 "name": { "type": "string", "maxLength": 100, "description": "The multicam sequence's name. Default Multicam." },
33 "at": { "type": ["string", "number"], "description": "Where the clip goes on the timeline. Default 0." },
34 "lane": { "type": "string", "description": "The video lane, e.g. V1 (default); the sound goes on the audio lane of the same number." }
35 },
36 "required": ["sources"]
37 })
38}
39
40fn flatten_schema() -> Value {
41 json!({
42 "type": "object",
43 "properties": { "clip": { "type": "string", "description": "A multicam clip, such as V1@0 (or its sound clip A1@0)." } },
44 "required": ["clip"]
45 })
46}
47
48/// A source index from `src:N` or a number.
49fn source_of(s: &PlaybackSession, v: &Value) -> Result<usize, String> {
50 let n = match v {
51 Value::Number(n) => n.as_u64().map(|n| n as usize).ok_or("a source is a whole number or src:N")?,
52 Value::String(t) => {
53 let t = t.trim();
54 t.strip_prefix("src:").unwrap_or(t).trim().parse::<usize>().map_err(|_| format!("`{t}` is not a source: write src:N"))?
55 }
56 other => return Err(format!("a source is src:N, got {}", parse::kind_of(other))),
57 };
58 if n >= s.sources().len() {
59 return Err(format!("there is no src:{n} (media_list shows what is imported)"));
60 }
61 Ok(n)
62}
63
64fn create(srv: &mut Server, args: &Value) -> Reply {
65 let before = match srv.session_ref() {
66 Ok(s) => s.history_pushes(),
67 Err(r) => return r,
68 };
69 let s = match srv.session() {
70 Ok(s) => s,
71 Err(r) => return r,
72 };
73 let list = match args.get("sources") {
74 Some(Value::Array(a)) if a.len() >= 2 => a,
75 Some(Value::Array(_)) => return Reply::err("multicam_create: a multicam clip needs at least 2 sources"),
76 None | Some(Value::Null) => return Reply::err("multicam_create: missing argument `sources`: a list such as [\"src:0\", \"src:1\"]"),
77 Some(v) => return Reply::err(format!("multicam_create: `sources` must be a list, got {}", parse::kind_of(v))),
78 };
79 let mut picks = Vec::new();
80 for v in list {
81 match source_of(s, v) {
82 Ok(n) => picks.push(n),
83 Err(e) => return Reply::err(format!("multicam_create: {e}")),
84 }
85 }
86 let sync = match args.get("sync").and_then(Value::as_str) {
87 None | Some("audio") => MulticamSync::Audio,
88 Some("start") => MulticamSync::Start,
89 Some(other) => return Reply::err(format!("multicam_create: sync is audio or start, not `{other}`")),
90 };
91 let fps = parse::session_fps(s);
92 let end = parse::session_end(s);
93 let at = match parse::opt_frame_arg(args, "at", fps, end) {
94 Ok(a) => a.unwrap_or(0),
95 Err(r) => return r,
96 };
97 let lane = match args.get("lane") {
98 None | Some(Value::Null) => Lane::V1,
99 Some(Value::String(t)) => match parse::lane(t) {
100 Ok(l) => l,
101 Err(e) => return Reply::err(format!("multicam_create: {e}")),
102 },
103 Some(v) => return Reply::err(format!("multicam_create: `lane` must be a name such as V1, got {}", parse::kind_of(v))),
104 };
105 if let Err(e) = super::edit::check_unlocked(s, &[lane, Lane::new(LaneKind::Audio, lane.ord)]) {
106 return Reply::err(format!("multicam_create: {e}"));
107 }
108 let name = args.get("name").and_then(Value::as_str);
109 let report = match s.make_multicam_at(&picks, sync, name, lane, parse::secs(at, fps)) {
110 Ok(r) => r,
111 Err(e) => return Reply::err(format!("multicam_create: {e}")),
112 };
113 let title = s.sequence_name(report.made.sequence).unwrap_or_default();
114 let names = s.angle_names(report.made.sequence).unwrap_or_default();
115 let mut lines = vec![format!(
116 "multicam \"{title}\" (sequence {}): {} angles, {}",
117 report.made.sequence,
118 picks.len(),
119 parse::clock(s.sequences().iter().find(|q| q.id == report.made.sequence).map_or(0, |q| q.frames), fps)
120 )];
121 let mut angles = Vec::new();
122 for (i, src) in picks.iter().enumerate() {
123 let how = match report.how[i] {
124 AngleSync::Reference => "sync reference".to_string(),
125 AngleSync::Audio { score } => format!("synced by sound, match {score:.2}, {:+.2} s against angle 1", report.offsets_secs[i]),
126 AngleSync::Start => "placed at the start".to_string(),
127 AngleSync::Weak { score } => format!("sound did not match well enough ({score:.2}): placed at the start"),
128 AngleSync::NoSound => "no sound: placed at the start".to_string(),
129 };
130 lines.push(format!(
131 " angle {} \"{}\" src:{src}: starts at {} — {how}",
132 i + 1,
133 names.get(i).cloned().unwrap_or_default(),
134 parse::clock(report.starts[i], fps)
135 ));
136 angles.push(json!({
137 "angle": i + 1,
138 "name": names.get(i).cloned().unwrap_or_default(),
139 "source": format!("src:{src}"),
140 "start_frames": report.starts[i],
141 "sync": match report.how[i] {
142 AngleSync::Reference => "reference",
143 AngleSync::Audio { .. } => "audio",
144 AngleSync::Start => "start",
145 AngleSync::Weak { .. } => "weak",
146 AngleSync::NoSound => "no_sound",
147 },
148 "offset_secs": report.offsets_secs[i],
149 }));
150 }
151 let clips: Vec<String> = report
152 .made
153 .clips
154 .iter()
155 .filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| parse::addr(l, c.start)))
156 .collect();
157 lines.push(format!("placed as {}; it shows angle 1 — switch with edit {{op:\"angle\", clip, at, angle}}", clips.join(" + ")));
158 let out = Reply::ok(lines.join("\n")).with(json!({
159 "sequence": report.made.sequence,
160 "name": title,
161 "clips": clips,
162 "angles": angles,
163 }));
164 super::project::note_pushes_as(srv, before, "multicam_create");
165 out
166}
167
168/// The picture clip of the multicam that `clip` (a picture or its linked sound) belongs to.
169fn picture_of(s: &PlaybackSession, lane: Lane, idx: usize) -> Result<Lane, String> {
170 if lane.kind == LaneKind::Video {
171 return Ok(lane);
172 }
173 let c = s.lane_clips(lane).get(idx).ok_or("there is no such clip")?;
174 let link = c.link.ok_or("that sound clip is not linked to a picture clip: give the picture clip")?;
175 s.lanes()
176 .into_iter()
177 .filter(|l| l.kind == LaneKind::Video)
178 .find(|&l| s.lane_clips(l).iter().any(|o| o.link == Some(link) && o.source == c.source))
179 .ok_or_else(|| "no picture clip is linked to that sound clip: give the picture clip".to_string())
180}
181
182/// An angle by 1-based number or name.
183fn angle_of(names: &[String], v: &Value, what: &str) -> Result<u8, String> {
184 let list = || names.iter().enumerate().map(|(i, n)| format!("{} \"{n}\"", i + 1)).collect::<Vec<_>>().join(", ");
185 let found = match v {
186 Value::Number(n) => n.as_u64().and_then(|n| n.checked_sub(1)).map(|n| n as usize).filter(|n| *n < names.len()),
187 Value::String(t) => {
188 let t = t.trim();
189 names
190 .iter()
191 .position(|n| n == t)
192 .or_else(|| names.iter().position(|n| n.eq_ignore_ascii_case(t)))
193 .or_else(|| t.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).filter(|n| *n < names.len()))
194 }
195 other => return Err(format!("`{what}` is an angle number or name, got {}", parse::kind_of(other))),
196 };
197 found.map(|n| n as u8).ok_or_else(|| format!("no angle {v}; the angles are {}", list()))
198}
199
200/// The `angle` edit op.
201pub fn angle(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
202 let raw = parse::addr_str(op, "clip", "\"V1@0\"")?;
203 let (lane, idx) = super::edit::clip_addr(s, raw)?;
204 let vlane = picture_of(s, lane, idx).map_err(|e| format!("angle {raw}: {e}"))?;
205 super::edit::check_unlocked(s, &[lane, vlane])?;
206 let Some((_, names)) = s.multicam_at(lane, idx) else {
207 return Err(format!("angle {raw}: {raw} is not a multicam clip (multicam_create makes one)"));
208 };
209 let video = match op.get("angle") {
210 None | Some(Value::Null) => None,
211 Some(v) => Some(angle_of(&names, v, "angle").map_err(|e| format!("angle {raw}: {e}"))?),
212 };
213 let audio = match op.get("audio") {
214 None | Some(Value::Null) => None,
215 Some(Value::String(t)) if t.trim().eq_ignore_ascii_case("follow") => Some(None),
216 Some(v) => Some(Some(angle_of(&names, v, "audio").map_err(|e| format!("angle {raw}: {e}"))?)),
217 };
218 if video.is_none() && audio.is_none() {
219 return Err(format!("angle {raw}: give `angle` (the picture), `audio` (follow or an angle), or both"));
220 }
221 let fps = parse::session_fps(s);
222 let end = parse::session_end(s);
223 let start = s.lane_clips(lane).get(idx).map_or(0, |c| c.start);
224 let at = super::edit::opt_time(op, "at", fps, end)?.unwrap_or(start);
225 // The clip addressed must be the one under `at`: its picture lane is where the cut is looked for.
226 let touched = s.switch_angle_at(Some(vlane), parse::secs(at, fps), video, audio).map_err(|e| format!("angle {raw}: {e}"))?;
227 let shown = |a: Option<u8>| a.map_or(String::new(), |a| format!("{} \"{}\"", a + 1, names[usize::from(a)]));
228 let mut what = Vec::new();
229 if video.is_some() {
230 what.push(format!("picture {}", shown(video)));
231 }
232 match audio {
233 Some(None) => what.push("sound follows the picture".to_string()),
234 Some(Some(a)) => what.push(format!("sound {}", shown(Some(a)))),
235 None => {}
236 }
237 let at_text = parse::clock(at, fps);
238 let list: Vec<String> = touched.iter().map(|&(l, st)| parse::addr(l, st)).collect();
239 Ok(Applied { text: format!("angle from {at_text}: {} → {}", what.join(", "), list.join(", ")), touched })
240}
241
242fn flatten(srv: &mut Server, args: &Value) -> Reply {
243 let before = match srv.session_ref() {
244 Ok(s) => s.history_pushes(),
245 Err(r) => return r,
246 };
247 let s = match srv.session() {
248 Ok(s) => s,
249 Err(r) => return r,
250 };
251 let raw = match parse::addr_str(args, "clip", "\"V1@0\"") {
252 Ok(r) => r,
253 Err(e) => return Reply::err(format!("multicam_flatten: {e}")),
254 };
255 let (lane, idx) = match super::edit::clip_addr(s, raw) {
256 Ok(x) => x,
257 Err(e) => return Reply::err(format!("multicam_flatten: {e}")),
258 };
259 if let Err(e) = super::edit::check_unlocked(s, &s.lanes()) {
260 return Reply::err(format!("multicam_flatten: {e}"));
261 }
262 match s.flatten_multicam(lane, idx) {
263 Ok(made) => {
264 let names: Vec<String> = made.iter().filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| parse::addr(l, c.start))).collect();
265 let out = Reply::ok(format!("multicam_flatten → {} plain clip(s): {}", names.len(), names.join(", ")))
266 .with(json!({ "clips": names }));
267 super::project::note_pushes_as(srv, before, "multicam_flatten");
268 out
269 }
270 Err(e) => Reply::err(format!("multicam_flatten: {e}")),
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277 use std::path::{Path, PathBuf};
278 use std::process::Command;
279
280 /// A 4 s clip of `pattern` with a 0.5 s tone burst at `burst` seconds.
281 fn camera(dir: &Path, name: &str, pattern: &str, burst: f64) -> PathBuf {
282 let out = dir.join(name);
283 let sound = format!(
284 "aevalsrc='0.02*sin(2*PI*220*t)+if(between(t,{burst},{}),0.5*sin(2*PI*1000*t),0)+if(between(t,{},{}),0.4*sin(2*PI*600*t),0)':s=44100:d=4",
285 burst + 0.5,
286 burst + 1.6,
287 burst + 1.9
288 );
289 let ok = Command::new("ffmpeg")
290 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &format!("{pattern}=s=160x90:r=25:d=4"), "-f", "lavfi", "-i", &sound])
291 .args(["-ac", "2", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest"])
292 .arg(&out)
293 .status()
294 .expect("ffmpeg runs")
295 .success();
296 assert!(ok, "ffmpeg made {name}");
297 out
298 }
299
300 fn rig() -> (Server, engine::scratch::Scratch) {
301 engine::ao::set_silent_output();
302 let dir = engine::scratch::Scratch::dir("ve_mcp_multicam");
303 let a = camera(&dir, "cam_a.mp4", "testsrc2", 0.8);
304 let b = camera(&dir, "cam_b.mp4", "smptebars", 1.7);
305 let mut s = PlaybackSession::open(a).expect("open");
306 s.import(&b).expect("import");
307 (Server { session: Some(s), ..Server::default() }, dir)
308 }
309
310 fn edit(srv: &mut Server, ops: Value) -> Reply {
311 crate::tools::edit::run_edit(srv, &json!({ "ops": ops }))
312 }
313
314 #[test]
315 fn docs_name_their_arguments() {
316 for w in ["clip", "at", "angle", "audio", "follow", "undo step"] {
317 assert!(ANGLE_OP_DOC.contains(w), "{w}");
318 }
319 for w in ["sources", "sync", "audio", "start", "name", "lane"] {
320 assert!(CREATE_DOC.contains(w), "{w}");
321 }
322 assert!(FLATTEN_DOC.contains("clip"));
323 }
324
325 #[test]
326 fn create_syncs_by_sound_then_angle_switches_and_flatten_restores() {
327 let (mut srv, _dir) = rig();
328 let r = create(&mut srv, &json!({"sources": ["src:0", 1], "name": "Show"}));
329 assert!(!r.is_error, "{}", r.text);
330 assert!(r.text.contains("synced by sound") && r.text.contains("+0.90 s"), "{}", r.text);
331 let st = r.structured.as_deref().expect("structured");
332 assert_eq!(st["angles"][1]["sync"], "audio");
333 let s = srv.session.as_ref().unwrap();
334 assert_eq!(s.sequence_name(st["sequence"].as_u64().unwrap() as u32).as_deref(), Some("Show"));
335 let r = edit(&mut srv, json!([{"op": "angle", "clip": "V1@0", "at": "2s", "angle": 2}]));
336 assert!(!r.is_error, "{}", r.text);
337 assert!(r.text.contains("cam_b"), "{}", r.text);
338 let s = srv.session.as_ref().unwrap();
339 assert_eq!(s.lane_clips(Lane::V1).len(), 2);
340 assert_eq!(s.lane_clips(Lane::A1).len(), 2);
341 // The sound clip address works too, a name works, and the sound can be pinned.
342 let r = edit(&mut srv, json!([{"op": "angle", "clip": "A1@50", "at": "3s", "angle": "cam_a", "audio": 2}]));
343 assert!(!r.is_error, "{}", r.text);
344 let s = srv.session.as_ref().unwrap();
345 assert_eq!(s.lane_clips(Lane::A1).last().map(|c| c.angle.audio), Some(Some(1)));
346 // Refusals say why.
347 for (op, word) in [
348 (json!({"op": "angle", "clip": "V1@0", "angle": 9}), "no angle"),
349 (json!({"op": "angle", "clip": "V1@0"}), "give `angle`"),
350 (json!({"op": "angle", "clip": "V1@0", "angle": 1}), "already"),
351 (json!({"op": "angle", "clip": "V1@900", "angle": 1}), "V1@900"),
352 ] {
353 let r = edit(&mut srv, json!([op]));
354 assert!(r.is_error && r.text.contains(word), "{word}: {}", r.text);
355 }
356 let tl = crate::rpc::handle(&mut srv, json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "timeline", "arguments": {}}}));
357 let tl = tl.expect("reply")["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();
358 assert!(tl.contains("multicam \"Show\"") && tl.contains("angle 2"), "{tl}");
359 let r = flatten(&mut srv, &json!({"clip": "V1@0"}));
360 assert!(!r.is_error, "{}", r.text);
361 let s = srv.session.as_ref().unwrap();
362 assert!(s.lane_clips(Lane::V1).iter().all(|c| !engine::project::is_sequence_source(c.source)));
363 assert_eq!(s.lane_clips(Lane::V1).len(), 3);
364 assert!(flatten(&mut srv, &json!({"clip": "V1@0"})).is_error, "nothing multicam left");
365 }
366
367 #[test]
368 fn create_refuses_what_it_cannot_do_by_name() {
369 let (mut srv, _dir) = rig();
370 for (args, word) in [
371 (json!({}), "sources"),
372 (json!({"sources": ["src:0"]}), "at least 2"),
373 (json!({"sources": ["src:0", "src:7"]}), "src:7"),
374 (json!({"sources": ["src:0", "src:0"]}), "twice"),
375 (json!({"sources": [0, 1], "sync": "clap"}), "audio or start"),
376 (json!({"sources": [0, 1], "lane": "A1"}), "video lane"),
377 ] {
378 let r = create(&mut srv, &args);
379 assert!(r.is_error && r.text.contains(word), "{word}: {}", r.text);
380 }
381 assert_eq!(srv.session.as_ref().unwrap().sequences().len(), 1, "a refusal changes nothing");
382 let r = create(&mut srv, &json!({"sources": [0, 1], "sync": "start"}));
383 assert!(!r.is_error && r.text.contains("placed at the start"), "{}", r.text);
384 }
385
386 #[test]
387 fn create_is_one_undo_step() {
388 let (mut srv, _dir) = rig();
389 let s = srv.session.as_ref().unwrap();
390 let before = s.undo_depth();
391 let r = create(&mut srv, &json!({"sources": [0, 1]}));
392 assert!(!r.is_error, "{}", r.text);
393 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), before + 1);
394 assert_eq!(srv.ledger.last().map(|e| e.label.as_str()), Some("multicam_create"));
395 }
396}