forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

editkeys.rs377 lines, 14.3 KiBHistoryRawDownload
1//! The edit-key verbs both the GUI and the MCP server run: copy and paste a clip's look, nudge, the split edit,
2//! match frame and the replace edit's plan. Each acts on a [`PlaybackSession`], so the two front ends share one rule.
3
4use std::path::PathBuf;
5
6use crate::color::ColorParams;
7use crate::eq::EqParams;
8use crate::project::{Clip, Edge, Lane, LaneKind, Speed};
9use crate::scale::FitPolicy;
10use crate::transform::TransformParams;
11use crate::PlaybackSession;
12
13/// Which part of a copied clip's look a paste carries.
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub enum Part {
16 Color,
17 Effects,
18 Transform,
19 Speed,
20 Audio,
21}
22
23impl Part {
24 fn word(self) -> &'static str {
25 match self {
26 Part::Color => "colour",
27 Part::Effects => "effects",
28 Part::Transform => "transform",
29 Part::Speed => "speed",
30 Part::Audio => "audio",
31 }
32 }
33}
34
35/// What a copy remembers of the clip, read at the moment of the copy so a later
36/// edit of the source does not change what the paste brings. The picture half
37/// and the sound half are both kept: copying either clip of a linked take
38/// copies the take's look.
39#[derive(Clone, Debug)]
40pub struct CopiedLook {
41 picture: Option<PictureLook>,
42 audio: Option<AudioLook>,
43 speed: SpeedLook,
44}
45
46#[derive(Clone, Debug)]
47pub struct PictureLook {
48 color: Option<ColorParams>,
49 transform: Option<TransformParams>,
50 fit: FitPolicy,
51 effects: Vec<crate::effects::Effect>,
52}
53
54#[derive(Clone, Debug)]
55pub struct AudioLook {
56 gain_db: f32,
57 eq: Option<EqParams>,
58}
59
60#[derive(Clone, Debug)]
61pub struct SpeedLook {
62 speed: Speed,
63 keys: Vec<crate::project::SpeedKey>,
64 reversed: bool,
65}
66
67/// The clip on a lane of `kind` that shares `(lane, idx)`'s group, if any.
68pub fn linked_of_kind(
69 session: &PlaybackSession,
70 (lane, idx): (Lane, usize),
71 kind: LaneKind,
72) -> Option<(Lane, usize)> {
73 let clip = session.lane_clips(lane).get(idx)?;
74 if lane.kind == kind {
75 return Some((lane, idx));
76 }
77 let id = clip.link?;
78 session.lanes().into_iter().filter(|l| l.kind == kind).find_map(|l| {
79 let i = session.lane_clips(l).iter().position(|c| c.link == Some(id))?;
80 Some((l, i))
81 })
82}
83
84/// What a paste did: how many things took it, which parts, and what was refused.
85pub struct PasteReport {
86 pub touched: usize,
87 pub words: Vec<&'static str>,
88 pub why: Vec<String>,
89}
90
91/// Pastes `parts` of `look` onto `picks`, as one undo step. A picture part
92/// reaches the picture half of each pick's take, the audio part the sound
93/// half; speed reaches the picks themselves.
94pub fn paste_look(
95 session: &mut PlaybackSession,
96 look: &CopiedLook,
97 picks: &[(Lane, usize)],
98 parts: &[Part],
99) -> PasteReport {
100 let targets = |session: &PlaybackSession, kind: LaneKind| {
101 let mut out: Vec<(Lane, usize)> = Vec::new();
102 for &p in picks {
103 if let Some(t) = linked_of_kind(session, p, kind)
104 && !out.contains(&t)
105 {
106 out.push(t);
107 }
108 }
109 out
110 };
111 let mut words: Vec<&'static str> = Vec::new();
112 let mut why: Vec<String> = Vec::new();
113 let mut touched = 0usize;
114 session.begin_batch();
115 for &part in parts {
116 let applied = match part {
117 Part::Color | Part::Effects | Part::Transform => match &look.picture {
118 None => {
119 why.push(format!("{}: the copied clip has no picture", part.word()));
120 0
121 }
122 Some(pic) => {
123 let mut n = 0;
124 for (l, i) in targets(session, LaneKind::Video) {
125 let ok = match part {
126 Part::Color => session.set_color(l, i, pic.color),
127 Part::Effects => session.set_effects(l, i, pic.effects.clone()),
128 _ => {
129 let a = session.set_transform(l, i, pic.transform);
130 let b = session.set_fit(l, i, pic.fit);
131 a || b
132 }
133 };
134 n += usize::from(ok);
135 }
136 n
137 }
138 },
139 Part::Audio => match &look.audio {
140 None => {
141 why.push("audio: the copied clip has no sound".into());
142 0
143 }
144 Some(snd) => {
145 let mut n = 0;
146 for (l, i) in targets(session, LaneKind::Audio) {
147 let a = session.set_clip_gain(l, i, snd.gain_db);
148 let b = session.set_eq(l, i, snd.eq.clone());
149 n += usize::from(a || b);
150 }
151 n
152 }
153 },
154 Part::Speed => {
155 let mut n = 0;
156 let mut refused = 0;
157 for &(l, i) in picks {
158 let sp = &look.speed;
159 let mut ok = session.reversed_of(l, i) == sp.reversed
160 || session.set_reverse(l, i, sp.reversed).is_ok();
161 ok &= session.speed_of(l, i) == sp.speed || session.set_speed(l, i, sp.speed).is_ok();
162 if !sp.keys.is_empty() {
163 ok &= session.set_speed_ramp(l, i, &sp.keys).is_ok();
164 }
165 match ok {
166 true => n += 1,
167 false => refused += 1,
168 }
169 }
170 if refused > 0 {
171 why.push(format!("speed: no room on {refused} clip(s)"));
172 }
173 n
174 }
175 };
176 touched += applied;
177 if applied > 0 {
178 words.push(part.word());
179 }
180 }
181 session.end_batch();
182 PasteReport { touched, words, why }
183}
184
185/// Moves `picks` (and their groups) `frames` along, all or nothing. `Err` says why not.
186pub fn nudge(session: &mut PlaybackSession, picks: &[(Lane, usize)], frames: i64) -> Result<(), &'static str> {
187 let &(lane, idx) = picks.last().ok_or("select the clips to move")?;
188 let start = session.lane_clips(lane).get(idx).ok_or("that clip is gone")?.start;
189 let to = (i64::from(start) + frames).max(0) as u32;
190 if to == start {
191 return Err("already at the start of the timeline");
192 }
193 match session.move_selection_to(picks, lane, idx, lane, to) {
194 true => Ok(()),
195 false => Err("a neighbouring clip is in the way"),
196 }
197}
198
199/// The split edit: moves the `audio` (else picture) edge of `anchor`'s take to
200/// `frame`, the edge nearer the frame being the one that moves. Unlinks first,
201/// because a group trims together. Returns the clip and the edge it moved to; on
202/// `Err` nothing has changed.
203pub fn split_edit_in(
204 session: &mut PlaybackSession,
205 anchor: (Lane, usize),
206 audio: bool,
207 frame: u32,
208) -> Result<(Lane, usize, Edge, u32), String> {
209 split_edit_at(session, anchor, audio, None, frame)
210}
211
212/// [`split_edit_in`] with the edge chosen: `Some(edge)` moves that edge (`Start` the in
213/// edge, `End` the out edge) and refuses a frame on the wrong side of the other one.
214/// `None` picks the edge nearer `frame`.
215pub fn split_edit_at(
216 session: &mut PlaybackSession,
217 anchor: (Lane, usize),
218 audio: bool,
219 edge: Option<Edge>,
220 frame: u32,
221) -> Result<(Lane, usize, Edge, u32), String> {
222 let kind = if audio { LaneKind::Audio } else { LaneKind::Video };
223 let (lane, idx) = linked_of_kind(session, anchor, kind).ok_or_else(|| {
224 format!("select the {} clip or group it with its partner", if audio { "sound" } else { "picture" })
225 })?;
226 if session.lane_locked(lane) {
227 return Err(format!("{} is locked", lane.label()));
228 }
229 let c = session.lane_clips(lane).get(idx).ok_or("that clip is gone")?.clone();
230 let edge = match edge {
231 Some(Edge::Start) if frame >= c.end() => return Err("the in edge would pass the out edge".into()),
232 Some(Edge::End) if frame <= c.start => return Err("the out edge would pass the in edge".into()),
233 Some(edge) => edge,
234 None if frame >= c.end() => Edge::End,
235 None if frame <= c.start || frame - c.start < c.end() - frame => Edge::Start,
236 None => Edge::End,
237 };
238 let before = if edge == Edge::Start { c.start } else { c.end() };
239 if before == frame {
240 return Err("that edge is already at the playhead".into());
241 }
242 let pushed = session.history_pushes();
243 session.begin_batch();
244 session.ungroup(lane, idx);
245 let ok = session.trim_clip(lane, idx, edge, frame);
246 session.end_batch();
247 if !ok {
248 // Only a batch that changed something left a step to take back.
249 if session.history_pushes() > pushed {
250 session.undo();
251 }
252 return Err("no room to move that edge there".into());
253 }
254 let now = session.lane_clips(lane).get(idx).map_or(frame, |c| if edge == Edge::Start { c.start } else { c.end() });
255 Ok((lane, idx, edge, now))
256}
257
258/// Where in which file the clip at `(lane, idx)` shows the timeline frame
259/// `frame`: the library path, the audio stream and the seconds into the file.
260pub fn matched_source(
261 session: &PlaybackSession,
262 (lane, idx): (Lane, usize),
263 frame: u32,
264 fps: f64,
265) -> Option<(PathBuf, usize, f64)> {
266 let clip = session.lane_clips(lane).get(idx)?;
267 if crate::project::is_sequence_source(clip.source) {
268 return None;
269 }
270 let src = session.sources().get(clip.source)?;
271 let into = frame.saturating_sub(clip.start).min(clip.frames().saturating_sub(1));
272 let from_in = clip.speed.source_at(into);
273 let at = match clip.reversed {
274 true => clip.out_frame.saturating_sub(1).saturating_sub(from_in),
275 false => clip.in_frame + from_in,
276 };
277 let secs = if crate::is_still(&src.path) { 0. } else { f64::from(at) / fps };
278 Some((src.path.clone(), src.audio_stream, secs))
279}
280
281/// Reads the look of the clip at `anchor`, with the other half of its take.
282pub fn look_of(session: &PlaybackSession, anchor: (Lane, usize)) -> Option<CopiedLook> {
283 let (lane, idx) = anchor;
284 let clip = session.lane_clips(lane).get(idx)?;
285 let picture = linked_of_kind(session, anchor, LaneKind::Video).map(|(l, i)| PictureLook {
286 color: session.color_of(l, i).copied(),
287 transform: session.transform_of(l, i).copied(),
288 fit: session.fit_of(l, i),
289 effects: session.effects_of(l, i).to_vec(),
290 });
291 let audio = linked_of_kind(session, anchor, LaneKind::Audio).map(|(l, i)| AudioLook {
292 gain_db: session.clip_gain_of(l, i).unwrap_or(0.),
293 eq: session.eq_of(l, i).cloned(),
294 });
295 Some(CopiedLook {
296 picture,
297 audio,
298 speed: SpeedLook { speed: clip.speed, keys: clip.speed_keys.clone(), reversed: clip.reversed },
299 })
300}
301
302/// The replace edit's plan: the `(lane, clip)` halves that overwrite the clip at
303/// `(lane, idx)` exactly -- same start, same length -- with `source` from `in_f`,
304/// the linked other half of the take included when it covers the same frames and
305/// the source has that half. `total` is the source's length in frames.
306/// Where a replace lands: its start, its length and the clips to place.
307pub type ReplacePlan = (u32, u32, Vec<(Lane, Clip)>);
308
309pub fn replace_plan(
310 session: &PlaybackSession,
311 (lane, idx): (Lane, usize),
312 source: usize,
313 in_f: u32,
314 total: u32,
315 (picture, sound, still): (bool, bool, bool),
316) -> Result<ReplacePlan, String> {
317 let old = session.lane_clips(lane).get(idx).ok_or("that clip is gone")?.clone();
318 let len = old.end() - old.start;
319 if !still && in_f + len > total {
320 return Err(format!("the item has {} frames after its start; the clip is {len}", total.saturating_sub(in_f)));
321 }
322 match lane.kind {
323 LaneKind::Video if !picture => return Err("that item has no picture".into()),
324 LaneKind::Audio if !sound => return Err("that item has no sound".into()),
325 _ => {}
326 }
327 let replacement = Clip::source_range(source, in_f, in_f + len);
328 let mut items = vec![(lane, replacement.clone())];
329 let other = if lane.kind == LaneKind::Video { LaneKind::Audio } else { LaneKind::Video };
330 if let Some((pl, pi)) = linked_of_kind(session, (lane, idx), other)
331 && let Some(p) = session.lane_clips(pl).get(pi)
332 && (p.start, p.end()) == (old.start, old.end())
333 && ((pl.kind == LaneKind::Audio && sound) || (pl.kind == LaneKind::Video && picture))
334 {
335 items.push((pl, replacement));
336 }
337 Ok((old.start, len, items))
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 fn open() -> PlaybackSession {
345 crate::ao::set_silent_output();
346 let p = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
347 PlaybackSession::open(p).expect("open the fixture")
348 }
349
350 #[test]
351 fn replace_plan_keeps_place_and_length_and_takes_the_linked_half() {
352 let s = open();
353 let len = s.lane_clips(Lane::V1)[0].frames();
354 let total = s.file_frames(&s.sources()[0].path);
355 let (at, n, items) = replace_plan(&s, (Lane::V1, 0), 0, 0, total, (true, true, false)).expect("plan");
356 assert_eq!((at, n), (0, len));
357 let lanes: Vec<Lane> = items.iter().map(|(l, _)| *l).collect();
358 assert_eq!(lanes, vec![Lane::V1, Lane::A1]);
359 assert!(items.iter().all(|(_, c)| (c.in_frame, c.out_frame) == (0, len)));
360 // A picture-only item cannot replace a sound clip, and a short item is refused with its length.
361 assert!(replace_plan(&s, (Lane::A1, 0), 0, 0, total, (true, false, false)).is_err());
362 assert!(replace_plan(&s, (Lane::V1, 0), 0, 5, len, (true, true, false)).unwrap_err().contains("frames after its start"));
363 }
364
365 #[test]
366 fn matched_source_reads_the_source_time_and_nudge_moves_the_take() {
367 let mut s = open();
368 let fps = 30.0;
369 let (path, _, secs) = matched_source(&s, (Lane::V1, 0), 30, fps).expect("a file");
370 assert!(path.ends_with("test_av.mp4"));
371 assert!((secs - 1.0).abs() < 1e-6, "{secs}");
372 assert!(nudge(&mut s, &[], 5).is_err());
373 nudge(&mut s, &[(Lane::V1, 0)], 10).expect("room after");
374 assert_eq!((s.lane_clips(Lane::V1)[0].start, s.lane_clips(Lane::A1)[0].start), (10, 10));
375 assert!(nudge(&mut s, &[(Lane::V1, 0)], 0).is_err(), "no distance is nothing to do");
376 }
377}