forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

multicam.rs395 lines, 17.7 KiBHistoryRawDownload
1//! Multicam clips: several cameras of one event, synced, cut between by angle.
2//!
3//! A multicam clip is a compound clip ([`super::sequence`]) whose sequence is flagged as a
4//! multicam source: angle `n` is that sequence's `n`th video lane and `n`th audio lane, each
5//! holding one camera's clip placed at its sync offset. On the timeline the compound clip carries
6//! an [`Angle`](super::Angle): the render plays that angle's picture, and its sound too unless the
7//! sound is pinned to another angle. Cutting between cameras is a razor cut plus a new angle on
8//! the right half ([`Project::switch_angle`]), so a multicam cut is a row of plain compound clips
9//! side by side, each trimmed with the ordinary tools. [`Project::flatten_multicam`] turns them
10//! into the camera clips they play.
11
12use super::sequence::{MAX_SEQUENCE_NAME_CHARS, SeqData};
13use super::*;
14
15/// The most angles a multicam clip holds (the angle monitor is a 3x3 grid, the number keys 1-9).
16pub const MAX_ANGLES: usize = 9;
17
18/// One camera of a multicam clip, as [`Project::make_multicam`] takes it.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct AngleSpec {
21 /// Index into [`Project::sources`].
22 pub source: usize,
23 /// What the angle is called; empty for "Angle N".
24 pub name: String,
25 /// The source's length in timeline frames.
26 pub frames: u32,
27 /// Where the camera's first frame sits on the common timeline of the multicam clip.
28 pub start: u32,
29 /// Whether the source has a sound track to put on the angle's audio lane.
30 pub audio: bool,
31}
32
33/// The multicam clip at a frame ([`Project::multicam_under`]).
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct MulticamUnder {
36 pub lane: Lane,
37 pub idx: usize,
38 /// The multicam source sequence.
39 pub sequence: u32,
40 pub names: Vec<String>,
41 /// The angle (from 0) the clip shows there.
42 pub shown: usize,
43}
44
45/// What [`Project::make_multicam`] made.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct MulticamMade {
48 /// The multicam source sequence.
49 pub sequence: u32,
50 /// The compound clips now on the timeline (picture, then sound when there is any).
51 pub clips: Vec<(Lane, usize)>,
52}
53
54impl Project {
55 /// The multicam sequence a clip plays and its angle names, when it is a multicam clip.
56 pub fn multicam_of(&self, clip: &Clip) -> Option<(u32, &[String])> {
57 let id = self.compound_of(clip)?;
58 self.angle_names(id).map(|n| (id, n))
59 }
60
61 /// The multicam clip showing at timeline `frame` on the lowest video lane that has one: its
62 /// lane, index, source sequence, angle names, and the angle it shows there.
63 pub fn multicam_under(&self, frame: u32) -> Option<MulticamUnder> {
64 for lane in self.lanes().into_iter().filter(|l| l.kind == LaneKind::Video) {
65 let Some((idx, c)) = self.lane(lane).iter().enumerate().find(|(_, c)| c.start <= frame && frame < c.end()) else {
66 continue;
67 };
68 if let Some((sequence, names)) = self.multicam_of(c) {
69 let shown = usize::from(c.angle.video).min(names.len().saturating_sub(1));
70 return Some(MulticamUnder { lane, idx, sequence, names: names.to_vec(), shown });
71 }
72 }
73 None
74 }
75
76 /// One flattened project per angle of the multicam clip under `frame`, each with that clip
77 /// showing the angle: what the angle monitor composes its tiles from. `None` with no multicam
78 /// clip there.
79 pub fn angle_views(&self, frame: u32) -> Option<(MulticamUnder, Vec<Project>)> {
80 let under = self.multicam_under(frame)?;
81 let mut views = Vec::new();
82 for n in 0..under.names.len() {
83 let mut p = self.raw_snapshot();
84 let idx = self.index(under.lane)?;
85 let clip = p.lanes.get_mut(idx)?.clips.get_mut(under.idx)?;
86 clip.angle.video = n as u8;
87 views.push(p.export_snapshot());
88 }
89 Some((under, views))
90 }
91
92 /// Makes a multicam source from `angles` and puts one clip of it (picture on `lane`, sound on
93 /// the audio lane of the same number, linked) at `at`. One undo step. Refused for fewer than
94 /// two or more than [`MAX_ANGLES`] angles, an unknown source, an empty angle, a lane that is
95 /// not a video lane, or the sequence limit.
96 pub fn make_multicam(&mut self, name: Option<&str>, angles: &[AngleSpec], lane: Lane, at: u32) -> crate::Result<MulticamMade> {
97 if angles.len() < 2 || angles.len() > MAX_ANGLES {
98 return Err(format!("a multicam clip needs 2 to {MAX_ANGLES} angles, got {}", angles.len()).into());
99 }
100 if lane.kind != LaneKind::Video || self.index(lane).is_none() {
101 return Err("a multicam clip goes on a video lane".into());
102 }
103 if self.seq.names.len() >= MAX_SEQUENCES {
104 return Err(format!("a project holds at most {MAX_SEQUENCES} sequences").into());
105 }
106 for a in angles {
107 if a.source >= self.sources.len() {
108 return Err(format!("angle source {} is not in the project", a.source).into());
109 }
110 if a.frames == 0 {
111 return Err("an angle has no frames".into());
112 }
113 }
114 let title = match name {
115 Some(n) => self.unique_name(n, None)?,
116 None => self.fresh_name("Multicam"),
117 };
118 let names: Vec<String> = angles
119 .iter()
120 .enumerate()
121 .map(|(i, a)| match a.name.trim() {
122 "" => format!("Angle {}", i + 1),
123 n => n.chars().take(MAX_SEQUENCE_NAME_CHARS).collect(),
124 })
125 .collect();
126 let len = angles.iter().map(|a| a.start + a.frames).max().unwrap_or(1);
127 self.snapshot();
128 let mut video = Vec::new();
129 let mut audio = Vec::new();
130 for a in angles {
131 let link = a.audio.then(|| self.new_link());
132 let mut v = Clip::source_range(a.source, 0, a.frames);
133 v.start = a.start;
134 v.link = link;
135 video.push(LaneData::new(LaneKind::Video, vec![v]));
136 let mut sound = Vec::new();
137 if a.audio {
138 let mut s = Clip::source_range(a.source, 0, a.frames);
139 s.start = a.start;
140 s.link = link;
141 sound.push(s);
142 }
143 audio.push(LaneData::new(LaneKind::Audio, sound));
144 }
145 let id = self.seq_next;
146 self.seq_next += 1;
147 let pos = self.seq.names.iter().position(|(i, _)| *i == self.seq.active).map_or(self.seq.names.len(), |p| p + 1);
148 self.seq.names.insert(pos, (id, title));
149 let mut data = SeqData::empty();
150 data.lanes = video.into_iter().chain(audio).collect();
151 self.seq.parked.push((id, data));
152 self.seq.mcam.push((id, names));
153 let alane = Lane::new(LaneKind::Audio, lane.ord);
154 while self.lane_count(LaneKind::Audio) <= alane.ord {
155 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
156 }
157 let link = self.new_link();
158 let mut made = Vec::new();
159 for target in [lane, alane] {
160 let mut c = Clip::source_range(sequence_source(id), 0, len);
161 c.start = at;
162 c.link = Some(link);
163 self.insert_over(target, c, &[]);
164 if let Some(i) = self.lane(target).iter().position(|x| x.start == at && x.source == sequence_source(id)) {
165 made.push((target, i));
166 }
167 }
168 self.flat.clear();
169 Ok(MulticamMade { sequence: id, clips: made })
170 }
171
172 /// Cuts the multicam clip under `frame` (on `lane`, or the lowest video lane that has one)
173 /// there and shows `video` from that frame on, as one undo step; `audio` is `Some(None)` to
174 /// make the sound follow the picture, `Some(Some(n))` to keep it on angle `n`. A cut at the
175 /// clip's own start is not needed and changes the whole clip. Returns the clips that now
176 /// carry the new angle (lane and start). Refused with nothing changed when there is no
177 /// multicam clip there, the angle does not exist, or nothing would change.
178 pub fn switch_angle(
179 &mut self,
180 lane: Option<Lane>,
181 frame: u32,
182 video: Option<u8>,
183 audio: Option<Option<u8>>,
184 ) -> crate::Result<Vec<(Lane, u32)>> {
185 if video.is_none() && audio.is_none() {
186 return Err("name an angle for the picture or for the sound".into());
187 }
188 let lanes: Vec<Lane> = match lane {
189 Some(l) => vec![l],
190 None => self.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).collect(),
191 };
192 let mut found = None;
193 for l in lanes {
194 if let Some(c) = self.lane(l).iter().find(|c| c.start <= frame && frame < c.end())
195 && self.multicam_of(c).is_some()
196 {
197 found = Some((l, c.clone()));
198 break;
199 }
200 }
201 let Some((vlane, head)) = found else {
202 return Err("there is no multicam clip there: park the playhead on one".into());
203 };
204 let (id, names) = self.multicam_of(&head).map(|(i, n)| (i, n.len())).unwrap_or((0, 0));
205 for a in video.into_iter().chain(audio.flatten()) {
206 if usize::from(a) >= names {
207 return Err(format!("angle {} does not exist: \"{}\" has {names}", a + 1, self.sequence_name(id).unwrap_or("multicam")).into());
208 }
209 }
210 // The group the cut touches: the picture clip and the sound clips linked to it.
211 let src = head.source;
212 let mut group: Vec<Lane> = vec![vlane];
213 if let Some(link) = head.link {
214 for l in self.lanes().into_iter().filter(|l| l.kind == LaneKind::Audio) {
215 if self.lane(l).iter().any(|c| c.link == Some(link) && c.source == src && c.start <= frame && frame < c.end()) {
216 group.push(l);
217 }
218 }
219 }
220 let apply = |c: &mut Clip| {
221 if let Some(v) = video {
222 c.angle.video = v;
223 }
224 if let Some(a) = audio {
225 c.angle.audio = a;
226 }
227 };
228 let current: Vec<Angle> = group
229 .iter()
230 .filter_map(|&l| self.lane(l).iter().find(|c| c.start <= frame && frame < c.end()).map(|c| c.angle))
231 .collect();
232 let mut probe = current.clone();
233 for a in &mut probe {
234 let mut c = Clip::source_range(0, 0, 1);
235 c.angle = *a;
236 apply(&mut c);
237 *a = c.angle;
238 }
239 if probe == current {
240 return Err("that angle is already showing there".into());
241 }
242 self.snapshot();
243 let idxs: Vec<usize> = group.iter().filter_map(|&l| self.index(l)).collect();
244 self.write_split(frame, false, &idxs);
245 let mut touched = Vec::new();
246 for &l in &group {
247 let Some(clips) = self.lane_mut(l) else { continue };
248 if let Some(c) = clips.iter_mut().find(|c| c.start <= frame && frame < c.end() && c.source == src) {
249 apply(c);
250 touched.push((l, c.start));
251 }
252 }
253 self.flat.clear();
254 Ok(touched)
255 }
256
257 /// Replaces the multicam clip at `lane`/`idx`, every other clip of the same multicam source in
258 /// this sequence, and their linked partners with the camera clips they play (the angle each
259 /// shows), one undo step. The multicam source sequence stays. Refused, changing nothing,
260 /// when another clip is in the way.
261 pub fn flatten_multicam(&mut self, lane: Lane, idx: usize) -> crate::Result<Vec<(Lane, usize)>> {
262 let Some(c) = self.lane(lane).get(idx) else {
263 return Err(format!("there is no clip {} #{idx}", lane.label()).into());
264 };
265 if self.multicam_of(c).is_none() {
266 return Err(format!("{} #{idx} is not a multicam clip", lane.label()).into());
267 }
268 let src = c.source;
269 let mut picks = Vec::new();
270 for l in self.lanes().into_iter().filter(|l| l.kind != LaneKind::Subtitle) {
271 for (i, o) in self.lane(l).iter().enumerate() {
272 if o.source == src {
273 picks.push((l, i));
274 }
275 }
276 }
277 self.break_apart(&picks)
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 fn spec(source: usize, start: u32, frames: u32, audio: bool) -> AngleSpec {
286 AngleSpec { source, name: String::new(), frames, start, audio }
287 }
288
289 fn pair() -> (Project, MulticamMade) {
290 let mut p = Project::single("/tmp/edith-mcam-a.mp4", 100);
291 p.import("/tmp/edith-mcam-b.mp4", 0);
292 let made = p
293 .make_multicam(Some("Show"), &[spec(0, 10, 100, true), spec(1, 0, 120, true)], Lane::V1, 0)
294 .expect("made");
295 (p, made)
296 }
297
298 type Strip = Vec<(LaneKind, Vec<(u32, u32, u32, usize)>)>;
299 /// What the render reads: every lane's clips as (start, in, out, source).
300 fn strip(p: &Project) -> Strip {
301 let v = p.render_view();
302 v.lanes.iter().map(|l| (l.kind, l.clips.iter().map(|c| (c.start, c.in_frame, c.out_frame, c.source)).collect())).collect()
303 }
304
305 fn lane_of(s: &Strip, kind: LaneKind) -> Vec<(u32, u32, u32, usize)> {
306 s.iter().find(|(k, _)| *k == kind).map(|(_, c)| c.clone()).unwrap_or_default()
307 }
308
309 #[test]
310 fn a_multicam_clip_plays_the_first_angle_at_its_sync_offset() {
311 let (p, made) = pair();
312 assert_eq!(made.clips.len(), 2);
313 assert_eq!(p.angle_names(made.sequence).map(<[String]>::to_vec), Some(vec!["Angle 1".to_string(), "Angle 2".to_string()]));
314 let s = strip(&p);
315 assert_eq!(lane_of(&s, LaneKind::Video), vec![(10, 0, 100, 0)]);
316 assert_eq!(lane_of(&s, LaneKind::Audio), vec![(10, 0, 100, 0)]);
317 assert_eq!(p.sequences().len(), 2);
318 }
319
320 #[test]
321 fn switching_the_angle_cuts_the_clip_and_is_one_undo_step() {
322 let (mut p, _) = pair();
323 let before = strip(&p);
324 let touched = p.switch_angle(None, 60, Some(1), None).expect("switch");
325 assert_eq!(touched, vec![(Lane::V1, 60), (Lane::A1, 60)]);
326 let s = strip(&p);
327 assert_eq!(lane_of(&s, LaneKind::Video), vec![(10, 0, 50, 0), (60, 60, 120, 1)]);
328 assert_eq!(lane_of(&s, LaneKind::Audio), vec![(10, 0, 50, 0), (60, 60, 120, 1)], "the sound follows the picture");
329 assert_eq!(p.lane(Lane::V1).len(), 2);
330 assert!(p.undo());
331 assert_eq!(strip(&p), before);
332 assert_eq!(p.lane(Lane::V1).len(), 1);
333 assert!(p.redo());
334 assert_eq!(p.lane(Lane::V1).len(), 2);
335 assert!(p.switch_angle(None, 60, Some(1), None).is_err(), "already showing there");
336 assert!(p.switch_angle(None, 61, Some(2), None).is_err(), "no third angle");
337 assert!(p.switch_angle(None, 500, Some(0), None).is_err(), "nothing there");
338 // Back to the first angle half way into the second segment.
339 p.switch_angle(None, 90, Some(0), None).expect("again");
340 assert_eq!(lane_of(&strip(&p), LaneKind::Video), vec![(10, 0, 50, 0), (60, 60, 90, 1), (90, 80, 100, 0)]);
341 }
342
343 #[test]
344 fn the_sound_can_stay_on_an_angle() {
345 let (mut p, _) = pair();
346 p.switch_angle(None, 60, Some(1), Some(Some(0))).expect("switch");
347 let s = strip(&p);
348 assert_eq!(lane_of(&s, LaneKind::Video), vec![(10, 0, 50, 0), (60, 60, 120, 1)]);
349 assert_eq!(lane_of(&s, LaneKind::Audio), vec![(10, 0, 50, 0), (60, 50, 100, 0)], "angle 1's sound plays on under angle 2");
350 // The next cut keeps the pin; asking the sound to follow again lifts it.
351 p.switch_angle(None, 100, Some(0), None).expect("next");
352 assert_eq!(p.lane(Lane::A1)[2].angle, Angle { video: 0, audio: Some(0) });
353 p.switch_angle(None, 100, None, Some(None)).expect("lift the pin");
354 assert_eq!(p.lane(Lane::A1)[2].angle, Angle { video: 0, audio: None });
355 assert!(p.switch_angle(None, 100, None, Some(None)).is_err(), "the sound already follows");
356 }
357
358 #[test]
359 fn flattening_leaves_the_render_as_it_was() {
360 let (mut p, _) = pair();
361 p.switch_angle(None, 60, Some(1), None).expect("switch");
362 p.switch_angle(None, 90, Some(0), Some(Some(1))).expect("switch");
363 let before = strip(&p);
364 let out = p.flatten_multicam(Lane::V1, 1).expect("flatten");
365 assert_eq!(out.len(), 6, "three picture and three sound clips");
366 assert!(p.lanes.iter().flat_map(|l| &l.clips).all(|c| !is_sequence_source(c.source)), "plain clips only");
367 assert_eq!(strip(&p), before);
368 assert!(p.undo());
369 assert!(p.lane(Lane::V1).iter().all(|c| is_sequence_source(c.source)));
370 assert!(p.flatten_multicam(Lane::V1, 7).is_err());
371 }
372
373 #[test]
374 fn a_multicam_needs_two_to_nine_angles_and_a_video_lane() {
375 let (mut p, _) = pair();
376 assert!(p.make_multicam(None, &[spec(0, 0, 10, true)], Lane::V1, 0).is_err());
377 let ten: Vec<AngleSpec> = (0..10).map(|_| spec(0, 0, 10, true)).collect();
378 assert!(p.make_multicam(None, &ten, Lane::V1, 0).is_err());
379 assert!(p.make_multicam(None, &[spec(0, 0, 10, true), spec(5, 0, 10, true)], Lane::V1, 0).is_err());
380 assert!(p.make_multicam(None, &[spec(0, 0, 10, true), spec(1, 0, 10, true)], Lane::A1, 0).is_err());
381 assert!(p.make_multicam(Some("Show"), &[spec(0, 0, 10, true), spec(1, 0, 10, true)], Lane::V1, 0).is_err(), "name taken");
382 }
383
384 #[test]
385 fn deleting_or_copying_a_multicam_source_keeps_its_angles_straight() {
386 let (mut p, made) = pair();
387 assert!(p.delete_sequence(made.sequence).is_err(), "a clip plays it");
388 let copy = p.duplicate_sequence(made.sequence).expect("copy");
389 assert_eq!(p.angle_count(copy), Some(2));
390 p.delete_sequence(copy).expect("delete");
391 assert_eq!(p.angle_count(copy), None);
392 assert!(p.undo());
393 assert_eq!(p.angle_count(copy), Some(2));
394 }
395}