forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

stabilise.rs224 lines, 9.7 KiBHistoryRawDownload
1//! Video stabilisation: the `stabilize` edit op (on with a strength and a crop, or off) and the
2//! `stabilize_status` tool (where each stabilised clip's analysis stands). The analysis and the
3//! correction are `engine::stabilise`; this is the argument handling and the replies.
4
5use engine::PlaybackSession;
6use engine::project::{Lane, LaneKind};
7use engine::stabilise::{self, Crop, Stabilise, Status};
8use serde_json::{Value, json};
9
10use super::edit_fx::Applied;
11use crate::parse;
12use crate::server::{Reply, Server, Tool};
13
14pub const STABILIZE_OP_DOC: &str = "stabilize {clip, on?, strength?, crop?, off?, cancel?} — takes the camera shake out of a video clip. \
15 The shake is measured from the clip's own footage (corners tracked frame to frame, a shift-turn-zoom fitted to them), \
16 the camera path is smoothed, and each frame is moved to the smoothed path; a steady pan or tilt is kept, the jitter around it goes. \
17 strength 0 to 1 (default 0.5): how smooth, about strength × 2 seconds of smoothing. \
18 crop: \"zoom\" (default) enlarges the picture just enough that no frame shows an edge (at most 1.5×); \"full\" keeps the frame's size and lets black edges show where it moved. \
19 off:true (or on:false) takes it off; cancel:true stops a running analysis. \
20 The analysis runs in the background the first time (stabilize_status shows its progress) and is cached per source, so re-opening the project does not redo it; until it finishes the clip plays unstabilised. \
21 It applies before the clip's transform, and follows the footage through trims, speed, ramps and reverse. An export measures it first if it is missing (export_status shows Measuring shake). \
22 e.g. edit {ops:[{op:\"stabilize\", clip:\"V1@0\", strength:0.6}]}";
23
24const STATUS_DOC: &str = "Where each stabilised clip's analysis stands: ready, running with its percent, failed with why, or not started. clip limits it to one clip (V1@0); wait:true blocks until every listed analysis has finished (an export measures a missing one itself, as its Measuring shake stage).";
25
26pub fn tools() -> Vec<Tool> {
27 vec![Tool { name: "stabilize_status", description: STATUS_DOC, schema: status_schema, run: run_status }]
28}
29
30fn status_schema() -> Value {
31 json!({
32 "type": "object",
33 "properties": {
34 "clip": { "type": "string", "description": "One clip, such as V1@0 or V1#0. Default: every stabilised clip." },
35 "wait": { "type": "boolean", "description": "Block until the analyses have finished. Default false." }
36 }
37 })
38}
39
40fn kind_of(v: &Value) -> &'static str {
41 match v {
42 Value::Null => "null",
43 Value::Bool(_) => "a boolean",
44 Value::Number(_) => "a number",
45 Value::String(_) => "a string",
46 Value::Array(_) => "a list",
47 Value::Object(_) => "an object",
48 }
49}
50
51fn opt_bool(op: &Value, key: &str) -> Result<Option<bool>, String> {
52 match op.get(key) {
53 None | Some(Value::Null) => Ok(None),
54 Some(Value::Bool(b)) => Ok(Some(*b)),
55 Some(v) => Err(format!("`{key}` must be true or false, got {}", kind_of(v))),
56 }
57}
58
59fn status_words(st: &Status) -> String {
60 match st {
61 Status::Ready => "analysis ready".into(),
62 Status::Running(f) => format!("analysing, {:.0}% done", f * 100.0),
63 Status::Failed(e) => format!("analysis failed: {e}"),
64 Status::Missing => "analysis not started".into(),
65 }
66}
67
68fn settings_words(st: Stabilise) -> String {
69 let crop = match st.crop() {
70 Crop::Zoom => "zoom to hide edges",
71 Crop::Full => "keep full frame",
72 };
73 format!("strength {}, crop {} ({crop})", st.amount(), st.crop().name())
74}
75
76/// The `stabilize` edit op.
77pub fn op(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
78 let raw = match op.get("clip") {
79 Some(Value::String(c)) => c.as_str(),
80 None | Some(Value::Null) => return Err("missing argument `clip`".into()),
81 Some(v) => return Err(format!("`clip` must be a string, got {}", kind_of(v))),
82 };
83 let (lane, idx) = super::edit::clip_addr(s, raw)?;
84 super::edit::check_unlocked(s, &[lane])?;
85 let who = format!("stabilize {raw}");
86 if lane.kind != LaneKind::Video {
87 return Err(format!("{who}: stabilisation is for video clips, and {raw} is not one"));
88 }
89 let start = s.lane_clips(lane).get(idx).map_or(0, |c| c.start);
90 if s.stabilise_range(lane, idx).is_none() {
91 return Err(format!("{who}: a still or a song has no camera motion to take out"));
92 }
93 if opt_bool(op, "cancel")? == Some(true) {
94 let stopped = s.stabilise_cancel(lane, idx);
95 let what = if stopped { "analysis cancelled" } else { "no analysis was running" };
96 return Ok(Applied { text: format!("{who} → {what}"), touched: vec![(lane, start)] });
97 }
98 let off = opt_bool(op, "off")? == Some(true) || opt_bool(op, "on")? == Some(false);
99 if off {
100 if s.stabilise_of(lane, idx).is_none() {
101 return Ok(Applied { text: format!("{who} → already off (no change)"), touched: vec![(lane, start)] });
102 }
103 s.set_stabilise(lane, idx, None);
104 return Ok(Applied { text: format!("{who} → off"), touched: vec![(lane, start)] });
105 }
106 let mut st = s.stabilise_of(lane, idx).unwrap_or_default();
107 match op.get("strength") {
108 None | Some(Value::Null) => {}
109 Some(Value::Number(n)) => {
110 let v = n.as_f64().unwrap_or(f64::NAN);
111 if !(0.0..=1.0).contains(&v) {
112 return Err(format!("{who}: strength {v} out of range 0–1"));
113 }
114 st = Stabilise::new(v as f32, st.crop());
115 }
116 Some(v) => return Err(format!("{who}: `strength` must be a number from 0 to 1, got {}", kind_of(v))),
117 }
118 match op.get("crop") {
119 None | Some(Value::Null) => {}
120 Some(Value::String(c)) => {
121 let crop = Crop::from_name(c).ok_or_else(|| format!("{who}: crop `{c}` is not zoom or full"))?;
122 st = Stabilise::with_percent(st.strength(), crop);
123 }
124 Some(v) => return Err(format!("{who}: `crop` must be \"zoom\" or \"full\", got {}", kind_of(v))),
125 }
126 let changed = s.stabilise_of(lane, idx) != Some(st);
127 if changed && !s.set_stabilise(lane, idx, Some(st)) {
128 return Err(format!("{who}: the engine refused it (is the clip there?)"));
129 }
130 let status = s.stabilise_start(lane, idx).unwrap_or(Status::Missing);
131 let tail = if changed { "" } else { " (no change)" };
132 Ok(Applied {
133 text: format!("{who} → on, {}; {}{tail}", settings_words(st), status_words(&status)),
134 touched: vec![(lane, start)],
135 })
136}
137
138/// The line a still or a sheet over timeline frames `from..=to` adds when a
139/// stabilised clip there has no finished analysis yet: it is drawn unstabilised,
140/// and its analysis runs in the background (the compose started it).
141pub fn pending_in(s: &PlaybackSession, from: u32, to: u32) -> Option<String> {
142 let names: Vec<String> = stabilised(s)
143 .into_iter()
144 .filter(|&(lane, idx)| {
145 let c = &s.lane_clips(lane)[idx];
146 c.start <= to && from < c.end() && !matches!(s.stabilise_status(lane, idx), Some(Status::Ready) | None)
147 })
148 .map(|(lane, idx)| format!("{}#{idx}", parse::lane_name(lane)))
149 .collect();
150 (!names.is_empty()).then(|| {
151 format!(
152 "stabilisation analysis pending for {}: drawn unstabilised here; stabilize_status {{wait:true}} waits for it (an export measures it itself)",
153 names.join(", ")
154 )
155 })
156}
157
158/// Every stabilised clip as (lane, index).
159fn stabilised(s: &PlaybackSession) -> Vec<(Lane, usize)> {
160 s.lanes()
161 .into_iter()
162 .filter(|l| l.kind == LaneKind::Video)
163 .flat_map(|l| {
164 s.lane_clips(l)
165 .iter()
166 .enumerate()
167 .filter(|(_, c)| c.stabilise.is_some())
168 .map(move |(i, _)| (l, i))
169 .collect::<Vec<_>>()
170 })
171 .collect()
172}
173
174fn run_status(srv: &mut Server, args: &Value) -> Reply {
175 let s = match srv.session_ref() {
176 Ok(s) => s,
177 Err(r) => return r,
178 };
179 let wait = match opt_bool(args, "wait") {
180 Ok(w) => w.unwrap_or(false),
181 Err(e) => return Reply::err(e),
182 };
183 let clips = match args.get("clip").and_then(Value::as_str) {
184 None => stabilised(s),
185 Some(raw) => match super::edit::clip_addr(s, raw) {
186 Ok(c) => vec![c],
187 Err(e) => return Reply::err(e),
188 },
189 };
190 if clips.is_empty() {
191 return Reply::ok("no clip is stabilised: edit {ops:[{op:\"stabilize\", clip:\"V1@0\"}]} turns it on");
192 }
193 let mut lines = Vec::new();
194 for (lane, idx) in clips {
195 let name = format!("{}#{idx}", parse::lane_name(lane));
196 let Some(st) = s.stabilise_of(lane, idx) else {
197 lines.push(format!("{name}: not stabilised"));
198 continue;
199 };
200 let Some((path, lo, hi)) = s.stabilise_range(lane, idx) else {
201 lines.push(format!("{name}: not footage"));
202 continue;
203 };
204 let status = if wait { stabilise::wait(&path, lo, hi) } else { stabilise::status(&path, lo, hi) };
205 let zoom = match (&status, stabilise::correction(&path, lo, hi, st, s.meta().frame_rate)) {
206 (Status::Ready, Some(c)) => format!(", zoom {:.3}×", c.zoom),
207 _ => String::new(),
208 };
209 lines.push(format!("{name}: {}; {}{zoom} (source frames {lo}–{})", settings_words(st), status_words(&status), hi - 1));
210 }
211 Reply::ok(lines.join("\n"))
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn the_op_doc_names_every_argument() {
220 for arg in ["strength", "crop", "off", "cancel", "zoom", "full"] {
221 assert!(STABILIZE_OP_DOC.contains(arg), "{arg}");
222 }
223 }
224}