| 1 | |
| 2 | |
| 3 | |
| 4 | use std::sync::atomic::{AtomicBool, AtomicU32}; |
| 5 | |
| 6 | use engine::PlaybackSession; |
| 7 | use engine::project::LaneKind; |
| 8 | use engine::reframe; |
| 9 | use serde_json::Value; |
| 10 | |
| 11 | use super::edit_fx::{Applied, transform_keys_text}; |
| 12 | |
| 13 | pub const REFRAME_OP_DOC: &str = "reframe {clip, aspect?, smoothness?} — auto reframe: follows the subject of a video clip and writes transform keys so the clip fills the project canvas, e.g. a 16:9 shot in a 9:16 project. \ |
| 14 | The subject is found from the footage itself (what moves, contrast, a pull to the middle; no models), the path is smoothed with a dead zone so the crop holds still while the subject stays put, and keys are written only where the path turns. \ |
| 15 | The scale makes the clip cover the canvas, so no frame ever shows an edge. It sets the clip's fit to fit (the placement the keys are made for) and replaces the clip's transform keys; it is one undo step, and the keys are ordinary: refine them with transform_keys, take them off with transform_keys {clip, clear:true}. \ |
| 16 | aspect: \"fit\" (default) is the project canvas; or a shape such as \"9:16\", which must be the project's own shape (set the size first with project_settings) — it guards against reframing for the wrong canvas. \ |
| 17 | smoothness 0 to 1 (default 0.5): how slowly the crop follows, about 0.25 + 1.75 × smoothness seconds. \ |
| 18 | It analyses the clip before it answers (a minute of 1080p takes a few seconds). A clip's display rotation is not accounted for. \ |
| 19 | e.g. project_settings {resolution:\"1080x1920\"}, then edit {ops:[{op:\"reframe\", clip:\"V1@0\", smoothness:0.6}]}"; |
| 20 | |
| 21 | fn kind_of(v: &Value) -> &'static str { |
| 22 | match v { |
| 23 | Value::Null => "null", |
| 24 | Value::Bool(_) => "a boolean", |
| 25 | Value::Number(_) => "a number", |
| 26 | Value::String(_) => "a string", |
| 27 | Value::Array(_) => "a list", |
| 28 | Value::Object(_) => "an object", |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | |
| 33 | fn aspect_of(text: &str) -> Option<f64> { |
| 34 | let t = text.trim(); |
| 35 | let v = match t.split_once([':', '/', 'x']) { |
| 36 | Some((w, h)) => w.trim().parse::<f64>().ok()? / h.trim().parse::<f64>().ok()?, |
| 37 | None => t.parse::<f64>().ok()?, |
| 38 | }; |
| 39 | (v.is_finite() && v > 0.0).then_some(v) |
| 40 | } |
| 41 | |
| 42 | |
| 43 | pub fn op(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> { |
| 44 | let raw = match op.get("clip") { |
| 45 | Some(Value::String(c)) => c.as_str(), |
| 46 | None | Some(Value::Null) => return Err("missing argument `clip`".into()), |
| 47 | Some(v) => return Err(format!("`clip` must be a string, got {}", kind_of(v))), |
| 48 | }; |
| 49 | let (lane, idx) = super::edit::clip_addr(s, raw)?; |
| 50 | super::edit::check_unlocked(s, &[lane])?; |
| 51 | let who = format!("reframe {raw}"); |
| 52 | if lane.kind != LaneKind::Video { |
| 53 | return Err(format!("{who}: reframing is for video clips, and {raw} is not one")); |
| 54 | } |
| 55 | let smoothness = match op.get("smoothness") { |
| 56 | None | Some(Value::Null) => reframe::DEFAULT_SMOOTHNESS, |
| 57 | Some(Value::Number(n)) => { |
| 58 | let v = n.as_f64().unwrap_or(f64::NAN); |
| 59 | if !(0.0..=1.0).contains(&v) { |
| 60 | return Err(format!("{who}: smoothness {v} out of range 0–1")); |
| 61 | } |
| 62 | v as f32 |
| 63 | } |
| 64 | Some(v) => return Err(format!("{who}: `smoothness` must be a number from 0 to 1, got {}", kind_of(v))), |
| 65 | }; |
| 66 | let (cw, ch) = (s.meta().width, s.meta().height); |
| 67 | match op.get("aspect") { |
| 68 | None | Some(Value::Null) => {} |
| 69 | Some(Value::String(a)) if a.trim().eq_ignore_ascii_case("fit") => {} |
| 70 | Some(Value::String(a)) => { |
| 71 | let want = aspect_of(a).ok_or_else(|| format!("{who}: aspect `{a}` is not fit or a shape such as 9:16"))?; |
| 72 | let have = f64::from(cw) / f64::from(ch); |
| 73 | if (want / have - 1.0).abs() > 0.02 { |
| 74 | return Err(format!( |
| 75 | "{who}: the project canvas is {cw}x{ch}, not {a}; set it first (project_settings {{resolution:\"…\"}}) and reframe again, or use aspect:\"fit\"" |
| 76 | )); |
| 77 | } |
| 78 | } |
| 79 | Some(v) => return Err(format!("{who}: `aspect` must be \"fit\" or a shape such as \"9:16\", got {}", kind_of(v))), |
| 80 | } |
| 81 | let start = s.lane_clips(lane).get(idx).map_or(0, |c| c.start); |
| 82 | let job = s.reframe_job(lane, idx).ok_or_else(|| format!("{who}: a still or a song has no subject to follow"))?; |
| 83 | let (progress, cancel) = (AtomicU32::new(0), AtomicBool::new(false)); |
| 84 | let subject = reframe::analyse(&job.path, job.lo, job.hi, &progress, &cancel).map_err(|e| format!("{who}: {e}"))?; |
| 85 | let keys = reframe::keys(&subject, &job.target, smoothness); |
| 86 | let n = keys.len(); |
| 87 | let scale = keys[0].params.scale; |
| 88 | if !s.apply_reframe(lane, idx, keys) { |
| 89 | return Err(format!("{who}: the engine refused the keys")); |
| 90 | } |
| 91 | let clip = s.lane_clips(lane)[idx].clone(); |
| 92 | let shown = transform_keys_text(&clip, s.meta().frame_rate, s.transform_keys_of(lane, idx)); |
| 93 | Ok(Applied { |
| 94 | text: format!("{who} → {n} key(s), scale {scale:.2} to cover {cw}x{ch}, smoothness {smoothness}; {shown}"), |
| 95 | touched: vec![(lane, start)], |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | #[cfg(test)] |
| 100 | mod tests { |
| 101 | use super::*; |
| 102 | use serde_json::json; |
| 103 | use std::path::Path; |
| 104 | |
| 105 | fn session() -> PlaybackSession { |
| 106 | engine::ao::set_silent_output(); |
| 107 | let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_25fps.mp4"); |
| 108 | PlaybackSession::open(p).expect("open test asset") |
| 109 | } |
| 110 | |
| 111 | #[test] |
| 112 | fn the_op_doc_names_every_argument() { |
| 113 | for arg in ["aspect", "smoothness", "transform_keys", "undo step"] { |
| 114 | assert!(REFRAME_OP_DOC.contains(arg), "{arg}"); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | #[test] |
| 119 | fn aspects_parse() { |
| 120 | assert_eq!(aspect_of("9:16"), Some(0.5625)); |
| 121 | assert_eq!(aspect_of("16/9"), Some(16.0 / 9.0)); |
| 122 | assert_eq!(aspect_of("0:1"), None); |
| 123 | assert_eq!(aspect_of("wide"), None); |
| 124 | } |
| 125 | |
| 126 | #[test] |
| 127 | fn reframing_into_the_wrong_shape_is_refused_and_a_vertical_one_writes_keys_in_one_undo() { |
| 128 | let mut s = session(); |
| 129 | let lane = engine::project::Lane::V1; |
| 130 | let err = op(&mut s, &json!({"op": "reframe", "clip": "V1#0", "aspect": "9:16"})).expect_err("16:9 canvas"); |
| 131 | assert!(err.contains("project_settings"), "{err}"); |
| 132 | let err = op(&mut s, &json!({"op": "reframe", "clip": "V1#0", "smoothness": 2})).expect_err("range"); |
| 133 | assert!(err.contains("0–1"), "{err}"); |
| 134 | assert!(op(&mut s, &json!({"op": "reframe", "clip": "V1#0", "aspect": "banana"})).is_err()); |
| 135 | |
| 136 | assert!(s.set_resolution(1080, 1920), "vertical canvas"); |
| 137 | let applied = op(&mut s, &json!({"op": "reframe", "clip": "V1#0", "aspect": "9:16"})).expect("reframed"); |
| 138 | assert!(applied.text.contains("key(s)"), "{}", applied.text); |
| 139 | let keys = s.transform_keys_of(lane, 0).to_vec(); |
| 140 | assert!(!keys.is_empty() && keys[0].params.scale > 3.0, "{keys:?}"); |
| 141 | assert_eq!(s.fit_of(lane, 0), engine::scale::FitPolicy::Fit); |
| 142 | assert!(s.undo(), "one undo"); |
| 143 | assert!(s.transform_keys_of(lane, 0).is_empty(), "the keys are gone in that one step"); |
| 144 | } |
| 145 | } |