edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | //! Sequences and compound (nested) clips. |
| 2 | //! |
| 3 | //! A project holds N named timelines -- *sequences* -- and exactly one is |
| 4 | //! active. The active one lives where every other edit already looks for it (the |
| 5 | //! project's own `lanes`, `titles`, `chapters`, ...), so nothing that edits a |
| 6 | //! timeline had to learn about sequences; the others are *parked* here, whole, |
| 7 | //! and [`Project::switch_sequence`] swaps one for the other. Resolution, rate, |
| 8 | //! limiter and the like stay project-wide ([`ProjectSettings`]). |
| 9 | //! |
| 10 | //! A **compound clip** is an ordinary [`Clip`] whose `source` is a sequence |
| 11 | //! rather than a file: `source = SEQ_BASE + id`. Its `[in_frame, out_frame)` is a |
| 12 | //! window of the inner sequence's timeline, counted in timeline frames, and it |
| 13 | //! is placed like any clip. A compound clip on a video lane plays the inner |
| 14 | //! sequence's picture, on an audio lane the inner sequence's mix; "nest" makes |
| 15 | //! one of each, linked. |
| 16 | //! |
| 17 | //! Playback and export never see a compound clip: they read |
| 18 | //! [`Project::render_view`], the active sequence with every compound clip |
| 19 | //! expanded in place into the inner clips it stands for, trimmed to the window |
| 20 | //! and shifted to the clip's start. A nested render is therefore the flat |
| 21 | //! render of the same clips, by construction. A compound clip plays at normal |
| 22 | //! speed forward only ([`Project::set_speed`] and friends refuse it). Its own |
| 23 | //! placement (position, scale, turn, opacity) and colour are laid over each inner clip when the |
| 24 | //! view is built ([`put_over`]); its effects and crop are not applied -- they belong on the |
| 25 | //! clips inside. |
| 26 | |
| 27 | use super::*; |
| 28 | use crate::transform::TransformParams; |
| 29 | use std::sync::{Arc, Mutex}; |
| 30 | |
| 31 | /// A clip whose `source` is at least this names a sequence (`source - SEQ_BASE`), |
| 32 | /// not an entry of [`Project::sources`]. |
| 33 | pub const SEQ_BASE: usize = 1 << 30; |
| 34 | |
| 35 | /// The most sequences a project holds. |
| 36 | pub const MAX_SEQUENCES: usize = 64; |
| 37 | |
| 38 | /// The longest a sequence name may be, in characters. |
| 39 | pub const MAX_SEQUENCE_NAME_CHARS: usize = 100; |
| 40 | |
| 41 | /// How deep compound clips may nest when rendering (a guard behind the cycle |
| 42 | /// check, which already makes a loop impossible). |
| 43 | const MAX_NEST_DEPTH: usize = 8; |
| 44 | |
| 45 | /// Whether a clip's `source` names a sequence. |
| 46 | pub fn is_sequence_source(source: usize) -> bool { |
| 47 | source >= SEQ_BASE |
| 48 | } |
| 49 | |
| 50 | /// The `source` value of a clip that plays sequence `id`. |
| 51 | pub fn sequence_source(id: u32) -> usize { |
| 52 | SEQ_BASE + id as usize |
| 53 | } |
| 54 | |
| 55 | /// The sequence a clip's `source` names, if it names one. |
| 56 | pub fn sequence_id_of(source: usize) -> Option<u32> { |
| 57 | source.checked_sub(SEQ_BASE).and_then(|n| u32::try_from(n).ok()) |
| 58 | } |
| 59 | |
| 60 | /// Everything about a timeline that is not project-wide. |
| 61 | #[derive(Clone, Debug, PartialEq)] |
| 62 | pub(super) struct SeqData { |
| 63 | pub(super) lanes: Vec<LaneData>, |
| 64 | pub(super) subtitles: Vec<SubtitleTrack>, |
| 65 | pub(super) cue_edits: Vec<(usize, usize, String)>, |
| 66 | pub(super) cue_adds: Vec<AddedCue>, |
| 67 | pub(super) titles: Vec<Title>, |
| 68 | pub(super) chapters: Vec<Chapter>, |
| 69 | pub(super) markers: Vec<Marker>, |
| 70 | } |
| 71 | |
| 72 | impl SeqData { |
| 73 | pub(super) fn empty() -> Self { |
| 74 | Self { |
| 75 | lanes: LaneData::two_lanes(Vec::new(), Vec::new()), |
| 76 | subtitles: Vec::new(), |
| 77 | cue_edits: Vec::new(), |
| 78 | cue_adds: Vec::new(), |
| 79 | titles: Vec::new(), |
| 80 | chapters: Vec::new(), |
| 81 | markers: Vec::new(), |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// The sequence list: which one is active, every name in tab order, and the |
| 87 | /// data of the ones that are not active. In every undo step, so a new, renamed |
| 88 | /// or deleted sequence undoes with the rest. |
| 89 | #[derive(Clone, Debug, PartialEq)] |
| 90 | pub(super) struct Seqs { |
| 91 | pub(super) active: u32, |
| 92 | pub(super) names: Vec<(u32, String)>, |
| 93 | pub(super) parked: Vec<(u32, SeqData)>, |
| 94 | /// The sequences that are multicam clips' sources, each with its angle names in lane order: |
| 95 | /// angle `n` is the `n`th video lane and the `n`th audio lane of that sequence. |
| 96 | pub(super) mcam: Vec<(u32, Vec<String>)>, |
| 97 | /// The sequences Nest made under its default name and that nothing has renamed since. Only |
| 98 | /// these may be dropped when a break-apart leaves them unplayed; a name never decides it. |
| 99 | /// Not written to the project file: after a reopen such a tab is kept, never removed. |
| 100 | pub(super) nested: Vec<u32>, |
| 101 | } |
| 102 | |
| 103 | impl Seqs { |
| 104 | pub(super) fn single() -> Self { |
| 105 | Self { active: 0, names: vec![(0, "Sequence 1".to_string())], parked: Vec::new(), mcam: Vec::new(), nested: Vec::new() } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// One row of [`Project::sequences`]. |
| 110 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 111 | pub struct SequenceInfo { |
| 112 | pub id: u32, |
| 113 | pub name: String, |
| 114 | pub active: bool, |
| 115 | /// Its length in timeline frames. |
| 116 | pub frames: u32, |
| 117 | /// How many compound clips in other sequences play it. |
| 118 | pub used: usize, |
| 119 | } |
| 120 | |
| 121 | /// What [`Project::nest`] made. |
| 122 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 123 | pub struct Nested { |
| 124 | /// The new sequence. |
| 125 | pub sequence: u32, |
| 126 | /// The compound clips now standing where the selection was. |
| 127 | pub clips: Vec<(Lane, usize)>, |
| 128 | } |
| 129 | |
| 130 | /// The expanded timeline cache behind [`Project::render_view`]. |
| 131 | #[derive(Default)] |
| 132 | pub(super) struct FlatCache(Mutex<Option<(u64, Arc<Project>)>>); |
| 133 | |
| 134 | impl Clone for FlatCache { |
| 135 | fn clone(&self) -> Self { |
| 136 | Self::default() |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | impl std::fmt::Debug for FlatCache { |
| 141 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 142 | f.write_str("FlatCache") |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | impl FlatCache { |
| 147 | pub(super) fn clear(&self) { |
| 148 | if let Ok(mut g) = self.0.lock() { |
| 149 | *g = None; |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// What playback and export read: the project itself, or its expanded copy. |
| 155 | pub enum RenderView<'a> { |
| 156 | Same(&'a Project), |
| 157 | Flat(Arc<Project>), |
| 158 | } |
| 159 | |
| 160 | impl std::ops::Deref for RenderView<'_> { |
| 161 | type Target = Project; |
| 162 | fn deref(&self) -> &Project { |
| 163 | match self { |
| 164 | RenderView::Same(p) => p, |
| 165 | RenderView::Flat(p) => p, |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// The part of `c` between clip-relative timeline frames `from..to`, placed at |
| 171 | /// `start`. `None` when nothing of it is in there. |
| 172 | fn piece(c: &Clip, from: u32, to: u32, start: u32) -> Option<Clip> { |
| 173 | let len = c.frames(); |
| 174 | let (from, to) = (from.min(len), to.min(len)); |
| 175 | if from >= to { |
| 176 | return None; |
| 177 | } |
| 178 | let mut p = c.clone(); |
| 179 | if from > 0 { |
| 180 | let off = c.source_offset(from); |
| 181 | match c.reversed { |
| 182 | true => p.out_frame = c.out_frame.saturating_sub(off), |
| 183 | false => p.in_frame = c.in_frame + off, |
| 184 | } |
| 185 | if !c.speed_keys.is_empty() { |
| 186 | p.speed_keys = ramp_keys_from(&c.speed_keys, from); |
| 187 | } |
| 188 | p.fade_in = 0; |
| 189 | } |
| 190 | if p.out_frame <= p.in_frame { |
| 191 | return None; |
| 192 | } |
| 193 | let want = to - from; |
| 194 | if p.frames() > want { |
| 195 | let src = p.fit_source(want)?; |
| 196 | match c.reversed { |
| 197 | true => p.in_frame = p.out_frame - src, |
| 198 | false => p.out_frame = p.in_frame + src, |
| 199 | } |
| 200 | p.fade_out = 0; |
| 201 | p.transition_out = 0; |
| 202 | } |
| 203 | if p.out_frame <= p.in_frame { |
| 204 | return None; |
| 205 | } |
| 206 | p.fade_in = p.fade_in.min(p.frames()); |
| 207 | p.fade_out = p.fade_out.min(p.frames()); |
| 208 | p.transition_out = p.transition_out.min(p.frames()); |
| 209 | p.start = start; |
| 210 | Some(p) |
| 211 | } |
| 212 | |
| 213 | /// The transform and colour tables of the flat copy, which compound clips add composed entries to, |
| 214 | /// with the canvas size a position is measured against. |
| 215 | struct Tables { |
| 216 | transform: Vec<TransformParams>, |
| 217 | color: Vec<ColorParams>, |
| 218 | size: (u32, u32), |
| 219 | } |
| 220 | |
| 221 | impl Tables { |
| 222 | fn transform_at(&mut self, t: TransformParams) -> Option<u16> { |
| 223 | let at = match self.transform.iter().position(|q| *q == t) { |
| 224 | Some(at) => at, |
| 225 | None if self.transform.len() >= usize::from(u16::MAX) => return None, |
| 226 | None => { |
| 227 | self.transform.push(t); |
| 228 | self.transform.len() - 1 |
| 229 | } |
| 230 | }; |
| 231 | Some(at as u16) |
| 232 | } |
| 233 | |
| 234 | fn color_at(&mut self, c: ColorParams) -> Option<u16> { |
| 235 | let at = match self.color.iter().position(|q| *q == c) { |
| 236 | Some(at) => at, |
| 237 | None if self.color.len() >= usize::from(u16::MAX) => return None, |
| 238 | None => { |
| 239 | self.color.push(c); |
| 240 | self.color.len() - 1 |
| 241 | } |
| 242 | }; |
| 243 | Some(at as u16) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | /// `inner` placed on a canvas that `outer` then moves, scales, turns and fades as one picture: |
| 248 | /// the inner position goes through the outer scale and turn, then the outer offset follows. |
| 249 | /// The outer crop is not applied (it would crop the inner crop's frame, which no single |
| 250 | /// placement says). |
| 251 | fn compose_transform(inner: TransformParams, outer: TransformParams, size: (u32, u32)) -> TransformParams { |
| 252 | let (w, h) = (size.0.max(1) as f32, size.1.max(1) as f32); |
| 253 | let (sin, cos) = outer.rotate.to_radians().sin_cos(); |
| 254 | let (x, y) = (inner.pos_x * w * outer.scale, inner.pos_y * h * outer.scale); |
| 255 | TransformParams { |
| 256 | pos_x: (x * cos - y * sin) / w + outer.pos_x, |
| 257 | pos_y: (x * sin + y * cos) / h + outer.pos_y, |
| 258 | scale: inner.scale * outer.scale, |
| 259 | rotate: inner.rotate + outer.rotate, |
| 260 | opacity: inner.opacity * outer.opacity, |
| 261 | ..inner |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// `inner` graded again by `outer`: the sliders stack, the RGB look is the inner one's unless it has none. |
| 266 | fn compose_color(inner: ColorParams, outer: ColorParams) -> ColorParams { |
| 267 | ColorParams { |
| 268 | brightness: (inner.brightness + outer.brightness).clamp(-1.0, 1.0), |
| 269 | contrast: (inner.contrast * outer.contrast).clamp(0.0, 2.0), |
| 270 | saturation: (inner.saturation * outer.saturation).clamp(0.0, 2.0), |
| 271 | tint: (inner.tint + outer.tint).clamp(-1.0, 1.0), |
| 272 | look: if inner.look == crate::color::Look::default() { outer.look } else { inner.look }, |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// Lays a compound clip's own placement and grade over an inner piece `p`. |
| 277 | fn put_over(p: &mut Clip, outer: Option<TransformParams>, grade: Option<ColorParams>, tables: &mut Tables) { |
| 278 | if let Some(o) = outer.filter(|o| !o.is_identity()) { |
| 279 | let size = tables.size; |
| 280 | let base = p.transform.and_then(|i| tables.transform.get(usize::from(i)).copied()).unwrap_or_default(); |
| 281 | p.transform = tables.transform_at(compose_transform(base, o, size)); |
| 282 | for k in &mut p.transform_keys { |
| 283 | k.params = compose_transform(k.params, o, size); |
| 284 | } |
| 285 | for k in &mut p.opacity_keys { |
| 286 | k.opacity = (k.opacity * o.opacity).clamp(0.0, 1.0); |
| 287 | } |
| 288 | } |
| 289 | if let Some(g) = grade { |
| 290 | p.color = match p.color.and_then(|i| tables.color.get(usize::from(i)).copied()) { |
| 291 | Some(inner) => tables.color_at(compose_color(inner, g)), |
| 292 | None => tables.color_at(g), |
| 293 | }; |
| 294 | for k in &mut p.color_keys { |
| 295 | k.params = compose_color(k.params, g); |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | fn compound_ids(lanes: &[LaneData]) -> impl Iterator<Item = u32> + '_ { |
| 301 | lanes |
| 302 | .iter() |
| 303 | .flat_map(|l| &l.clips) |
| 304 | .filter_map(|c| sequence_id_of(c.source)) |
| 305 | } |
| 306 | |
| 307 | fn clean_name(name: &str) -> crate::Result<String> { |
| 308 | let name = name.trim(); |
| 309 | if name.is_empty() { |
| 310 | return Err("a sequence needs a name".into()); |
| 311 | } |
| 312 | if name.chars().count() > MAX_SEQUENCE_NAME_CHARS { |
| 313 | return Err(format!("a sequence name is at most {MAX_SEQUENCE_NAME_CHARS} characters").into()); |
| 314 | } |
| 315 | if name.chars().any(char::is_control) { |
| 316 | return Err("a sequence name is one line of plain text".into()); |
| 317 | } |
| 318 | Ok(name.to_string()) |
| 319 | } |
| 320 | |
| 321 | impl Project { |
| 322 | /// Every sequence in tab order. |
| 323 | pub fn sequences(&self) -> Vec<SequenceInfo> { |
| 324 | self.seq |
| 325 | .names |
| 326 | .iter() |
| 327 | .map(|(id, name)| { |
| 328 | let lanes = self.lanes_of(*id); |
| 329 | let frames = lanes |
| 330 | .map(|ls| ls.iter().flat_map(|l| &l.clips).map(Clip::end).max().unwrap_or(0)) |
| 331 | .unwrap_or(0); |
| 332 | let used = self |
| 333 | .seq |
| 334 | .names |
| 335 | .iter() |
| 336 | .filter(|(other, _)| other != id) |
| 337 | .filter_map(|(other, _)| self.lanes_of(*other)) |
| 338 | .map(|ls| compound_ids(ls).filter(|x| x == id).count()) |
| 339 | .sum(); |
| 340 | SequenceInfo { id: *id, name: name.clone(), active: *id == self.seq.active, frames, used } |
| 341 | }) |
| 342 | .collect() |
| 343 | } |
| 344 | |
| 345 | /// The id of the active sequence. |
| 346 | pub fn active_sequence(&self) -> u32 { |
| 347 | self.seq.active |
| 348 | } |
| 349 | |
| 350 | /// How many sequences the project holds. |
| 351 | pub fn sequence_count(&self) -> usize { |
| 352 | self.seq.names.len() |
| 353 | } |
| 354 | |
| 355 | /// The name of sequence `id`. |
| 356 | pub fn sequence_name(&self, id: u32) -> Option<&str> { |
| 357 | self.seq.names.iter().find(|(i, _)| *i == id).map(|(_, n)| n.as_str()) |
| 358 | } |
| 359 | |
| 360 | /// The sequence called `name` (exact, then ignoring case). |
| 361 | pub fn sequence_named(&self, name: &str) -> Option<u32> { |
| 362 | let name = name.trim(); |
| 363 | self.seq |
| 364 | .names |
| 365 | .iter() |
| 366 | .find(|(_, n)| n == name) |
| 367 | .or_else(|| self.seq.names.iter().find(|(_, n)| n.eq_ignore_ascii_case(name))) |
| 368 | .map(|(i, _)| *i) |
| 369 | } |
| 370 | |
| 371 | /// The sequence a clip plays, when it is a compound clip. |
| 372 | pub fn compound_of(&self, clip: &Clip) -> Option<u32> { |
| 373 | sequence_id_of(clip.source).filter(|id| self.sequence_name(*id).is_some()) |
| 374 | } |
| 375 | |
| 376 | /// How many angles sequence `id` has when it is a multicam source. |
| 377 | pub fn angle_count(&self, id: u32) -> Option<usize> { |
| 378 | self.seq.mcam.iter().find(|(i, _)| *i == id).map(|(_, n)| n.len()) |
| 379 | } |
| 380 | |
| 381 | /// The angle names of sequence `id` when it is a multicam source. |
| 382 | pub fn angle_names(&self, id: u32) -> Option<&[String]> { |
| 383 | self.seq.mcam.iter().find(|(i, _)| *i == id).map(|(_, n)| n.as_slice()) |
| 384 | } |
| 385 | |
| 386 | /// Whether any sequence holds a compound clip, or there is more than one |
| 387 | /// sequence: what makes a saved file v45. |
| 388 | pub fn uses_sequences(&self) -> bool { |
| 389 | self.seq.names.len() > 1 |
| 390 | || self.lanes.iter().flat_map(|l| &l.clips).any(|c| is_sequence_source(c.source)) |
| 391 | } |
| 392 | |
| 393 | /// The rate and the other time-scaled settings cannot be changed once there |
| 394 | /// is more than one sequence (the inner windows are in timeline frames). |
| 395 | pub fn rate_locked(&self) -> bool { |
| 396 | self.uses_sequences() |
| 397 | } |
| 398 | |
| 399 | pub(super) fn lanes_of(&self, id: u32) -> Option<&[LaneData]> { |
| 400 | if id == self.seq.active { |
| 401 | return Some(&self.lanes); |
| 402 | } |
| 403 | self.seq.parked.iter().find(|(i, _)| *i == id).map(|(_, d)| d.lanes.as_slice()) |
| 404 | } |
| 405 | |
| 406 | /// Whether sequence `from` plays, directly or through others, sequence `target`. |
| 407 | fn reaches(&self, from: u32, target: u32) -> bool { |
| 408 | let mut seen = vec![from]; |
| 409 | let mut stack = vec![from]; |
| 410 | while let Some(id) = stack.pop() { |
| 411 | let Some(lanes) = self.lanes_of(id) else { continue }; |
| 412 | for next in compound_ids(lanes) { |
| 413 | if next == target { |
| 414 | return true; |
| 415 | } |
| 416 | if !seen.contains(&next) { |
| 417 | seen.push(next); |
| 418 | stack.push(next); |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | false |
| 423 | } |
| 424 | |
| 425 | /// Why `clip` may not be placed in the active sequence, if it may not: it |
| 426 | /// plays a sequence that does not exist, or one that plays (or is) the |
| 427 | /// active sequence. |
| 428 | pub fn compound_refusal(&self, clip: &Clip) -> Option<String> { |
| 429 | let id = sequence_id_of(clip.source)?; |
| 430 | let Some(name) = self.sequence_name(id) else { |
| 431 | return Some(format!("there is no sequence {id}")); |
| 432 | }; |
| 433 | if id == self.seq.active { |
| 434 | return Some(format!("\"{name}\" cannot contain itself")); |
| 435 | } |
| 436 | if self.reaches(id, self.seq.active) { |
| 437 | let me = self.sequence_name(self.seq.active).unwrap_or("this sequence"); |
| 438 | return Some(format!("\"{name}\" already contains \"{me}\": that would nest a sequence inside itself")); |
| 439 | } |
| 440 | None |
| 441 | } |
| 442 | |
| 443 | /// Whether the clip is refused by [`compound_refusal`](Project::compound_refusal). |
| 444 | pub(super) fn cycles(&self, clip: &Clip) -> bool { |
| 445 | is_sequence_source(clip.source) && self.compound_refusal(clip).is_some() |
| 446 | } |
| 447 | |
| 448 | /// Checks every compound clip of every sequence names a real sequence and |
| 449 | /// that no sequence plays itself. The loader's gate. |
| 450 | pub(crate) fn check_sequences(&self) -> crate::Result<()> { |
| 451 | for (id, name) in &self.seq.names { |
| 452 | let Some(lanes) = self.lanes_of(*id) else { |
| 453 | return Err(format!("sequence {id} has no data").into()); |
| 454 | }; |
| 455 | for inner in compound_ids(lanes) { |
| 456 | if self.sequence_name(inner).is_none() { |
| 457 | return Err(format!("\"{name}\" plays sequence {inner}, which the file does not hold").into()); |
| 458 | } |
| 459 | } |
| 460 | for c in lanes.iter().flat_map(|l| &l.clips).filter(|c| is_sequence_source(c.source)) { |
| 461 | let inner = sequence_id_of(c.source).unwrap_or(u32::MAX); |
| 462 | if inner == *id || self.reaches(inner, *id) { |
| 463 | return Err(format!("\"{name}\" contains itself").into()); |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | Ok(()) |
| 468 | } |
| 469 | |
| 470 | /// Empties the sequence list a fresh project starts with ([`Seqs::single`], the |
| 471 | /// placeholder "Sequence 1" with id 0). A loader calls this before it absorbs a |
| 472 | /// file's sequences: the placeholder is not a sequence the file holds, and left |
| 473 | /// in place it collides with a parked sequence 0 ("holds sequence 0 twice"). |
| 474 | pub(crate) fn clear_sequences(&mut self) { |
| 475 | self.seq.names.clear(); |
| 476 | self.seq.parked.clear(); |
| 477 | self.seq.mcam.clear(); |
| 478 | self.seq.nested.clear(); |
| 479 | } |
| 480 | |
| 481 | /// Makes `data` (read off a loaded standalone project) a parked sequence. |
| 482 | /// Its effect-table indexes are shifted past this project's tables. |
| 483 | pub(crate) fn absorb_sequence(&mut self, id: u32, name: &str, other: Project) -> crate::Result<()> { |
| 484 | if self.seq.names.iter().any(|(i, _)| *i == id) { |
| 485 | return Err(format!("the file holds sequence {id} twice").into()); |
| 486 | } |
| 487 | let fits = |have: usize, add: usize| have + add <= usize::from(u16::MAX); |
| 488 | if !fits(self.eq.len(), other.eq.len()) |
| 489 | || !fits(self.color.len(), other.color.len()) |
| 490 | || !fits(self.transform.len(), other.transform.len()) |
| 491 | { |
| 492 | return Err("the sequences hold more effect settings than a project can".into()); |
| 493 | } |
| 494 | let (eq_at, color_at, transform_at) = (self.eq.len(), self.color.len(), self.transform.len()); |
| 495 | let shift = |i: u16, by: usize| (usize::from(i) + by) as u16; |
| 496 | let mut lanes = other.lanes; |
| 497 | for c in lanes.iter_mut().flat_map(|l| &mut l.clips) { |
| 498 | c.eq = c.eq.map(|i| shift(i, eq_at)); |
| 499 | c.color = c.color.map(|i| shift(i, color_at)); |
| 500 | c.transform = c.transform.map(|i| shift(i, transform_at)); |
| 501 | } |
| 502 | self.eq.extend(other.eq); |
| 503 | self.color.extend(other.color); |
| 504 | self.transform.extend(other.transform); |
| 505 | self.next_link = self.next_link.max(other.next_link); |
| 506 | self.seq.names.push((id, name.to_string())); |
| 507 | self.seq.parked.push(( |
| 508 | id, |
| 509 | SeqData { |
| 510 | lanes, |
| 511 | subtitles: other.subtitles, |
| 512 | cue_edits: other.cue_edits, |
| 513 | cue_adds: other.cue_adds, |
| 514 | titles: other.titles, |
| 515 | chapters: other.chapters, |
| 516 | markers: other.markers, |
| 517 | }, |
| 518 | )); |
| 519 | self.seq_next = self.seq_next.max(id + 1); |
| 520 | Ok(()) |
| 521 | } |
| 522 | |
| 523 | /// Names the active sequence and the tab order, as a load reads them off a file. |
| 524 | pub(crate) fn set_sequence_meta(&mut self, active: u32, active_name: &str, order: &[u32]) { |
| 525 | self.seq.active = active; |
| 526 | match self.seq.names.iter_mut().find(|(i, _)| *i == active) { |
| 527 | Some(row) => row.1 = active_name.to_string(), |
| 528 | None => self.seq.names.insert(0, (active, active_name.to_string())), |
| 529 | } |
| 530 | let mut sorted: Vec<(u32, String)> = Vec::new(); |
| 531 | for id in order { |
| 532 | if let Some(row) = self.seq.names.iter().find(|(i, _)| i == id) |
| 533 | && !sorted.iter().any(|(i, _)| i == id) |
| 534 | { |
| 535 | sorted.push(row.clone()); |
| 536 | } |
| 537 | } |
| 538 | for row in &self.seq.names { |
| 539 | if !sorted.iter().any(|(i, _)| *i == row.0) { |
| 540 | sorted.push(row.clone()); |
| 541 | } |
| 542 | } |
| 543 | self.seq.names = sorted; |
| 544 | self.seq_next = self.seq_next.max(self.seq.names.iter().map(|(i, _)| i + 1).max().unwrap_or(1)); |
| 545 | } |
| 546 | |
| 547 | /// A project that has sequence `id` as its active one and nothing else |
| 548 | /// different, for a writer to take parts off. The undo history is left out. |
| 549 | pub(crate) fn as_sequence(&self, id: u32) -> crate::Result<Project> { |
| 550 | let mut p = self.raw_snapshot(); |
| 551 | p.switch_sequence(id)?; |
| 552 | Ok(p) |
| 553 | } |
| 554 | |
| 555 | /// The multicam sources and their angle names, for the writer. |
| 556 | pub(crate) fn multicam_rows(&self) -> Vec<(u32, Vec<String>)> { |
| 557 | self.seq.mcam.clone() |
| 558 | } |
| 559 | |
| 560 | /// Flags the sequences a file names as multicam sources (`mcam` lines, grouped by sequence in |
| 561 | /// order). Refused when a sequence is missing or does not hold one video and one sound lane |
| 562 | /// per angle. |
| 563 | pub(crate) fn set_multicam(&mut self, lines: &[(u32, String)]) -> crate::Result<()> { |
| 564 | let mut mcam: Vec<(u32, Vec<String>)> = Vec::new(); |
| 565 | for (id, name) in lines { |
| 566 | match mcam.iter_mut().find(|(i, _)| i == id) { |
| 567 | Some((_, names)) => names.push(name.clone()), |
| 568 | None => mcam.push((*id, vec![name.clone()])), |
| 569 | } |
| 570 | } |
| 571 | for (id, names) in &mcam { |
| 572 | let Some(lanes) = self.lanes_of(*id) else { |
| 573 | return Err(format!("multicam names sequence {id}, which the file does not hold").into()); |
| 574 | }; |
| 575 | let count = |k: LaneKind| lanes.iter().filter(|l| l.kind == k).count(); |
| 576 | if names.len() > super::multicam::MAX_ANGLES || count(LaneKind::Video) != names.len() || count(LaneKind::Audio) != names.len() { |
| 577 | return Err(format!("multicam sequence {id} must hold one picture lane and one sound lane per angle").into()); |
| 578 | } |
| 579 | } |
| 580 | self.seq.mcam = mcam; |
| 581 | Ok(()) |
| 582 | } |
| 583 | |
| 584 | /// Every sequence id and name in tab order, with the active one marked. |
| 585 | pub(crate) fn sequence_rows(&self) -> Vec<(u32, String, bool)> { |
| 586 | self.seq.names.iter().map(|(i, n)| (*i, n.clone(), *i == self.seq.active)).collect() |
| 587 | } |
| 588 | |
| 589 | /// The name a new nested sequence starts from when none is given: the first clip nested, |
| 590 | /// so the tab says what is inside ("Interview (nested)"). A compound clip names its sequence. |
| 591 | fn nested_base_name(&self, picks: &[(Lane, usize)]) -> String { |
| 592 | let first = picks.first().and_then(|&(lane, i)| self.lane(lane).get(i)).map(|c| c.source); |
| 593 | let stem = match first { |
| 594 | Some(source) => match sequence_id_of(source) { |
| 595 | Some(id) => self.sequence_name(id).map(str::to_string), |
| 596 | None => self.sources.get(source).and_then(|s| s.path.file_stem()).map(|s| s.to_string_lossy().into_owned()), |
| 597 | }, |
| 598 | None => None, |
| 599 | }; |
| 600 | match stem { |
| 601 | Some(stem) if !stem.is_empty() => format!("{stem} (nested)"), |
| 602 | _ => "Nested Sequence".to_string(), |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | pub(super) fn fresh_name(&self, base: &str) -> String { |
| 607 | if self.sequence_named(base).is_none() { |
| 608 | return base.to_string(); |
| 609 | } |
| 610 | (2..) |
| 611 | .map(|n| format!("{base} {n}")) |
| 612 | .find(|n| self.sequence_named(n).is_none()) |
| 613 | .unwrap_or_else(|| base.to_string()) |
| 614 | } |
| 615 | |
| 616 | pub(super) fn unique_name(&self, name: &str, except: Option<u32>) -> crate::Result<String> { |
| 617 | let name = clean_name(name)?; |
| 618 | if let Some(other) = self.seq.names.iter().find(|(i, n)| n == &name && Some(*i) != except) { |
| 619 | return Err(format!("a sequence named \"{}\" exists already", other.1).into()); |
| 620 | } |
| 621 | Ok(name) |
| 622 | } |
| 623 | |
| 624 | /// Adds an empty sequence (`V1` and `A1`) after the active one in the tab |
| 625 | /// order. One undo step. It is not switched to; see [`switch_sequence`](Project::switch_sequence). |
| 626 | pub fn new_sequence(&mut self, name: Option<&str>) -> crate::Result<u32> { |
| 627 | if self.seq.names.len() >= MAX_SEQUENCES { |
| 628 | return Err(format!("a project holds at most {MAX_SEQUENCES} sequences").into()); |
| 629 | } |
| 630 | let name = match name { |
| 631 | Some(n) => self.unique_name(n, None)?, |
| 632 | None => self.fresh_name(&format!("Sequence {}", self.seq.names.len() + 1)), |
| 633 | }; |
| 634 | self.snapshot(); |
| 635 | let id = self.seq_next; |
| 636 | self.seq_next += 1; |
| 637 | let at = self.seq.names.iter().position(|(i, _)| *i == self.seq.active).map_or(self.seq.names.len(), |p| p + 1); |
| 638 | self.seq.names.insert(at, (id, name)); |
| 639 | self.seq.parked.push((id, SeqData::empty())); |
| 640 | self.flat.clear(); |
| 641 | Ok(id) |
| 642 | } |
| 643 | |
| 644 | /// Renames sequence `id`. One undo step. |
| 645 | pub fn rename_sequence(&mut self, id: u32, name: &str) -> crate::Result<()> { |
| 646 | if self.sequence_name(id).is_none() { |
| 647 | return Err(format!("there is no sequence {id}").into()); |
| 648 | } |
| 649 | let name = self.unique_name(name, Some(id))?; |
| 650 | if self.sequence_name(id) == Some(name.as_str()) { |
| 651 | return Ok(()); |
| 652 | } |
| 653 | self.snapshot(); |
| 654 | if let Some(row) = self.seq.names.iter_mut().find(|(i, _)| *i == id) { |
| 655 | row.1 = name; |
| 656 | } |
| 657 | self.seq.nested.retain(|i| *i != id); |
| 658 | Ok(()) |
| 659 | } |
| 660 | |
| 661 | /// A copy of sequence `id` right after it in the tab order, named "<name> copy". |
| 662 | /// Compound clips in the copy still play the same inner sequences. One undo step. |
| 663 | pub fn duplicate_sequence(&mut self, id: u32) -> crate::Result<u32> { |
| 664 | let Some(name) = self.sequence_name(id).map(str::to_string) else { |
| 665 | return Err(format!("there is no sequence {id}").into()); |
| 666 | }; |
| 667 | if self.seq.names.len() >= MAX_SEQUENCES { |
| 668 | return Err(format!("a project holds at most {MAX_SEQUENCES} sequences").into()); |
| 669 | } |
| 670 | let data = if id == self.seq.active { |
| 671 | self.active_data() |
| 672 | } else { |
| 673 | self.seq.parked.iter().find(|(i, _)| *i == id).map(|(_, d)| d.clone()).ok_or("sequence data is missing")? |
| 674 | }; |
| 675 | let copy_name = self.fresh_name(&format!("{name} copy")); |
| 676 | self.snapshot(); |
| 677 | let new = self.seq_next; |
| 678 | self.seq_next += 1; |
| 679 | let at = self.seq.names.iter().position(|(i, _)| *i == id).map_or(self.seq.names.len(), |p| p + 1); |
| 680 | self.seq.names.insert(at, (new, copy_name)); |
| 681 | self.seq.parked.push((new, data)); |
| 682 | if let Some(names) = self.seq.mcam.iter().find(|(i, _)| *i == id).map(|(_, n)| n.clone()) { |
| 683 | self.seq.mcam.push((new, names)); |
| 684 | } |
| 685 | self.flat.clear(); |
| 686 | Ok(new) |
| 687 | } |
| 688 | |
| 689 | /// Deletes sequence `id`; the neighbour in the tab order becomes active when |
| 690 | /// it was the active one. Refused for the last sequence and for one that a |
| 691 | /// compound clip still plays. One undo step. Returns the active sequence after. |
| 692 | pub fn delete_sequence(&mut self, id: u32) -> crate::Result<u32> { |
| 693 | let Some(name) = self.sequence_name(id).map(str::to_string) else { |
| 694 | return Err(format!("there is no sequence {id}").into()); |
| 695 | }; |
| 696 | if self.seq.names.len() < 2 { |
| 697 | return Err("a project keeps at least one sequence".into()); |
| 698 | } |
| 699 | let users: Vec<String> = self |
| 700 | .seq |
| 701 | .names |
| 702 | .iter() |
| 703 | .filter(|(other, _)| *other != id) |
| 704 | .filter(|(other, _)| self.lanes_of(*other).is_some_and(|ls| compound_ids(ls).any(|x| x == id))) |
| 705 | .map(|(_, n)| format!("\"{n}\"")) |
| 706 | .collect(); |
| 707 | if !users.is_empty() { |
| 708 | return Err(format!( |
| 709 | "\"{name}\" is played by compound clips in {}: break them apart or delete them first", |
| 710 | users.join(", ") |
| 711 | ) |
| 712 | .into()); |
| 713 | } |
| 714 | self.snapshot(); |
| 715 | if id == self.seq.active { |
| 716 | let pos = self.seq.names.iter().position(|(i, _)| *i == id).unwrap_or(0); |
| 717 | let next = if pos > 0 { self.seq.names[pos - 1].0 } else { self.seq.names[1].0 }; |
| 718 | self.switch_sequence(next)?; |
| 719 | } |
| 720 | self.seq.names.retain(|(i, _)| *i != id); |
| 721 | self.seq.parked.retain(|(i, _)| *i != id); |
| 722 | self.seq.mcam.retain(|(i, _)| *i != id); |
| 723 | self.seq.nested.retain(|i| *i != id); |
| 724 | self.flat.clear(); |
| 725 | Ok(self.seq.active) |
| 726 | } |
| 727 | |
| 728 | fn active_data(&self) -> SeqData { |
| 729 | SeqData { |
| 730 | lanes: self.lanes.clone(), |
| 731 | subtitles: self.subtitles.clone(), |
| 732 | cue_edits: self.cue_edits.clone(), |
| 733 | cue_adds: self.cue_adds.clone(), |
| 734 | titles: self.titles.clone(), |
| 735 | chapters: self.chapters.clone(), |
| 736 | markers: self.markers.clone(), |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | /// Makes sequence `id` the active one. Not an undo step (it edits nothing), |
| 741 | /// and it leaves the redo stack alone. |
| 742 | pub fn switch_sequence(&mut self, id: u32) -> crate::Result<()> { |
| 743 | if id == self.seq.active { |
| 744 | return Ok(()); |
| 745 | } |
| 746 | let Some(at) = self.seq.parked.iter().position(|(i, _)| *i == id) else { |
| 747 | return Err(format!("there is no sequence {id}").into()); |
| 748 | }; |
| 749 | let (_, inbound) = self.seq.parked.swap_remove(at); |
| 750 | let outbound = SeqData { |
| 751 | lanes: std::mem::replace(&mut self.lanes, inbound.lanes), |
| 752 | subtitles: std::mem::replace(&mut self.subtitles, inbound.subtitles), |
| 753 | cue_edits: std::mem::replace(&mut self.cue_edits, inbound.cue_edits), |
| 754 | cue_adds: std::mem::replace(&mut self.cue_adds, inbound.cue_adds), |
| 755 | titles: std::mem::replace(&mut self.titles, inbound.titles), |
| 756 | chapters: std::mem::replace(&mut self.chapters, inbound.chapters), |
| 757 | markers: std::mem::replace(&mut self.markers, inbound.markers), |
| 758 | }; |
| 759 | let old = self.seq.active; |
| 760 | self.seq.parked.push((old, outbound)); |
| 761 | self.seq.active = id; |
| 762 | self.flat.clear(); |
| 763 | Ok(()) |
| 764 | } |
| 765 | |
| 766 | /// How many clips play `source` in each parked sequence that uses it, as `(sequence id, count)`: |
| 767 | /// the library's "is it on the timeline" counts these as uses. |
| 768 | pub fn source_uses_parked(&self, source: usize) -> Vec<(u32, usize)> { |
| 769 | self.seq |
| 770 | .parked |
| 771 | .iter() |
| 772 | .map(|(id, d)| (*id, d.lanes.iter().flat_map(|l| &l.clips).filter(|c| c.source == source).count())) |
| 773 | .filter(|(_, n)| *n > 0) |
| 774 | .collect() |
| 775 | } |
| 776 | |
| 777 | /// The clips a compound clip `c` on a `kind` lane stands for, as the render sees them: |
| 778 | /// trimmed to its window and placed relative to its own start. What the bench draws a |
| 779 | /// compound clip from (thumbnails of the picture, waveform of the mix). |
| 780 | pub fn compound_pieces(&self, kind: LaneKind, c: &Clip) -> Vec<Clip> { |
| 781 | if !is_sequence_source(c.source) { |
| 782 | return Vec::new(); |
| 783 | } |
| 784 | let mut tables = Tables { transform: self.transform.clone(), color: self.color.clone(), size: self.settings.resolution }; |
| 785 | let lane = LaneData::new(kind, vec![c.clone()]); |
| 786 | self.expand(&[lane], 0, &mut tables) |
| 787 | .into_iter() |
| 788 | .flat_map(|l| l.clips) |
| 789 | .map(|mut p| { |
| 790 | p.start = p.start.saturating_sub(c.start); |
| 791 | p |
| 792 | }) |
| 793 | .collect() |
| 794 | } |
| 795 | |
| 796 | /// The sequence the compound clip at `lane`/`idx` plays. |
| 797 | pub fn compound_at(&self, lane: Lane, idx: usize) -> Option<u32> { |
| 798 | self.lane(lane).get(idx).and_then(|c| self.compound_of(c)) |
| 799 | } |
| 800 | |
| 801 | /// Replaces the clips at `picks` with one compound clip per kind (picture, |
| 802 | /// sound) of a new sequence that holds them. The new sequence keeps the |
| 803 | /// picks' lanes in order (compacted), the clips shifted to start at 0. One |
| 804 | /// undo step. Refused when another clip sits in the way on a lane involved. |
| 805 | pub fn nest(&mut self, picks: &[(Lane, usize)], name: Option<&str>) -> crate::Result<Nested> { |
| 806 | if picks.is_empty() { |
| 807 | return Err("nest needs at least one clip".into()); |
| 808 | } |
| 809 | if self.seq.names.len() >= MAX_SEQUENCES { |
| 810 | return Err(format!("a project holds at most {MAX_SEQUENCES} sequences").into()); |
| 811 | } |
| 812 | let mut picks: Vec<(Lane, usize)> = picks.to_vec(); |
| 813 | picks.sort_by_key(|(l, i)| (l.kind as u8, l.ord, *i)); |
| 814 | picks.dedup(); |
| 815 | for &(lane, idx) in &picks { |
| 816 | if lane.kind == LaneKind::Subtitle { |
| 817 | return Err("captions cannot be nested".into()); |
| 818 | } |
| 819 | if self.lane(lane).get(idx).is_none() { |
| 820 | return Err(format!("there is no clip {} #{idx}", lane.label()).into()); |
| 821 | } |
| 822 | } |
| 823 | // A take goes whole: the linked partners of a pick (the sound of a picture) come too. |
| 824 | let links: Vec<u32> = picks.iter().filter_map(|&(l, i)| self.lane(l)[i].link).collect(); |
| 825 | if !links.is_empty() { |
| 826 | for lane in self.lanes().into_iter().filter(|l| l.kind != LaneKind::Subtitle) { |
| 827 | for (i, c) in self.lane(lane).iter().enumerate() { |
| 828 | if c.link.is_some_and(|k| links.contains(&k)) && !picks.contains(&(lane, i)) { |
| 829 | picks.push((lane, i)); |
| 830 | } |
| 831 | } |
| 832 | } |
| 833 | picks.sort_by_key(|(l, i)| (l.kind as u8, l.ord, *i)); |
| 834 | } |
| 835 | let lo = picks.iter().map(|&(l, i)| self.lane(l)[i].start).min().unwrap_or(0); |
| 836 | let hi = picks.iter().map(|&(l, i)| self.lane(l)[i].end()).max().unwrap_or(0); |
| 837 | let mut lanes_used: Vec<Lane> = picks.iter().map(|p| p.0).collect(); |
| 838 | lanes_used.dedup(); |
| 839 | for &lane in &lanes_used { |
| 840 | for (i, c) in self.lane(lane).iter().enumerate() { |
| 841 | if !picks.contains(&(lane, i)) && c.start < hi && c.end() > lo { |
| 842 | return Err(format!( |
| 843 | "{} has a clip at {} between the selected ones: select it too, or nest a range with nothing else on those lanes", |
| 844 | lane.label(), |
| 845 | c.start |
| 846 | ) |
| 847 | .into()); |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | let (name, default_named) = match name { |
| 852 | Some(n) => (self.unique_name(n, None)?, false), |
| 853 | None => (self.fresh_name(&self.nested_base_name(&picks)), true), |
| 854 | }; |
| 855 | // The inner lanes: the picked video lanes in order, then the audio ones. |
| 856 | let mut inner: Vec<LaneData> = Vec::new(); |
| 857 | let mut first_video = None; |
| 858 | let mut first_audio = None; |
| 859 | for &lane in &lanes_used { |
| 860 | let clips: Vec<Clip> = picks |
| 861 | .iter() |
| 862 | .filter(|p| p.0 == lane) |
| 863 | .map(|&(l, i)| { |
| 864 | let mut c = self.lane(l)[i].clone(); |
| 865 | c.start -= lo; |
| 866 | c |
| 867 | }) |
| 868 | .collect(); |
| 869 | inner.push(LaneData::new(lane.kind, clips)); |
| 870 | match lane.kind { |
| 871 | LaneKind::Video if first_video.is_none() => first_video = Some(lane), |
| 872 | LaneKind::Audio if first_audio.is_none() => first_audio = Some(lane), |
| 873 | _ => {} |
| 874 | } |
| 875 | } |
| 876 | self.snapshot(); |
| 877 | let id = self.seq_next; |
| 878 | self.seq_next += 1; |
| 879 | // Out of the parent, last index first so the others stay put. |
| 880 | for &lane in &lanes_used { |
| 881 | let mut idxs: Vec<usize> = picks.iter().filter(|p| p.0 == lane).map(|p| p.1).collect(); |
| 882 | idxs.sort_unstable_by(|a, b| b.cmp(a)); |
| 883 | if let Some(clips) = self.lane_mut(lane) { |
| 884 | for i in idxs { |
| 885 | clips.remove(i); |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 | let at = self.seq.names.iter().position(|(i, _)| *i == self.seq.active).map_or(self.seq.names.len(), |p| p + 1); |
| 890 | self.seq.names.insert(at, (id, name)); |
| 891 | if default_named { |
| 892 | self.seq.nested.push(id); |
| 893 | } |
| 894 | let mut data = SeqData::empty(); |
| 895 | data.lanes = inner; |
| 896 | self.seq.parked.push((id, data)); |
| 897 | let link = (first_video.is_some() && first_audio.is_some()).then(|| self.new_link()); |
| 898 | let mut made = Vec::new(); |
| 899 | for lane in [first_video, first_audio].into_iter().flatten() { |
| 900 | let mut c = Clip::source_range(sequence_source(id), 0, hi - lo); |
| 901 | c.start = lo; |
| 902 | c.link = link; |
| 903 | if let Some(clips) = self.lane_mut(lane) { |
| 904 | let at = clips.partition_point(|x| x.start < lo); |
| 905 | clips.insert(at, c); |
| 906 | made.push((lane, at)); |
| 907 | } |
| 908 | } |
| 909 | self.flat.clear(); |
| 910 | Ok(Nested { sequence: id, clips: made }) |
| 911 | } |
| 912 | |
| 913 | /// Puts the clips of each compound clip at `picks` (and its linked partner) |
| 914 | /// back into the sequence, in place of the compound clip: the inner lanes |
| 915 | /// land on the compound clip's lane and the ones above it. One undo step. |
| 916 | /// Refused, changing nothing, when another clip is in the way. Captions and |
| 917 | /// titles inside are not carried. |
| 918 | pub fn break_apart(&mut self, picks: &[(Lane, usize)]) -> crate::Result<Vec<(Lane, usize)>> { |
| 919 | let mut set: Vec<(Lane, usize)> = Vec::new(); |
| 920 | for &(lane, idx) in picks { |
| 921 | let Some(c) = self.lane(lane).get(idx) else { |
| 922 | return Err(format!("there is no clip {} #{idx}", lane.label()).into()); |
| 923 | }; |
| 924 | if self.compound_of(c).is_none() { |
| 925 | return Err(format!("{} #{idx} is not a compound clip", lane.label()).into()); |
| 926 | } |
| 927 | if !set.contains(&(lane, idx)) { |
| 928 | set.push((lane, idx)); |
| 929 | } |
| 930 | if let Some(link) = c.link { |
| 931 | for other in self.lanes() { |
| 932 | for (i, o) in self.lane(other).iter().enumerate() { |
| 933 | if o.link == Some(link) && o.source == c.source && !set.contains(&(other, i)) { |
| 934 | set.push((other, i)); |
| 935 | } |
| 936 | } |
| 937 | } |
| 938 | } |
| 939 | } |
| 940 | if set.is_empty() { |
| 941 | return Err("break apart needs a compound clip".into()); |
| 942 | } |
| 943 | // The pieces each compound clip stands for, by target lane, with which compound |
| 944 | // clip each came out of (its inner link ids are only meaningful per compound). |
| 945 | let mut plan: Vec<(Lane, Clip, usize)> = Vec::new(); |
| 946 | for (n, &(lane, idx)) in set.iter().enumerate() { |
| 947 | let c = self.lane(lane)[idx].clone(); |
| 948 | let id = self.compound_of(&c).unwrap_or(0); |
| 949 | let Some(inner) = self.lanes_of(id) else { |
| 950 | return Err(format!("sequence {id} is missing").into()); |
| 951 | }; |
| 952 | let mut same: Vec<&LaneData> = inner.iter().filter(|l| l.kind == lane.kind).collect(); |
| 953 | if let Some(n) = self.angle_count(id) { |
| 954 | let pick = usize::from(c.angle.of(lane.kind)).min(n.saturating_sub(1)); |
| 955 | same = same.get(pick).copied().into_iter().collect(); |
| 956 | } |
| 957 | for (slot, il) in same.into_iter().enumerate() { |
| 958 | let target = Lane::new(lane.kind, lane.ord + slot); |
| 959 | for q in &il.clips { |
| 960 | let lo = q.start.max(c.in_frame); |
| 961 | let hi = q.end().min(c.out_frame); |
| 962 | if lo >= hi { |
| 963 | continue; |
| 964 | } |
| 965 | if let Some(p) = piece(q, lo - q.start, hi - q.start, c.start + (lo - c.in_frame)) { |
| 966 | plan.push((target, p, n)); |
| 967 | } |
| 968 | } |
| 969 | } |
| 970 | } |
| 971 | // Room: nothing but the compound clips being broken may be in the way. |
| 972 | for (target, p, _) in &plan { |
| 973 | for (i, o) in self.lane(*target).iter().enumerate() { |
| 974 | let broken = set.contains(&(*target, i)); |
| 975 | if !broken && o.start < p.end() && o.end() > p.start { |
| 976 | return Err(format!( |
| 977 | "{} has a clip at {} where the compound clip's contents land: move it first", |
| 978 | target.label(), |
| 979 | o.start |
| 980 | ) |
| 981 | .into()); |
| 982 | } |
| 983 | } |
| 984 | } |
| 985 | // The sequences the broken compound clips played, for the tidy-up below. |
| 986 | let mut inner_ids: Vec<u32> = set.iter().filter_map(|&(l, i)| self.compound_of(&self.lane(l)[i])).collect(); |
| 987 | inner_ids.sort_unstable(); |
| 988 | inner_ids.dedup(); |
| 989 | self.snapshot(); |
| 990 | // Lanes the plan needs that do not exist yet. |
| 991 | for (target, _, _) in &plan { |
| 992 | while self.lane_count(target.kind) <= target.ord { |
| 993 | self.lanes.push(LaneData::new(target.kind, Vec::new())); |
| 994 | } |
| 995 | } |
| 996 | // Out with the compound clips, last index first. |
| 997 | let mut removals = set.clone(); |
| 998 | removals.sort_by_key(|a| std::cmp::Reverse((a.0.kind as u8, a.0.ord, a.1))); |
| 999 | for (lane, idx) in removals { |
| 1000 | if let Some(clips) = self.lane_mut(lane) { |
| 1001 | clips.remove(idx); |
| 1002 | } |
| 1003 | } |
| 1004 | // Fresh link ids: one per (compound clip, inner link), so two copies of one |
| 1005 | // sequence never share a group. |
| 1006 | let mut fresh: Vec<((usize, u32), u32)> = Vec::new(); |
| 1007 | let mut placed: Vec<(Lane, u32)> = Vec::new(); |
| 1008 | for (target, mut p, owner) in plan { |
| 1009 | if let Some(l) = p.link { |
| 1010 | let id = match fresh.iter().find(|(k, _)| *k == (owner, l)) { |
| 1011 | Some((_, id)) => *id, |
| 1012 | None => { |
| 1013 | let id = self.new_link(); |
| 1014 | fresh.push(((owner, l), id)); |
| 1015 | id |
| 1016 | } |
| 1017 | }; |
| 1018 | p.link = Some(id); |
| 1019 | } |
| 1020 | placed.push((target, p.start)); |
| 1021 | if let Some(clips) = self.lane_mut(target) { |
| 1022 | let at = clips.partition_point(|x| x.start < p.start); |
| 1023 | clips.insert(at, p); |
| 1024 | } |
| 1025 | } |
| 1026 | let made: Vec<(Lane, usize)> = placed |
| 1027 | .into_iter() |
| 1028 | .filter_map(|(lane, start)| self.lane(lane).iter().position(|c| c.start == start).map(|i| (lane, i))) |
| 1029 | .collect(); |
| 1030 | // A sequence Nest made (under its default name, never renamed) that nothing plays any more |
| 1031 | // would only be an orphan tab: it goes in this same undo step. |
| 1032 | for id in inner_ids { |
| 1033 | let orphan = self.seq.nested.contains(&id) |
| 1034 | && !self.seq.mcam.iter().any(|(i, _)| *i == id) |
| 1035 | && !self.seq.names.iter().any(|(other, _)| { |
| 1036 | *other != id && self.lanes_of(*other).is_some_and(|ls| compound_ids(ls).any(|x| x == id)) |
| 1037 | }) |
| 1038 | && id != self.seq.active; |
| 1039 | if orphan { |
| 1040 | self.seq.names.retain(|(i, _)| *i != id); |
| 1041 | self.seq.parked.retain(|(i, _)| *i != id); |
| 1042 | self.seq.nested.retain(|i| *i != id); |
| 1043 | } |
| 1044 | } |
| 1045 | self.flat.clear(); |
| 1046 | Ok(made) |
| 1047 | } |
| 1048 | |
| 1049 | /// Places a compound clip playing sequence `seq` on `lane` at `at`, over the |
| 1050 | /// sequence's whole length, replacing what is there (the clip is placed like |
| 1051 | /// any other). Refused when `seq` would contain the active sequence. |
| 1052 | pub fn place_sequence(&mut self, seq: u32, lane: Lane, at: u32) -> crate::Result<()> { |
| 1053 | let Some(name) = self.sequence_name(seq).map(str::to_string) else { |
| 1054 | return Err(format!("there is no sequence {seq}").into()); |
| 1055 | }; |
| 1056 | let len = self.sequence_frames(seq); |
| 1057 | if len == 0 { |
| 1058 | return Err(format!("\"{name}\" is empty: there is nothing to play").into()); |
| 1059 | } |
| 1060 | let clip = Clip::source_range(sequence_source(seq), 0, len); |
| 1061 | if let Some(why) = self.compound_refusal(&clip) { |
| 1062 | return Err(why.into()); |
| 1063 | } |
| 1064 | if lane.kind == LaneKind::Subtitle { |
| 1065 | return Err("a compound clip goes on a video or audio lane".into()); |
| 1066 | } |
| 1067 | if !self.place(lane, at, clip) { |
| 1068 | return Err(format!("{} cannot take the clip there", lane.label()).into()); |
| 1069 | } |
| 1070 | Ok(()) |
| 1071 | } |
| 1072 | |
| 1073 | /// The length of sequence `id` in timeline frames. |
| 1074 | pub fn sequence_frames(&self, id: u32) -> u32 { |
| 1075 | self.lanes_of(id).map_or(0, |ls| ls.iter().flat_map(|l| &l.clips).map(Clip::end).max().unwrap_or(0)) |
| 1076 | } |
| 1077 | |
| 1078 | /// A copy of the project with the undo history left out and everything else |
| 1079 | /// as it is, compound clips included. |
| 1080 | pub fn raw_snapshot(&self) -> Self { |
| 1081 | Self { |
| 1082 | sources: self.sources.clone(), |
| 1083 | lanes: self.lanes.clone(), |
| 1084 | eq: self.eq.clone(), |
| 1085 | color: self.color.clone(), |
| 1086 | transform: self.transform.clone(), |
| 1087 | history: Vec::new(), |
| 1088 | redo: Vec::new(), |
| 1089 | pushes: self.history_pushes(), |
| 1090 | revision: self.revision(), |
| 1091 | batching: false, |
| 1092 | batch_snapped: false, |
| 1093 | pending: None, |
| 1094 | hold_cap: false, |
| 1095 | next_link: self.next_link, |
| 1096 | subtitles: self.subtitles.clone(), |
| 1097 | cue_edits: self.cue_edits.clone(), |
| 1098 | cue_adds: self.cue_adds.clone(), |
| 1099 | titles: self.titles.clone(), |
| 1100 | chapters: self.chapters.clone(), |
| 1101 | markers: self.markers.clone(), |
| 1102 | settings: self.settings.clone(), |
| 1103 | seq: self.seq.clone(), |
| 1104 | bins: self.bins.clone(), |
| 1105 | bin_next: self.bin_next, |
| 1106 | seq_next: self.seq_next, |
| 1107 | flat: FlatCache::default(), |
| 1108 | } |
| 1109 | } |
| 1110 | |
| 1111 | /// The project an export or a render reads: the active sequence with its |
| 1112 | /// compound clips expanded, the undo history left behind. |
| 1113 | pub fn export_snapshot(&self) -> Self { |
| 1114 | if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| is_sequence_source(c.source) || c.mark.off) { |
| 1115 | let mut p = self.raw_snapshot(); |
| 1116 | p.seq = Seqs { active: p.seq.active, names: p.seq.names.clone(), parked: Vec::new(), mcam: p.seq.mcam.clone(), nested: p.seq.nested.clone() }; |
| 1117 | return p; |
| 1118 | } |
| 1119 | self.flatten() |
| 1120 | } |
| 1121 | |
| 1122 | /// [`export_snapshot`](Project::export_snapshot) of sequence `seq` (the active one for `None`). |
| 1123 | pub fn render_snapshot(&self, seq: Option<u32>) -> crate::Result<Self> { |
| 1124 | match seq { |
| 1125 | Some(id) if id != self.seq.active => { |
| 1126 | let mut p = self.raw_snapshot(); |
| 1127 | p.switch_sequence(id)?; |
| 1128 | Ok(p.export_snapshot()) |
| 1129 | } |
| 1130 | _ => Ok(self.export_snapshot()), |
| 1131 | } |
| 1132 | } |
| 1133 | |
| 1134 | fn flatten(&self) -> Self { |
| 1135 | let mut p = self.raw_snapshot(); |
| 1136 | let mut tables = Tables { transform: self.transform.clone(), color: self.color.clone(), size: self.settings.resolution }; |
| 1137 | p.lanes = self.expand(&self.lanes, 0, &mut tables); |
| 1138 | p.transform = tables.transform; |
| 1139 | p.color = tables.color; |
| 1140 | p.seq = Seqs { active: p.seq.active, names: p.seq.names.clone(), parked: Vec::new(), mcam: p.seq.mcam.clone(), nested: p.seq.nested.clone() }; |
| 1141 | p |
| 1142 | } |
| 1143 | |
| 1144 | /// What playback and export read: this project when it holds no compound |
| 1145 | /// clip, otherwise its expansion, kept until the timeline changes. |
| 1146 | pub fn render_view(&self) -> RenderView<'_> { |
| 1147 | // A switched-off clip is left out of the render like a compound one is expanded: by a copy. |
| 1148 | if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| is_sequence_source(c.source) || c.mark.off) { |
| 1149 | return RenderView::Same(self); |
| 1150 | } |
| 1151 | use std::hash::{Hash, Hasher}; |
| 1152 | let mut h = std::collections::hash_map::DefaultHasher::new(); |
| 1153 | for l in &self.lanes { |
| 1154 | (l.kind as u8, l.gain_db.to_bits(), l.hidden, l.muted, l.clips.len()).hash(&mut h); |
| 1155 | for c in &l.clips { |
| 1156 | (c.start, c.in_frame, c.out_frame, c.source, c.speed.permille(), c.reversed, c.angle.video, c.angle.audio).hash(&mut h); |
| 1157 | (c.fade_in, c.fade_out, c.gain_db.to_bits(), c.transition_out, c.eq, c.color, c.transform, c.mark).hash(&mut h); |
| 1158 | } |
| 1159 | } |
| 1160 | format!("{:?}", self.settings).hash(&mut h); |
| 1161 | (self.history_pushes(), self.titles.len(), self.chapters.len(), self.markers.len(), self.subtitles.len()).hash(&mut h); |
| 1162 | let key = h.finish(); |
| 1163 | let mut guard = match self.flat.0.lock() { |
| 1164 | Ok(g) => g, |
| 1165 | Err(e) => e.into_inner(), |
| 1166 | }; |
| 1167 | if let Some((k, p)) = guard.as_ref() |
| 1168 | && *k == key |
| 1169 | { |
| 1170 | return RenderView::Flat(Arc::clone(p)); |
| 1171 | } |
| 1172 | let flat = Arc::new(self.flatten()); |
| 1173 | *guard = Some((key, Arc::clone(&flat))); |
| 1174 | RenderView::Flat(flat) |
| 1175 | } |
| 1176 | |
| 1177 | fn expand(&self, lanes: &[LaneData], depth: usize, tables: &mut Tables) -> Vec<LaneData> { |
| 1178 | let mut out: Vec<LaneData> = Vec::with_capacity(lanes.len()); |
| 1179 | let mut audio_map: Vec<usize> = Vec::new(); |
| 1180 | let mut audio_out = 0usize; |
| 1181 | for lane in lanes { |
| 1182 | let compound = lane.kind != LaneKind::Subtitle && lane.clips.iter().any(|c| is_sequence_source(c.source)); |
| 1183 | if !compound { |
| 1184 | if lane.kind == LaneKind::Audio { |
| 1185 | audio_map.push(audio_out); |
| 1186 | audio_out += 1; |
| 1187 | } |
| 1188 | let mut whole = lane.clone(); |
| 1189 | whole.clips.retain(|c| !c.mark.off); |
| 1190 | out.push(whole); |
| 1191 | continue; |
| 1192 | } |
| 1193 | let mut base = lane.clone(); |
| 1194 | base.clips.retain(|c| !is_sequence_source(c.source) && !c.mark.off); |
| 1195 | let mut extra: Vec<LaneData> = Vec::new(); |
| 1196 | for c in lane.clips.iter().filter(|c| is_sequence_source(c.source) && !c.mark.off) { |
| 1197 | let Some(id) = sequence_id_of(c.source) else { continue }; |
| 1198 | if depth >= MAX_NEST_DEPTH { |
| 1199 | continue; |
| 1200 | } |
| 1201 | let Some(inner_lanes) = self.lanes_of(id) else { continue }; |
| 1202 | let inner = self.expand(inner_lanes, depth + 1, tables); |
| 1203 | let mut same: Vec<&LaneData> = inner.iter().filter(|l| l.kind == lane.kind).collect(); |
| 1204 | if let Some(n) = self.angle_count(id) { |
| 1205 | // A multicam clip plays one angle: that angle's lane, alone. |
| 1206 | let pick = usize::from(c.angle.of(lane.kind)).min(n.saturating_sub(1)); |
| 1207 | same = same.get(pick).copied().into_iter().collect(); |
| 1208 | } |
| 1209 | for (slot, il) in same.into_iter().enumerate() { |
| 1210 | let skip = match lane.kind { |
| 1211 | LaneKind::Video => il.hidden, |
| 1212 | _ => il.muted, |
| 1213 | }; |
| 1214 | let target: &mut LaneData = if slot == 0 { |
| 1215 | &mut base |
| 1216 | } else { |
| 1217 | while extra.len() < slot { |
| 1218 | let mut e = LaneData::new(lane.kind, Vec::new()); |
| 1219 | e.gain_db = lane.gain_db; |
| 1220 | e.hidden = lane.hidden; |
| 1221 | e.muted = lane.muted; |
| 1222 | e.voice = lane.voice.clone(); |
| 1223 | extra.push(e); |
| 1224 | } |
| 1225 | &mut extra[slot - 1] |
| 1226 | }; |
| 1227 | if skip { |
| 1228 | continue; |
| 1229 | } |
| 1230 | for q in il.clips.iter().filter(|q| !q.mark.off) { |
| 1231 | let lo = q.start.max(c.in_frame); |
| 1232 | let hi = q.end().min(c.out_frame); |
| 1233 | if lo >= hi { |
| 1234 | continue; |
| 1235 | } |
| 1236 | let Some(mut p) = piece(q, lo - q.start, hi - q.start, c.start + (lo - c.in_frame)) else { continue }; |
| 1237 | if lane.kind == LaneKind::Audio { |
| 1238 | p.gain_db = (p.gain_db + il.gain_db + c.gain_db).clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB); |
| 1239 | if lo == c.in_frame && lo >= q.start { |
| 1240 | p.fade_in = p.fade_in.max(c.fade_in.min(p.frames())); |
| 1241 | } |
| 1242 | if hi == c.out_frame && hi <= q.end() { |
| 1243 | p.fade_out = p.fade_out.max(c.fade_out.min(p.frames())); |
| 1244 | } |
| 1245 | } |
| 1246 | p.link = None; |
| 1247 | if lane.kind == LaneKind::Video { |
| 1248 | let outer = c.transform.and_then(|i| tables.transform.get(usize::from(i)).copied()); |
| 1249 | let grade = c.color.and_then(|i| tables.color.get(usize::from(i)).copied()); |
| 1250 | put_over(&mut p, outer, grade, tables); |
| 1251 | } |
| 1252 | target.clips.push(p); |
| 1253 | } |
| 1254 | } |
| 1255 | } |
| 1256 | base.clips.sort_by_key(|c| c.start); |
| 1257 | if lane.kind == LaneKind::Audio { |
| 1258 | audio_map.push(audio_out); |
| 1259 | audio_out += 1 + extra.len(); |
| 1260 | } |
| 1261 | out.push(base); |
| 1262 | for mut e in extra { |
| 1263 | e.clips.sort_by_key(|c| c.start); |
| 1264 | out.push(e); |
| 1265 | } |
| 1266 | } |
| 1267 | if audio_map.iter().enumerate().any(|(i, m)| i != *m) { |
| 1268 | for l in out.iter_mut().filter(|l| l.kind == LaneKind::Audio) { |
| 1269 | for d in &mut l.ducks { |
| 1270 | if let Some(m) = audio_map.get(d.under) { |
| 1271 | d.under = *m; |
| 1272 | } |
| 1273 | } |
| 1274 | } |
| 1275 | } |
| 1276 | out |
| 1277 | } |
| 1278 | } |
| 1279 | |
| 1280 | #[cfg(test)] |
| 1281 | mod tests { |
| 1282 | use super::*; |
| 1283 | |
| 1284 | const FILE: &str = "/tmp/edith-sequence-test.mp4"; |
| 1285 | |
| 1286 | fn base() -> Project { |
| 1287 | let mut p = Project::single(FILE, 100); |
| 1288 | p.import("/tmp/edith-sequence-test-b.mp4", 0); |
| 1289 | p |
| 1290 | } |
| 1291 | |
| 1292 | fn clip(src: usize, a: u32, b: u32, start: u32) -> Clip { |
| 1293 | let mut c = Clip::source_range(src, a, b); |
| 1294 | c.start = start; |
| 1295 | c |
| 1296 | } |
| 1297 | |
| 1298 | type Strip = Vec<(LaneKind, Vec<(u32, u32, u32, usize)>)>; |
| 1299 | fn strip(p: &Project) -> Strip { |
| 1300 | p.lanes |
| 1301 | .iter() |
| 1302 | .map(|l| (l.kind, l.clips.iter().map(|c| (c.start, c.in_frame, c.out_frame, c.source)).collect())) |
| 1303 | .collect() |
| 1304 | } |
| 1305 | |
| 1306 | #[test] |
| 1307 | fn one_sequence_by_default() { |
| 1308 | let p = base(); |
| 1309 | let rows = p.sequences(); |
| 1310 | assert_eq!(rows.len(), 1); |
| 1311 | assert!(rows[0].active); |
| 1312 | assert_eq!(rows[0].frames, 100); |
| 1313 | assert!(!p.uses_sequences()); |
| 1314 | } |
| 1315 | |
| 1316 | #[test] |
| 1317 | fn new_rename_duplicate_delete_switch_and_undo() { |
| 1318 | let mut p = base(); |
| 1319 | let b = p.new_sequence(Some("B")).unwrap(); |
| 1320 | assert_eq!(p.sequence_count(), 2); |
| 1321 | assert!(p.new_sequence(Some("B")).is_err(), "names are unique"); |
| 1322 | p.rename_sequence(b, "Interview").unwrap(); |
| 1323 | assert_eq!(p.sequence_name(b), Some("Interview")); |
| 1324 | p.switch_sequence(b).unwrap(); |
| 1325 | assert_eq!(p.active_sequence(), b); |
| 1326 | assert!(p.lane(Lane::V1).is_empty(), "the new sequence is empty"); |
| 1327 | assert!(p.place(Lane::V1, 10, clip(0, 0, 20, 0))); |
| 1328 | p.switch_sequence(0).unwrap(); |
| 1329 | assert_eq!(p.lane(Lane::V1).len(), 1); |
| 1330 | assert_eq!(p.lane(Lane::V1)[0].out_frame, 100); |
| 1331 | let copy = p.duplicate_sequence(b).unwrap(); |
| 1332 | assert_eq!(p.sequence_name(copy), Some("Interview copy")); |
| 1333 | assert_eq!(p.sequence_frames(copy), 30); |
| 1334 | // The undo stack holds new, rename, place (in B), duplicate. |
| 1335 | assert!(p.undo()); |
| 1336 | assert_eq!(p.sequence_count(), 2, "the copy is gone"); |
| 1337 | assert!(p.undo()); |
| 1338 | assert_eq!(p.sequence_frames(b), 0, "the placement in B is undone, and the sequence list with it"); |
| 1339 | assert!(p.undo()); |
| 1340 | assert_eq!(p.sequence_name(b), Some("B")); |
| 1341 | assert!(p.undo()); |
| 1342 | assert_eq!(p.sequence_count(), 1); |
| 1343 | assert!(p.redo()); |
| 1344 | assert_eq!(p.sequence_count(), 2); |
| 1345 | let after = p.delete_sequence(b).unwrap(); |
| 1346 | assert_eq!(after, 0); |
| 1347 | assert!(p.delete_sequence(0).is_err(), "the last sequence stays"); |
| 1348 | assert!(p.undo()); |
| 1349 | assert_eq!(p.sequence_count(), 2); |
| 1350 | } |
| 1351 | |
| 1352 | #[test] |
| 1353 | fn nest_then_break_apart_is_the_identity() { |
| 1354 | let mut p = base(); |
| 1355 | assert!(p.place(Lane::V1, 0, clip(0, 0, 100, 0))); |
| 1356 | let before = strip(&p); |
| 1357 | let depth = p.history_len(); |
| 1358 | let n = p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], Some("Scene")).unwrap(); |
| 1359 | assert_eq!(p.history_len(), depth + 1, "one undo step"); |
| 1360 | assert_eq!(n.clips.len(), 2); |
| 1361 | assert!(p.lane(Lane::V1)[0].source >= SEQ_BASE); |
| 1362 | assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link); |
| 1363 | assert_eq!(p.sequence_frames(n.sequence), 100); |
| 1364 | let depth = p.history_len(); |
| 1365 | let made = p.break_apart(&[(Lane::V1, 0)]).unwrap(); |
| 1366 | assert_eq!(p.history_len(), depth + 1, "one undo step"); |
| 1367 | assert_eq!(made.len(), 2); |
| 1368 | assert_eq!(strip(&p), before); |
| 1369 | // And each step undoes. |
| 1370 | assert!(p.undo()); |
| 1371 | assert!(p.lane(Lane::V1)[0].source >= SEQ_BASE); |
| 1372 | assert!(p.undo()); |
| 1373 | assert_eq!(strip(&p), before); |
| 1374 | assert_eq!(p.sequence_count(), 1); |
| 1375 | } |
| 1376 | |
| 1377 | #[test] |
| 1378 | fn break_apart_drops_the_default_named_sequence_nest_made_in_the_same_undo_step() { |
| 1379 | let mut p = base(); |
| 1380 | assert!(p.place(Lane::V1, 0, clip(0, 0, 100, 0))); |
| 1381 | let n = p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], None).unwrap(); |
| 1382 | assert!(p.sequence_name(n.sequence).is_some_and(|n| n.ends_with(" (nested)"))); |
| 1383 | assert_eq!(p.sequence_count(), 2); |
| 1384 | let depth = p.history_len(); |
| 1385 | p.break_apart(&[(Lane::V1, 0)]).unwrap(); |
| 1386 | assert_eq!(p.history_len(), depth + 1, "one undo step"); |
| 1387 | assert_eq!(p.sequence_count(), 1, "no orphan tab is left"); |
| 1388 | assert!(p.undo()); |
| 1389 | assert_eq!(p.sequence_count(), 2, "undo brings the sequence back with the compound clip"); |
| 1390 | } |
| 1391 | |
| 1392 | #[test] |
| 1393 | fn a_user_sequence_named_like_a_nest_survives_break_apart_and_nest_undo() { |
| 1394 | let mut p = base(); |
| 1395 | assert!(p.place(Lane::V1, 0, clip(0, 0, 100, 0))); |
| 1396 | // The user's own sequence, named the way Nest names one. |
| 1397 | let user = p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], Some("x (nested)")).unwrap().sequence; |
| 1398 | assert_eq!(p.sequence_count(), 2); |
| 1399 | p.break_apart(&[(Lane::V1, 0)]).unwrap(); |
| 1400 | assert_eq!(p.sequence_count(), 2, "a sequence the user named is never dropped by name"); |
| 1401 | assert_eq!(p.sequence_name(user), Some("x (nested)")); |
| 1402 | // A default Nest, then undo: undo takes exactly the sequence that Nest made. |
| 1403 | let depth = p.history_len(); |
| 1404 | let made = p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], None).unwrap().sequence; |
| 1405 | assert_eq!(p.sequence_count(), 3); |
| 1406 | assert!(p.undo()); |
| 1407 | assert_eq!(p.history_len(), depth); |
| 1408 | assert_eq!(p.sequence_count(), 2); |
| 1409 | assert_eq!(p.sequence_name(user), Some("x (nested)")); |
| 1410 | assert!(p.sequence_name(made).is_none(), "the default-named one is gone with its undo step"); |
| 1411 | } |
| 1412 | |
| 1413 | #[test] |
| 1414 | fn break_apart_keeps_a_sequence_the_user_named() { |
| 1415 | let mut p = base(); |
| 1416 | assert!(p.place(Lane::V1, 0, clip(0, 0, 100, 0))); |
| 1417 | p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], Some("Scene")).unwrap(); |
| 1418 | p.break_apart(&[(Lane::V1, 0)]).unwrap(); |
| 1419 | assert_eq!(p.sequence_count(), 2, "a named sequence is the user's work"); |
| 1420 | } |
| 1421 | |
| 1422 | #[test] |
| 1423 | fn nest_refuses_a_clip_in_the_way() { |
| 1424 | let mut p = base(); |
| 1425 | p.lanes[0].clips = vec![clip(0, 0, 10, 0), clip(1, 0, 10, 10), clip(0, 10, 20, 20)]; |
| 1426 | let err = p.nest(&[(Lane::V1, 0), (Lane::V1, 2)], None).unwrap_err().to_string(); |
| 1427 | assert!(err.contains("between the selected"), "{err}"); |
| 1428 | assert_eq!(p.sequence_count(), 1, "a refusal changes nothing"); |
| 1429 | assert_eq!(p.lane(Lane::V1).len(), 3); |
| 1430 | } |
| 1431 | |
| 1432 | #[test] |
| 1433 | fn cycles_are_refused() { |
| 1434 | let mut p = base(); |
| 1435 | let b = p.new_sequence(Some("B")).unwrap(); |
| 1436 | // A plays B. |
| 1437 | p.place(Lane::V1, 0, clip(0, 0, 10, 0)); |
| 1438 | p.switch_sequence(b).unwrap(); |
| 1439 | p.place(Lane::V1, 0, clip(0, 0, 10, 0)); |
| 1440 | p.switch_sequence(0).unwrap(); |
| 1441 | p.place_sequence(b, Lane::V1, 20).unwrap(); |
| 1442 | // B may not play A (directly or not), nor itself. |
| 1443 | p.switch_sequence(b).unwrap(); |
| 1444 | let err = p.place_sequence(0, Lane::V1, 40).unwrap_err().to_string(); |
| 1445 | assert!(err.contains("inside itself"), "{err}"); |
| 1446 | let own = Clip::source_range(sequence_source(b), 0, 5); |
| 1447 | assert!(!p.place(Lane::V1, 40, own), "a sequence cannot play itself"); |
| 1448 | // A copy pasted from the clipboard is refused the same way. |
| 1449 | p.switch_sequence(0).unwrap(); |
| 1450 | let comp = p.lane(Lane::V1).iter().find(|c| c.source >= SEQ_BASE).unwrap().clone(); |
| 1451 | p.switch_sequence(b).unwrap(); |
| 1452 | assert!(!p.paste(50, comp)); |
| 1453 | // A file that loops is refused by the check the loader uses. |
| 1454 | let mut q = p.raw_snapshot(); |
| 1455 | q.lanes[0].clips.push(clip(0, 0, 1, 0)); |
| 1456 | q.lanes[0].clips.last_mut().unwrap().source = sequence_source(0); |
| 1457 | assert!(q.check_sequences().is_err()); |
| 1458 | // A sequence a compound clip plays cannot be deleted. |
| 1459 | p.switch_sequence(0).unwrap(); |
| 1460 | let err = p.delete_sequence(b).unwrap_err().to_string(); |
| 1461 | assert!(err.contains("played by compound clips"), "{err}"); |
| 1462 | } |
| 1463 | |
| 1464 | #[test] |
| 1465 | fn a_compound_expands_to_the_clips_it_stands_for() { |
| 1466 | let mut p = base(); |
| 1467 | p.lanes[0].clips = vec![clip(0, 10, 40, 5), clip(1, 0, 20, 40)]; |
| 1468 | p.lanes[1].clips = vec![clip(0, 10, 40, 5)]; |
| 1469 | let flat = strip(&p); |
| 1470 | p.nest(&[(Lane::V1, 0), (Lane::V1, 1), (Lane::A1, 0)], None).unwrap(); |
| 1471 | let view = p.render_view(); |
| 1472 | assert_eq!(strip(&view), flat, "the nested render is the flat one"); |
| 1473 | assert_eq!(view.timeline_frames(), p.timeline_frames()); |
| 1474 | } |
| 1475 | |
| 1476 | #[test] |
| 1477 | fn a_trimmed_compound_shows_the_window() { |
| 1478 | let mut p = base(); |
| 1479 | p.lanes[0].clips = vec![clip(0, 0, 60, 0)]; |
| 1480 | p.lanes[1].clips = vec![clip(0, 0, 60, 0)]; |
| 1481 | p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], None).unwrap(); |
| 1482 | // Trim the compound to inner frames 10..40, and move it. |
| 1483 | for kind in [LaneKind::Video, LaneKind::Audio] { |
| 1484 | let lane = Lane::new(kind, 0); |
| 1485 | let at = p.index(lane).unwrap(); |
| 1486 | let c = &mut p.lanes[at].clips[0]; |
| 1487 | c.in_frame = 10; |
| 1488 | c.out_frame = 40; |
| 1489 | c.start = 100; |
| 1490 | } |
| 1491 | let view = p.render_view(); |
| 1492 | assert_eq!(view.lane(Lane::V1).len(), 1); |
| 1493 | let v = &view.lane(Lane::V1)[0]; |
| 1494 | assert_eq!((v.start, v.in_frame, v.out_frame, v.source), (100, 10, 40, 0)); |
| 1495 | let a = &view.lane(Lane::A1)[0]; |
| 1496 | assert_eq!((a.start, a.in_frame, a.out_frame, a.source), (100, 10, 40, 0)); |
| 1497 | } |
| 1498 | |
| 1499 | #[test] |
| 1500 | fn inner_layers_and_sound_come_through_the_nest() { |
| 1501 | let mut p = base(); |
| 1502 | p.add_lane(LaneKind::Video); |
| 1503 | p.add_lane(LaneKind::Audio); |
| 1504 | p.lanes[0].clips = vec![clip(0, 0, 50, 0)]; |
| 1505 | let v2 = p.index(Lane::new(LaneKind::Video, 1)).unwrap(); |
| 1506 | p.lanes[v2].clips = vec![clip(1, 0, 50, 10)]; |
| 1507 | let a1 = p.index(Lane::A1).unwrap(); |
| 1508 | p.lanes[a1].clips = vec![clip(0, 0, 50, 0)]; |
| 1509 | let a2 = p.index(Lane::new(LaneKind::Audio, 1)).unwrap(); |
| 1510 | p.lanes[a2].clips = vec![clip(1, 0, 30, 5)]; |
| 1511 | let picks = vec![ |
| 1512 | (Lane::V1, 0), |
| 1513 | (Lane::new(LaneKind::Video, 1), 0), |
| 1514 | (Lane::A1, 0), |
| 1515 | (Lane::new(LaneKind::Audio, 1), 0), |
| 1516 | ]; |
| 1517 | p.nest(&picks, None).unwrap(); |
| 1518 | let view = p.render_view(); |
| 1519 | assert!(view.lane_count(LaneKind::Video) >= 2, "the inner layer keeps its own lane"); |
| 1520 | assert!(view.lane_count(LaneKind::Audio) >= 2, "both sounds are in the mix"); |
| 1521 | assert_eq!(view.lane(Lane::new(LaneKind::Video, 1))[0].start, 10); |
| 1522 | assert_eq!(view.lane(Lane::new(LaneKind::Audio, 1))[0].start, 5); |
| 1523 | assert_eq!(view.audio_lanes().len(), 2); |
| 1524 | // The inner mix and mute are honoured. |
| 1525 | let mut q = p.raw_snapshot(); |
| 1526 | q.switch_sequence(1).unwrap(); |
| 1527 | let second = q.index(Lane::new(LaneKind::Audio, 1)).unwrap(); |
| 1528 | q.lanes[second].muted = true; |
| 1529 | q.switch_sequence(0).unwrap(); |
| 1530 | assert_eq!(q.render_view().lane(Lane::new(LaneKind::Audio, 1)).len(), 0, "a muted inner lane is silent"); |
| 1531 | } |
| 1532 | |
| 1533 | #[test] |
| 1534 | fn nested_compounds_expand_through_each_other() { |
| 1535 | let mut p = base(); |
| 1536 | p.lanes[0].clips = vec![clip(0, 0, 50, 0)]; |
| 1537 | p.lanes[1].clips = vec![clip(0, 0, 50, 0)]; |
| 1538 | let first = p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], Some("Inner")).unwrap(); |
| 1539 | let second = p.nest(&[(Lane::V1, 0), (Lane::A1, 0)], Some("Outer")).unwrap(); |
| 1540 | assert_ne!(first.sequence, second.sequence); |
| 1541 | let view = p.render_view(); |
| 1542 | assert_eq!(strip(&view)[0].1, vec![(0, 0, 50, 0)]); |
| 1543 | assert_eq!(strip(&view)[1].1, vec![(0, 0, 50, 0)]); |
| 1544 | assert!(p.reaches(second.sequence, first.sequence)); |
| 1545 | assert!(!p.reaches(first.sequence, second.sequence)); |
| 1546 | } |
| 1547 | |
| 1548 | #[test] |
| 1549 | fn export_of_a_named_sequence_renders_that_one() { |
| 1550 | let mut p = base(); |
| 1551 | let b = p.new_sequence(Some("B")).unwrap(); |
| 1552 | p.switch_sequence(b).unwrap(); |
| 1553 | p.place(Lane::V1, 0, clip(1, 0, 25, 0)); |
| 1554 | p.switch_sequence(0).unwrap(); |
| 1555 | let snap = p.render_snapshot(Some(b)).unwrap(); |
| 1556 | assert_eq!(snap.lane(Lane::V1)[0].source, 1); |
| 1557 | assert_eq!(snap.timeline_frames(), 25); |
| 1558 | assert_eq!(p.active_sequence(), 0, "the project itself did not move"); |
| 1559 | assert!(p.render_snapshot(Some(99)).is_err()); |
| 1560 | } |
| 1561 | } |