| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use engine::playback::TrackJob; |
| 8 | use engine::project::LaneKind; |
| 9 | use engine::track::{self, Status}; |
| 10 | use serde_json::{Value, json}; |
| 11 | |
| 12 | use super::edit_fx::src_at; |
| 13 | use crate::parse; |
| 14 | use crate::server::{Reply, Server, Tool}; |
| 15 | |
| 16 | const TRACK_DOC: &str = "track {clip, effect_index, from?, to?, direction?, apply?, cancel?} — follows a rect or ellipse mask's box through a clip and moves the mask with the picture. \ |
| 17 | The box is the mask's own at from; the picture under it is matched frame to frame (sub-pixel, template learned slowly), and the mask's centre takes the same path, its size and soft edge kept. \ |
| 18 | from and to are clip-relative times (default: the clip's start and end; direction \"backward\" defaults to starting at the end). \ |
| 19 | The track runs in the background: track_status shows its percent and writes the keys when it has finished (they show as diamonds on the mask). \ |
| 20 | It stops where the feature is lost (a flat or line-only patch, or a second place that matches nearly as well) and says at which frame. apply: \"mask\" (the default); a title cannot be tracked, since titles have no keyable position. \ |
| 21 | The path follows the clip's placement (position, scale, rotation, crop and transform keys), so the mask stays on the feature on a moved or scaled clip. Not yet: a source stored turned (a phone's portrait video) or with non-square pixels is tracked as stored. \ |
| 22 | cancel:true with a clip stops that clip's tracks. \ |
| 23 | e.g. track {clip:\"V1#0\", effect_index:1, direction:\"forward\"}"; |
| 24 | |
| 25 | const STATUS_DOC: &str = "Where each running track stands (percent). A finished track's keys are written onto its mask, and the reply says how far it got. wait:true blocks until every running track has finished."; |
| 26 | |
| 27 | pub fn tools() -> Vec<Tool> { |
| 28 | vec![ |
| 29 | Tool { name: "track", description: TRACK_DOC, schema: track_schema, run: run_track }, |
| 30 | Tool { name: "track_status", description: STATUS_DOC, schema: status_schema, run: run_status }, |
| 31 | ] |
| 32 | } |
| 33 | |
| 34 | fn track_schema() -> Value { |
| 35 | json!({ |
| 36 | "type": "object", |
| 37 | "properties": { |
| 38 | "clip": { "type": "string", "description": "The clip, such as V1#0 or V1@0." }, |
| 39 | "effect_index": { "type": "integer", "description": "The mask's stack position on the clip, 0 for the first effect." }, |
| 40 | "from": { "type": "string", "examples": ["0s"], "description": "Where the track starts, clip-relative (\"0s\", \"1.5s\", \"end\"). Default: the clip's start (its end for backward)." }, |
| 41 | "to": { "type": "string", "examples": ["2s"], "description": "Where it stops, clip-relative. Default: the clip's end (its start for backward)." }, |
| 42 | "direction": { "type": "string", "enum": ["forward", "backward"] }, |
| 43 | "apply": { "type": "string", "default": "mask", "description": "What the track writes to: the mask. Titles are not trackable." }, |
| 44 | "cancel": { "type": "boolean", "description": "Stop this clip's running tracks instead of starting one." } |
| 45 | }, |
| 46 | "required": ["clip"] |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | fn status_schema() -> Value { |
| 51 | json!({ |
| 52 | "type": "object", |
| 53 | "properties": { |
| 54 | "wait": { "type": "boolean", "description": "Block until every running track has finished. Default false." } |
| 55 | } |
| 56 | }) |
| 57 | } |
| 58 | |
| 59 | fn opt_bool(args: &Value, key: &str) -> Result<bool, String> { |
| 60 | match args.get(key) { |
| 61 | None | Some(Value::Null) => Ok(false), |
| 62 | Some(Value::Bool(b)) => Ok(*b), |
| 63 | Some(_) => Err(format!("`{key}` must be true or false")), |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | pub(super) fn settle(srv: &mut Server) -> Vec<String> { |
| 70 | let mut jobs = std::mem::take(&mut srv.tracks); |
| 71 | let Some(s) = srv.session.as_mut() else { |
| 72 | return Vec::new(); |
| 73 | }; |
| 74 | let start = s.history_pushes(); |
| 75 | let fps = parse::session_fps(s); |
| 76 | let done = s.track_settle(&mut jobs); |
| 77 | let notes = done |
| 78 | .into_iter() |
| 79 | .map(|d| { |
| 80 | let name = format!("{}#{} mask {}", parse::lane_name(d.lane), d.idx, d.slot); |
| 81 | match d.result { |
| 82 | Ok(o) => { |
| 83 | let lost = o.lost_at.map_or(String::new(), |f| format!(", lost the feature at frame {f} ({:.2}s)", parse::secs(f, fps))); |
| 84 | format!("{name}: tracked frames {}–{}{lost}; {} keys written", o.from, o.to, o.keys) |
| 85 | } |
| 86 | Err(e) => format!("{name}: track stopped: {e}"), |
| 87 | } |
| 88 | }) |
| 89 | .collect(); |
| 90 | srv.tracks = jobs; |
| 91 | super::hear::record_pushes(srv, start, "track mask".into()); |
| 92 | notes |
| 93 | } |
| 94 | |
| 95 | |
| 96 | fn run_track(srv: &mut Server, args: &Value) -> Reply { |
| 97 | let cancel = match opt_bool(args, "cancel") { |
| 98 | Ok(c) => c, |
| 99 | Err(e) => return Reply::err(e), |
| 100 | }; |
| 101 | let Some(raw) = args.get("clip").and_then(Value::as_str) else { |
| 102 | return Reply::err("missing argument `clip`: the clip to track, such as V1#0"); |
| 103 | }; |
| 104 | let mut notes = settle(srv); |
| 105 | let s = match srv.session_ref() { |
| 106 | Ok(s) => s, |
| 107 | Err(r) => return r, |
| 108 | }; |
| 109 | let (lane, idx) = match super::edit::clip_addr(s, raw) { |
| 110 | Ok(a) => a, |
| 111 | Err(e) => return Reply::err(e), |
| 112 | }; |
| 113 | let name = format!("{}#{idx}", parse::lane_name(lane)); |
| 114 | if cancel { |
| 115 | let mut stopped = 0; |
| 116 | for job in srv.tracks.iter().filter(|j| j.lane == lane && j.idx == idx) { |
| 117 | if track::cancel(job.id) { |
| 118 | stopped += 1; |
| 119 | } |
| 120 | } |
| 121 | let text = if stopped == 0 { format!("{name}: no track was running") } else { format!("{name}: {stopped} track(s) cancelled") }; |
| 122 | notes.push(text); |
| 123 | return Reply::ok(notes.join("\n")); |
| 124 | } |
| 125 | if lane.kind != LaneKind::Video { |
| 126 | return Reply::err(format!("{raw} is not a picture clip; only a mask on a video clip can be tracked")); |
| 127 | } |
| 128 | let Some(c) = s.lane_clips(lane).get(idx).cloned() else { |
| 129 | return Reply::err(format!("{raw}: there is no clip there")); |
| 130 | }; |
| 131 | let slot = match args.get("effect_index").or_else(|| args.get("effect")).and_then(Value::as_u64) { |
| 132 | Some(n) => n as usize, |
| 133 | None => return Reply::err("missing `effect_index`: the mask's stack position, 0 for the first effect"), |
| 134 | }; |
| 135 | match args.get("apply").and_then(Value::as_str) { |
| 136 | None | Some("mask") => {} |
| 137 | Some(a) if a.starts_with("title") => { |
| 138 | return Reply::err("a title cannot be tracked: titles have no keyable position. Track a mask (apply:\"mask\")"); |
| 139 | } |
| 140 | Some(a) => return Reply::err(format!("apply `{a}` is not \"mask\"")), |
| 141 | } |
| 142 | let backward = match args.get("direction").and_then(Value::as_str) { |
| 143 | None | Some("forward") => false, |
| 144 | Some("backward") => true, |
| 145 | Some(d) => return Reply::err(format!("direction `{d}` is not forward or backward")), |
| 146 | }; |
| 147 | let fps = parse::session_fps(s); |
| 148 | let len = c.frames(); |
| 149 | let clip_frame = |key: &str, default: u32| -> Result<u32, String> { |
| 150 | match args.get(key) { |
| 151 | None | Some(Value::Null) => Ok(default), |
| 152 | Some(v) => parse::frame(v, fps, len), |
| 153 | } |
| 154 | }; |
| 155 | let (from_default, to_default) = if backward { (len, 0) } else { (0, len) }; |
| 156 | let (from_off, to_off) = match (clip_frame("from", from_default), clip_frame("to", to_default)) { |
| 157 | (Ok(a), Ok(b)) => (a, b), |
| 158 | (Err(e), _) | (_, Err(e)) => return Reply::err(e), |
| 159 | }; |
| 160 | let from = src_at(&c, c.start + from_off); |
| 161 | let to = src_at(&c, c.start + to_off); |
| 162 | if from == to { |
| 163 | return Reply::err(format!("{raw}: from and to are the same frame; a track needs two")); |
| 164 | } |
| 165 | if (to > from) == backward { |
| 166 | return Reply::err(format!("{raw}: direction {} runs the other way from from to to", if backward { "backward" } else { "forward" })); |
| 167 | } |
| 168 | let job: TrackJob = match s.track_mask_start(lane, idx, slot, from, to) { |
| 169 | Ok(j) => j, |
| 170 | Err(e) => return Reply::err(format!("track {raw} effect {slot}: {e}")), |
| 171 | }; |
| 172 | let dir = if backward { "backward" } else { "forward" }; |
| 173 | srv.tracks.push(job); |
| 174 | notes.push(format!( |
| 175 | "track {raw} effect {slot}: {dir} from {:.2}s to {:.2}s, analysing in the background; track_status shows its progress and writes the keys", |
| 176 | parse::secs(c.start + from_off, fps), |
| 177 | parse::secs(c.start + to_off, fps), |
| 178 | )); |
| 179 | Reply::ok(notes.join("\n")) |
| 180 | } |
| 181 | |
| 182 | |
| 183 | fn run_status(srv: &mut Server, args: &Value) -> Reply { |
| 184 | let wait = match opt_bool(args, "wait") { |
| 185 | Ok(w) => w, |
| 186 | Err(e) => return Reply::err(e), |
| 187 | }; |
| 188 | if wait { |
| 189 | while srv.tracks.iter().any(|j| matches!(track::status(j.id), Status::Running(_))) { |
| 190 | std::thread::sleep(std::time::Duration::from_millis(20)); |
| 191 | } |
| 192 | } |
| 193 | let mut lines = settle(srv); |
| 194 | for job in &srv.tracks { |
| 195 | if let Status::Running(f) = track::status(job.id) { |
| 196 | lines.push(format!("{}#{} mask {}: analysing, {:.0}% done", parse::lane_name(job.lane), job.idx, job.slot, f * 100.0)); |
| 197 | } |
| 198 | } |
| 199 | if lines.is_empty() { |
| 200 | return Reply::ok("no track is running or waiting to be written"); |
| 201 | } |
| 202 | Reply::ok(lines.join("\n")) |
| 203 | } |