forge
Explore
Log in

Don't you dare go Hollow

The project holds N lanes, V1..Vn and A1..An

Browse files at this commit

b474a9be667bb5e5b6b49bee531c7cbcc9e9a5e1Ahmet Kaan GümüşParent: 29f2836154fd69
  • refactor
    • the project holds N lanes, V1..Vn and A1..An
Show full message
♻️ refactor(engine): the project holds N lanes, V1..Vn and A1..An

Merge of the multi-lane winner (candidate B) onto the S5a main, plus the
three grafts the judge picked out of candidate A and the delete-selected
fix it flagged:

* LaneData::two_lanes(), one place for the pair single() and from_parts()
  both build;
* a_group_may_span_any_lane: hand-built lanes driving links_are_consistent
  directly -- one take on V1 + A2 with the lanes between it empty is legal,
  and both ways to break the rule are asserted by their exact message;
* add_lane doc: an empty new lane is legal even though from_parts refuses
  an all-empty project -- the lanes that were there still hold the timeline;
* delete_selected is exhaustive over lane.kind and explicit about ord: it
  hands V1/A1 indexes to engine calls that mean V1/A1, so a second-lane
  selection would have deleted a different clip under a _ => false wildcard.

Conflicts, all against the S5a Source model: without_orphan_sources keeps
B's crate::Result and its >1-lane-per-kind refusal but returns Vec<Source>,
and Lane::Audio in place_stream_at/import_audio became Lane::A1.
crates/app/src/main.rsmodified+41 -23
@@ -11,7 +11,7 @@ use std::time::{Duration, Instant};
11 11
12 use engine::audio::StreamInfo;12 use engine::audio::StreamInfo;
13 use engine::export::ExportSettings;13 use engine::export::ExportSettings;
14-use engine::project::{Lane, Source};14+use engine::project::{Lane, LaneKind, Source};
15 use engine::{Clip, ExportHandle, Frame, PlaybackSession};15 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
16 use gpui::{16 use gpui::{
17 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,17 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
@@ -494,14 +494,34 @@ impl Player {
494 if self.exporting().is_some() {494 if self.exporting().is_some() {
495 return;495 return;
496 }496 }
497- let deleted = match (&mut self.session, self.selected.take()) {497+ let selected = self.selected.take();
498- (Some(session), Some((Lane::Video, idx))) => session.delete_clip(idx),498+ // Exhaustive over the kind, and explicit about the ord: both engine
499- (Some(session), Some((Lane::Audio, idx))) => match video_half(session, idx) {499+ // calls below take a *first*-lane index (`delete_clip` deletes the V1
500+ // clip at `idx`, `video_half` reads A1), so a selection on a second
501+ // lane of either kind would delete a different clip than the one
502+ // clicked. It is refused by name until the add-track slice teaches
503+ // those two a lane -- a wildcard here would drop it silently.
504+ let deleted = match (&mut self.session, selected) {
505+ (Some(session), Some((lane, idx))) if lane.ord == 0 => match lane.kind {
506+ LaneKind::Video => session.delete_clip(idx),
507+ LaneKind::Audio => match video_half(session, idx) {
500 Some(video) => session.delete_clip(video),508 Some(video) => session.delete_clip(video),
501- None => session.lift_clip(Lane::Audio, idx),509+ None => session.lift_clip(lane, idx),
510+ },
502 },511 },
503 _ => false,512 _ => false,
504 };513 };
514+ if let Some((lane, _)) = selected.filter(|_| !deleted) {
515+ if lane.ord > 0 {
516+ self.notice = Some(
517+ format!(
518+ "NOTHING DELETED — delete does not reach {} yet",
519+ lane.label()
520+ )
521+ .into(),
522+ );
523+ }
524+ }
505 if deleted {525 if deleted {
506 self.reset_after_reseek();526 self.reset_after_reseek();
507 }527 }
@@ -654,7 +674,7 @@ impl Player {
654 // dropped on the video lane it is refused by name, and asked for by the674 // dropped on the video lane it is refused by name, and asked for by the
655 // Add button (which names no lane) it goes to the audio one -- which is675 // Add button (which names no lane) it goes to the audio one -- which is
656 // the engine's choice, in `place_stream_at`, not one made twice here.676 // the engine's choice, in `place_stream_at`, not one made twice here.
657- if engine::is_audio(path) && onto == Some(Lane::Video) {677+ if engine::is_audio(path) && onto == Some(Lane::V1) {
658 let name = file_name(path);678 let name = file_name(path);
659 self.notice = Some(679 self.notice = Some(
660 format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(),680 format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(),
@@ -1748,8 +1768,8 @@ impl Player {
1748 ),1768 ),
1749 ),1769 ),
1750 )1770 )
1751- .child(self.lane_row(Lane::Video, "V1", duration, filled, cx))1771+ .child(self.lane_row(Lane::V1, "V1", duration, filled, cx))
1752- .child(self.lane_row(Lane::Audio, "A1", duration, filled, cx))1772+ .child(self.lane_row(Lane::A1, "A1", duration, filled, cx))
1753 }1773 }
1754 1774
1755 /// A notice holds its own bar, full width, until it is answered: any key1775 /// A notice holds its own bar, full width, until it is answered: any key
@@ -2281,9 +2301,10 @@ impl Player {
2281 let (clips, others) = match &self.session {2301 let (clips, others) = match &self.session {
2282 Some(session) => (2302 Some(session) => (
2283 session.lane_clips(lane),2303 session.lane_clips(lane),
2284- session.lane_clips(match lane {2304+ session.lane_clips(if lane.kind == LaneKind::Video {
2285- Lane::Video => Lane::Audio,2305+ Lane::A1
2286- Lane::Audio => Lane::Video,2306+ } else {
2307+ Lane::V1
2287 }),2308 }),
2288 ),2309 ),
2289 None => (&[][..], &[][..]),2310 None => (&[][..], &[][..]),
@@ -2293,7 +2314,7 @@ impl Player {
2293 .as_ref()2314 .as_ref()
2294 .map_or(&[][..], PlaybackSession::sources);2315 .map_or(&[][..], PlaybackSession::sources);
2295 let (sel, sel_link) = (self.selected, self.selected_link());2316 let (sel, sel_link) = (self.selected, self.selected_link());
2296- let audio = lane == Lane::Audio;2317+ let audio = lane.kind == LaneKind::Audio;
2297 let tip: SharedString = format!(2318 let tip: SharedString = format!(
2298 "Select — {} removes the take, {} leaves a gap, {} rejoins a cut",2319 "Select — {} removes the take, {} leaves a gap, {} rejoins a cut",
2299 self.keymap.display(ActionId::Delete),2320 self.keymap.display(ActionId::Delete),
@@ -2615,9 +2636,9 @@ fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>)
2615 /// Both lanes' clips, which is everything the timeline knows about its sources.2636 /// Both lanes' clips, which is everything the timeline knows about its sources.
2616 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {2637 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2617 session2638 session
2618- .lane_clips(Lane::Video)2639+ .lane_clips(Lane::V1)
2619 .iter()2640 .iter()
2620- .chain(session.lane_clips(Lane::Audio))2641+ .chain(session.lane_clips(Lane::A1))
2621 }2642 }
2622 2643
2623 /// How long a source is, as the timeline knows it: the furthest frame any clip2644 /// How long a source is, as the timeline knows it: the furthest frame any clip
@@ -2989,9 +3010,9 @@ fn start_frac(start: f64, total: f64) -> f32 {
2989 /// still holds that half. `None` for a half whose picture was lifted -- which is3010 /// still holds that half. `None` for a half whose picture was lifted -- which is
2990 /// what makes it a thing of its own to delete.3011 /// what makes it a thing of its own to delete.
2991 fn video_half(session: &PlaybackSession, audio: usize) -> Option<usize> {3012 fn video_half(session: &PlaybackSession, audio: usize) -> Option<usize> {
2992- let link = session.lane_clips(Lane::Audio).get(audio)?.link?;3013+ let link = session.lane_clips(Lane::A1).get(audio)?.link?;
2993 session3014 session
2994- .lane_clips(Lane::Video)3015+ .lane_clips(Lane::V1)
2995 .iter()3016 .iter()
2996 .position(|clip| clip.link == Some(link))3017 .position(|clip| clip.link == Some(link))
2997 }3018 }
@@ -3590,10 +3611,7 @@ mod tests {
3590 // The whole of source 1 went in and nothing was painted over: the3611 // The whole of source 1 went in and nothing was painted over: the
3591 // timeline is longer by exactly that file.3612 // timeline is longer by exactly that file.
3592 assert_eq!(session.timeline_duration(), 13.0);3613 assert_eq!(session.timeline_duration(), 13.0);
3593- let (video, audio) = (3614+ let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
3594- session.lane_clips(Lane::Video),
3595- session.lane_clips(Lane::Audio),
3596- );
3597 // One take, not a video clip with no sound under it: both lanes hold3615 // One take, not a video clip with no sound under it: both lanes hold
3598 // the same clip at the same place, in the same group.3616 // the same clip at the same place, in the same group.
3599 let at = |lane: &[Clip]| {3617 let at = |lane: &[Clip]| {
@@ -4097,13 +4115,13 @@ mod tests {
4097 4115
4098 #[test]4116 #[test]
4099 fn a_click_marks_the_whole_group_and_nothing_else() {4117 fn a_click_marks_the_whole_group_and_nothing_else() {
4100- let (v, a) = ((Lane::Video, 0), (Lane::Audio, 0));4118+ let (v, a) = ((Lane::V1, 0), (Lane::A1, 0));
4101 // Clicking the video half of group 1 marks the audio half with it.4119 // Clicking the video half of group 1 marks the audio half with it.
4102 assert!(marked(v, Some(1), Some(v), Some(1)));4120 assert!(marked(v, Some(1), Some(v), Some(1)));
4103 assert!(marked(a, Some(1), Some(v), Some(1)));4121 assert!(marked(a, Some(1), Some(v), Some(1)));
4104 // Another group's clips stay unmarked, in either lane.4122 // Another group's clips stay unmarked, in either lane.
4105- assert!(!marked((Lane::Video, 1), Some(2), Some(v), Some(1)));4123+ assert!(!marked((Lane::V1, 1), Some(2), Some(v), Some(1)));
4106- assert!(!marked((Lane::Audio, 1), Some(2), Some(v), Some(1)));4124+ assert!(!marked((Lane::A1, 1), Some(2), Some(v), Some(1)));
4107 // A half a lift left behind has no group: it marks itself only, which4125 // A half a lift left behind has no group: it marks itself only, which
4108 // is what makes it separately deletable. Two ungrouped clips must not4126 // is what makes it separately deletable. Two ungrouped clips must not
4109 // mark each other by both being ungrouped.4127 // mark each other by both being ungrouped.
crates/engine/src/export.rsmodified+1 -1
@@ -179,7 +179,7 @@ fn run(
179 // Spans, not clips: a gap in the video lane is part of the timeline and179 // Spans, not clips: a gap in the video lane is part of the timeline and
180 // gets encoded too, as black frames. The picture count is therefore180 // gets encoded too, as black frames. The picture count is therefore
181 // `timeline_frames` however the lane is arranged.181 // `timeline_frames` however the lane is arranged.
182- for span in project.spans_from(Lane::Video, 0) {182+ for span in project.spans_from(Lane::V1, 0) {
183 // Every clip reopens its own source file at its own in point; the183 // Every clip reopens its own source file at its own in point; the
184 // encoder is *not* reopened, so the export is one continuous stream184 // encoder is *not* reopened, so the export is one continuous stream
185 // whose GOP boundaries need not line up with the cuts -- nor with the185 // whose GOP boundaries need not line up with the cuts -- nor with the
crates/engine/src/playback.rsmodified+8 -8
@@ -149,7 +149,7 @@ impl PlaybackSession {
149 // One clip per lane covering the file, so timeline == source until the149 // One clip per lane covering the file, so timeline == source until the
150 // first edit -- and the range opened above is exactly that clip's.150 // first edit -- and the range opened above is exactly that clip's.
151 let project = Project::single(&path, meta.frame_count);151 let project = Project::single(&path, meta.frame_count);
152- let span = project.span_at(Lane::Video, 0).expect("never empty");152+ let span = project.span_at(Lane::V1, 0).expect("never empty");
153 Ok(Self {153 Ok(Self {
154 meta,154 meta,
155 frames: stream.frames,155 frames: stream.frames,
@@ -242,7 +242,7 @@ impl PlaybackSession {
242 242
243 let playhead = doc.playhead;243 let playhead = doc.playhead;
244 let project = Project::from_parts(doc.sources, doc.video, doc.audio)?;244 let project = Project::from_parts(doc.sources, doc.video, doc.audio)?;
245- let span = project.span_at(Lane::Video, 0).expect("never empty");245+ let span = project.span_at(Lane::V1, 0).expect("never empty");
246 // Last, because it is the one thing here that cannot be taken back: the246 // Last, because it is the one thing here that cannot be taken back: the
247 // feeder thread outlives the `Audio` value (it holds its own clones) and247 // feeder thread outlives the `Audio` value (it holds its own clones) and
248 // only a session's `drop` retires it, so a refusal above this line would248 // only a session's `drop` retires it, so a refusal above this line would
@@ -295,7 +295,7 @@ impl PlaybackSession {
295 /// [`crate::edith`]). Sources no clip plays from are left out, and the295 /// [`crate::edith`]). Sources no clip plays from are left out, and the
296 /// playhead is saved with it so a reopened project resumes where it stood.296 /// playhead is saved with it so a reopened project resumes where it stood.
297 pub fn save_project(&self, path: &Path) -> crate::Result<()> {297 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
298- let (sources, video, audio) = self.project.without_orphan_sources();298+ let (sources, video, audio) = self.project.without_orphan_sources()?;
299 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)299 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
300 .min(self.project.timeline_frames().saturating_sub(1));300 .min(self.project.timeline_frames().saturating_sub(1));
301 crate::edith::save(path, &sources, &video, &audio, playhead)301 crate::edith::save(path, &sources, &video, &audio, playhead)
@@ -359,7 +359,7 @@ impl PlaybackSession {
359 /// clip under the running worker and only the mapping stays true.359 /// clip under the running worker and only the mapping stays true.
360 fn next_clip(&mut self) -> bool {360 fn next_clip(&mut self) -> bool {
361 let next = self.span.end();361 let next = self.span.end();
362- let Some(span) = self.project.span_at(Lane::Video, next) else {362+ let Some(span) = self.project.span_at(Lane::V1, next) else {
363 return false;363 return false;
364 };364 };
365 // We only get here on a disconnect, so the old worker has already365 // We only get here on a disconnect, so the old worker has already
@@ -423,7 +423,7 @@ impl PlaybackSession {
423 /// [`Project::sources`] each clip plays from -- what a lane needs to colour423 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
424 /// an imported clip differently from the file the session was opened with.424 /// an imported clip differently from the file the session was opened with.
425 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {425 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
426- self.lane_spans_by_source(Lane::Video)426+ self.lane_spans_by_source(Lane::V1)
427 }427 }
428 428
429 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,429 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
@@ -539,7 +539,7 @@ impl PlaybackSession {
539 // nothing, because there is nothing on the video lane to move along539 // nothing, because there is nothing on the video lane to move along
540 // with it.540 // with it.
541 Ok(match crate::is_audio(path) {541 Ok(match crate::is_audio(path) {
542- true => self.place_at(Lane::Audio, timeline_secs, clip),542+ true => self.place_at(Lane::A1, timeline_secs, clip),
543 false => self.paste_at(timeline_secs, clip),543 false => self.paste_at(timeline_secs, clip),
544 })544 })
545 }545 }
@@ -630,7 +630,7 @@ impl PlaybackSession {
630 let source = self.project.import(path, 0);630 let source = self.project.import(path, 0);
631 let at = self.project.timeline_frames();631 let at = self.project.timeline_frames();
632 self.project.place(632 self.project.place(
633- Lane::Audio,633+ Lane::A1,
634 at,634 at,
635 Clip {635 Clip {
636 start: at,636 start: at,
@@ -752,7 +752,7 @@ impl PlaybackSession {
752 // `target` is inside the timeline (never empty), so this always spans;752 // `target` is inside the timeline (never empty), so this always spans;
753 // the span runs from there to the end of whatever it landed in -- a753 // the span runs from there to the end of whatever it landed in -- a
754 // clip, or a gap, which starts a black-frame worker instead.754 // clip, or a gap, which starts a black-frame worker instead.
755- if let Some(span) = self.project.span_at(Lane::Video, target) {755+ if let Some(span) = self.project.span_at(Lane::V1, target) {
756 self.start_span(span);756 self.start_span(span);
757 }757 }
758 self.eos = false;758 self.eos = false;
crates/engine/src/project.rsmodified+718 -226
@@ -1,6 +1,8 @@
1-//! Edit list: two lanes of *placed* source ranges. Pure data, no I/O.1+//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2 //!2 //!
3-//! A [`Project`] holds a video lane and an audio lane. Each lane is a list of3+//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4+//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5+//! list of
4 //! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of6 //! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
5 //! *source* frames it plays, which file it plays it from, and -- the whole model7 //! *source* frames it plays, which file it plays it from, and -- the whole model
6 //! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an8 //! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
@@ -11,8 +13,10 @@
11 //! a hole cannot disagree with its neighbours about how long it is;13 //! a hole cannot disagree with its neighbours about how long it is;
12 //! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a14 //! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
13 //! splice of the list;15 //! splice of the list;
14-//! * the lanes are independent: deleting audio under a picture is one lane's16+//! * the lanes are independent and are peers: deleting audio under a picture is
15-//! business, and the picture does not shift.17+//! one lane's business, and the picture does not shift. No lane is special
18+//! except by what a *caller* reads -- playback and export take `V1`, the audio
19+//! worker takes `A1`, until a compositing slice teaches them the rest.
16 //!20 //!
17 //! The price is one invariant this module enforces at every mutation and every21 //! The price is one invariant this module enforces at every mutation and every
18 //! constructor: within a lane, clips are **sorted by `start` and never overlap**22 //! constructor: within a lane, clips are **sorted by `start` and never overlap**
@@ -24,14 +28,17 @@
24 //! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).28 //! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
25 //!29 //!
26 //! Grouping is [`Clip::link`]: clips carrying the same id were split from the30 //! Grouping is [`Clip::link`]: clips carrying the same id were split from the
27-//! same take and move together. [`Project::split`] cuts every lane at a timeline31+//! same take and move together. An id is *not* a pairing of two lanes -- it
28-//! frame and hands the two sides two fresh ids; [`Project::regroup`] is its32+//! names at most one clip per lane and every clip carrying it covers the same
29-//! inverse and rejoins them.33+//! timeline span, on however many lanes ([`links_are_consistent`]).
34+//! [`Project::split`] cuts every lane at a timeline frame and hands each side
35+//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
36+//! is its inverse and rejoins them.
30 //!37 //!
31 //! Editing is metadata only. [`Project::split`] changes no timeline->source38 //! Editing is metadata only. [`Project::split`] changes no timeline->source
32 //! mapping, so a running decoder stays correct across it; everything else does39 //! mapping, so a running decoder stays correct across it; everything else does
33-//! and the caller must reseek. Every successful edit snapshots both lanes, so40+//! and the caller must reseek. Every successful edit snapshots every lane, so
34-//! [`Project::undo`] is an exact restore.41+//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
35 //!42 //!
36 //! A clip names its file by *index* into [`Project::sources`], which is43 //! A clip names its file by *index* into [`Project::sources`], which is
37 //! append-only: an index handed out once stays valid forever, so a clip on the44 //! append-only: an index handed out once stays valid forever, so a clip on the
@@ -96,19 +103,74 @@ impl Source {
96 }103 }
97 }104 }
98 105
99-/// Which lane an operation acts on. The lanes are peers: no operation reads one106+/// What a lane carries, which is what a *gap* in it means: black frames on a
100-/// to decide what to do to the other, except the grouped ones that say so.107+/// video lane, silence on an audio one.
101 #[derive(Clone, Copy, PartialEq, Eq, Debug)]108 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
102-pub enum Lane {109+pub enum LaneKind {
103 Video,110 Video,
104 Audio,111 Audio,
105 }112 }
106 113
114+/// Which lane an operation acts on: a kind plus a 0-based position among the
115+/// lanes of that kind, so [`Lane::V1`] is the first video lane and
116+/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
117+///
118+/// A handle, not the lane itself. It stays meaningful while lanes are added,
119+/// and one naming a lane that is not there reads as an empty lane and refuses
120+/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
121+/// bounds check of its own.
122+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
123+pub struct Lane {
124+ pub kind: LaneKind,
125+ pub ord: usize,
126+}
127+
107 impl Lane {128 impl Lane {
108- pub const ALL: [Lane; 2] = [Lane::Video, Lane::Audio];129+ /// The first video lane: what a decoder plays and what an export renders.
130+ pub const V1: Lane = Lane::new(LaneKind::Video, 0);
131+ /// The first audio lane: what the audio worker plays.
132+ pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
109 133
110- fn index(self) -> usize {134+ pub const fn new(kind: LaneKind, ord: usize) -> Self {
111- self as usize135+ Self { kind, ord }
136+ }
137+
138+ /// `V1`, `A2`: how a lane is written in a header column and named in an
139+ /// error about it.
140+ pub fn label(self) -> String {
141+ let kind = match self.kind {
142+ LaneKind::Video => 'V',
143+ LaneKind::Audio => 'A',
144+ };
145+ format!("{kind}{}", self.ord + 1)
146+ }
147+}
148+
149+/// One lane: what it is and what it holds. A struct rather than a bare
150+/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
151+/// compositing mode, a name -- and it belongs next to the clips it applies to.
152+#[derive(Clone, Debug)]
153+struct LaneData {
154+ kind: LaneKind,
155+ /// Sorted by `start` and disjoint ([`sorted_disjoint`]).
156+ clips: Vec<Clip>,
157+}
158+
159+impl LaneData {
160+ /// The two lanes a project starts with and the only two a `.edith` file
161+ /// holds: `V1` then `A1`, in display order. One place, because every door
162+ /// that builds a project from the outside builds exactly this pair.
163+ fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
164+ vec![
165+ LaneData {
166+ kind: LaneKind::Video,
167+ clips: video,
168+ },
169+ LaneData {
170+ kind: LaneKind::Audio,
171+ clips: audio,
172+ },
173+ ]
112 }174 }
113 }175 }
114 176
@@ -138,20 +200,22 @@ impl Span {
138 pub struct Project {200 pub struct Project {
139 /// Append-only: never popped, never reordered. See the module docs.201 /// Append-only: never popped, never reordered. See the module docs.
140 sources: Vec<Source>,202 sources: Vec<Source>,
141- /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint.203+ /// In display order, which is the order [`Lane::ord`] counts in: the nth
142- lanes: [Vec<Clip>; 2],204+ /// lane of a kind here is that kind's `ord` n. Never empty.
143- /// Snapshots pushed *before* each successful edit; `undo` pops one.205+ lanes: Vec<LaneData>,
144- history: Vec<[Vec<Clip>; 2]>,206+ /// Snapshots pushed *before* each successful edit; `undo` pops one. The
207+ /// whole lane list, so adding a lane undoes as well.
208+ history: Vec<Vec<LaneData>>,
145 /// Never rolled back by an undo: an id retired by an undone split must not209 /// Never rolled back by an undo: an id retired by an undone split must not
146 /// come back and group two clips that were never together.210 /// come back and group two clips that were never together.
147 next_link: u32,211 next_link: u32,
148 }212 }
149 213
150 impl Project {214 impl Project {
151- /// One clip per lane covering the whole of `path`, the two grouped -- the215+ /// `V1` and `A1`, one clip each covering the whole of `path` and the two
152- /// state of a freshly opened video, where the timeline is the source.216+ /// grouped -- the state of a freshly opened video, where the timeline is the
153- /// `frame_count` of 0 would break the never-empty invariant, so it is217+ /// source. `frame_count` of 0 would break the never-empty invariant, so it
154- /// clamped to one frame.218+ /// is clamped to one frame.
155 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {219 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
156 let clip = Clip {220 let clip = Clip {
157 start: 0,221 start: 0,
@@ -164,14 +228,16 @@ impl Project {
164 // A file is opened on its first audio stream: nothing has picked228 // A file is opened on its first audio stream: nothing has picked
165 // one yet, and every file with audio at all has that one.229 // one yet, and every file with audio at all has that one.
166 sources: vec![Source::new(path, 0)],230 sources: vec![Source::new(path, 0)],
167- lanes: [vec![clip], vec![clip]],231+ lanes: LaneData::two_lanes(vec![clip], vec![clip]),
168 history: Vec::new(),232 history: Vec::new(),
169 next_link: 1,233 next_link: 1,
170 }234 }
171 }235 }
172 236
173 /// A project rebuilt from a saved edit list -- the load half of237 /// A project rebuilt from a saved edit list -- the load half of
174- /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is238+ /// [`crate::edith`], which is a two-lane format, so this door takes `V1` and
239+ /// `A1` and nothing else (see [`Project::without_orphan_sources`], which
240+ /// refuses to *write* more). History is *not* saved, so [`Project::undo`] is
175 /// `false` until the first edit of the new session. This is the one door241 /// `false` until the first edit of the new session. This is the one door
176 /// untrusted parts come in through, so every invariant every other242 /// untrusted parts come in through, so every invariant every other
177 /// constructor keeps is checked here, by name and in release: both lanes243 /// constructor keeps is checked here, by name and in release: both lanes
@@ -186,9 +252,10 @@ impl Project {
186 if video.is_empty() && audio.is_empty() {252 if video.is_empty() && audio.is_empty() {
187 return Err("both lanes are empty: that is not a project".into());253 return Err("both lanes are empty: that is not a project".into());
188 }254 }
189- let lanes = [video, audio];255+ let lanes = LaneData::two_lanes(video, audio);
190- for (lane, name) in lanes.iter().zip(["video", "audio"]) {256+ for (data, lane) in lanes.iter().zip(handles(&lanes)) {
191- for c in lane {257+ let name = lane.label();
258+ for c in &data.clips {
192 if c.out_frame <= c.in_frame {259 if c.out_frame <= c.in_frame {
193 return Err(format!(260 return Err(format!(
194 "{name} clip at {} plays the empty range [{}, {})",261 "{name} clip at {} plays the empty range [{}, {})",
@@ -213,14 +280,14 @@ impl Project {
213 .into());280 .into());
214 }281 }
215 }282 }
216- if !sorted_disjoint(lane) {283+ if !sorted_disjoint(&data.clips) {
217 return Err(format!("the {name} lane is out of order or overlaps itself").into());284 return Err(format!("the {name} lane is out of order or overlaps itself").into());
218 }285 }
219 }286 }
220 links_are_consistent(&lanes)?;287 links_are_consistent(&lanes)?;
221 let next_link = lanes288 let next_link = lanes
222 .iter()289 .iter()
223- .flatten()290+ .flat_map(|l| &l.clips)
224 .filter_map(|c| c.link)291 .filter_map(|c| c.link)
225 .max()292 .max()
226 // Saturating so a crafted file cannot make the counter wrap: at the293 // Saturating so a crafted file cannot make the counter wrap: at the
@@ -237,14 +304,60 @@ impl Project {
237 })304 })
238 }305 }
239 306
240- /// The video lane -- what an export renders and what a single-lane caller307+ /// The first video lane -- what an export renders and what a single-lane
241- /// still means by "the clips".308+ /// caller still means by "the clips".
242 pub fn clips(&self) -> &[Clip] {309 pub fn clips(&self) -> &[Clip] {
243- self.lane(Lane::Video)310+ self.lane(Lane::V1)
244 }311 }
245 312
313+ /// The clips of `lane`, or nothing at all for a lane that is not there.
246 pub fn lane(&self, lane: Lane) -> &[Clip] {314 pub fn lane(&self, lane: Lane) -> &[Clip] {
247- &self.lanes[lane.index()]315+ self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
316+ }
317+
318+ /// Every lane's handle, in display order -- what a walk over "all lanes"
319+ /// iterates, and what a front-end lays out top to bottom.
320+ pub fn lanes(&self) -> Vec<Lane> {
321+ handles(&self.lanes)
322+ }
323+
324+ /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
325+ /// for every `ord` below it, and none at or above it.
326+ pub fn lane_count(&self, kind: LaneKind) -> usize {
327+ self.lanes.iter().filter(|l| l.kind == kind).count()
328+ }
329+
330+ /// Appends an empty lane of `kind` and hands back its handle. One undo
331+ /// step, because the lane list is state a front-end shows: an added lane
332+ /// that could not be taken back would be the one edit with no way out.
333+ /// Nothing plays differently until something is placed on it.
334+ ///
335+ /// The new lane being empty is fine even though [`Project::from_parts`]
336+ /// refuses an all-empty project: the lanes that were there still hold the
337+ /// timeline, and "no lane holds anything" is what that door refuses.
338+ pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
339+ self.snapshot();
340+ self.lanes.push(LaneData {
341+ kind,
342+ clips: Vec::new(),
343+ });
344+ Lane::new(kind, self.lane_count(kind) - 1)
345+ }
346+
347+ /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
348+ /// not there. The one place a handle becomes a position.
349+ fn index(&self, lane: Lane) -> Option<usize> {
350+ self.lanes
351+ .iter()
352+ .enumerate()
353+ .filter(|(_, l)| l.kind == lane.kind)
354+ .map(|(i, _)| i)
355+ .nth(lane.ord)
356+ }
357+
358+ fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
359+ let i = self.index(lane)?;
360+ Some(&mut self.lanes[i].clips)
248 }361 }
249 362
250 /// The files the clips index into, in import order; index 0 is the file the363 /// The files the clips index into, in import order; index 0 is the file the
@@ -280,7 +393,7 @@ impl Project {
280 }393 }
281 }394 }
282 395
283- /// Append a whole-file clip of `source` to the end of *both* lanes, grouped396+ /// Append a whole-file clip of `source` to the end of *every* lane, grouped
284 /// -- an import lands as one take. One history snapshot, so an import is one397 /// -- an import lands as one take. One history snapshot, so an import is one
285 /// undo step, and undoing it leaves the (harmless) source entry behind,398 /// undo step, and undoing it leaves the (harmless) source entry behind,
286 /// because indexes are forever. Refused for an unknown source index.399 /// because indexes are forever. Refused for an unknown source index.
@@ -297,8 +410,8 @@ impl Project {
297 source,410 source,
298 link: Some(self.new_link()),411 link: Some(self.new_link()),
299 };412 };
300- for lane in &mut self.lanes {413+ for data in &mut self.lanes {
301- lane.push(clip);414+ data.clips.push(clip);
302 }415 }
303 true416 true
304 }417 }
@@ -310,11 +423,31 @@ impl Project {
310 /// nothing plays refuse a future load. New indexes are assigned in order of423 /// nothing plays refuse a future load. New indexes are assigned in order of
311 /// first use -- video lane first, then audio -- so the same project always424 /// first use -- video lane first, then audio -- so the same project always
312 /// emits the same bytes.425 /// emits the same bytes.
313- pub fn without_orphan_sources(&self) -> (Vec<Source>, Vec<Clip>, Vec<Clip>) {426+ ///
427+ /// Refused, by name, for a timeline with more than one lane of a kind: the
428+ /// `.edith` format has one line keyword per kind, so writing a third lane
429+ /// would silently drop it. The model runs ahead of the format here on
430+ /// purpose -- the bump is its own slice -- and a refused save is the one
431+ /// answer that loses nothing.
432+ pub fn without_orphan_sources(&self) -> crate::Result<(Vec<Source>, Vec<Clip>, Vec<Clip>)> {
433+ for kind in [LaneKind::Video, LaneKind::Audio] {
434+ let n = self.lane_count(kind);
435+ if n > 1 {
436+ let name = match kind {
437+ LaneKind::Video => "video",
438+ LaneKind::Audio => "audio",
439+ };
440+ return Err(format!(
441+ "this timeline has {n} {name} lanes; a project file holds one of each -- \
442+ saving more than two lanes needs a newer format"
443+ )
444+ .into());
445+ }
446+ }
314 let mut moved = vec![None; self.sources.len()];447 let mut moved = vec![None; self.sources.len()];
315 let mut sources = Vec::new();448 let mut sources = Vec::new();
316 let mut lanes = self.lanes.clone();449 let mut lanes = self.lanes.clone();
317- for c in lanes.iter_mut().flatten() {450+ for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
318 let old = c.source;451 let old = c.source;
319 c.source = match moved[old] {452 c.source = match moved[old] {
320 Some(new) => new,453 Some(new) => new,
@@ -325,8 +458,14 @@ impl Project {
325 }458 }
326 };459 };
327 }460 }
328- let [video, audio] = lanes;461+ let (mut video, mut audio) = (Vec::new(), Vec::new());
329- (sources, video, audio)462+ for data in lanes {
463+ match data.kind {
464+ LaneKind::Video => video = data.clips,
465+ LaneKind::Audio => audio = data.clips,
466+ }
467+ }
468+ Ok((sources, video, audio))
330 }469 }
331 470
332 /// Length of the timeline in frames: where the *last* lane runs out. A lane471 /// Length of the timeline in frames: where the *last* lane runs out. A lane
@@ -334,15 +473,15 @@ impl Project {
334 pub fn timeline_frames(&self) -> u32 {473 pub fn timeline_frames(&self) -> u32 {
335 self.lanes474 self.lanes
336 .iter()475 .iter()
337- .filter_map(|lane| lane.last().map(Clip::end))476+ .filter_map(|l| l.clips.last().map(Clip::end))
338 .max()477 .max()
339 .unwrap_or(0)478 .unwrap_or(0)
340 }479 }
341 480
342- /// `(timeline_start, len)` per video clip, in order -- what a UI lane needs481+ /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
343 /// to lay clips out. Gaps show up as the holes between consecutive entries.482 /// to lay clips out. Gaps show up as the holes between consecutive entries.
344 pub fn clip_spans(&self) -> Vec<(u32, u32)> {483 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
345- self.lane_spans(Lane::Video)484+ self.lane_spans(Lane::V1)
346 }485 }
347 486
348 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {487 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
@@ -361,9 +500,9 @@ impl Project {
361 ))500 ))
362 }501 }
363 502
364- /// [`map`](Project::map) on the video lane -- the mapping a decoder follows.503+ /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
365 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {504 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
366- self.map(Lane::Video, timeline_frame)505+ self.map(Lane::V1, timeline_frame)
367 }506 }
368 507
369 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering508 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
@@ -418,53 +557,40 @@ impl Project {
418 /// placement's own start, in a gap, and past the end -- all of which would557 /// placement's own start, in a gap, and past the end -- all of which would
419 /// produce an empty clip or nothing at all.558 /// produce an empty clip or nothing at all.
420 ///559 ///
421- /// The two lanes' halves share an id only where they are the *same* span:560+ /// Lanes' halves share an id only where they are the *same* span: the lanes
422- /// the lanes are edited apart, so the clip being cut here may start (or561+ /// are edited apart, so the clip being cut here may start (or end)
423- /// end) somewhere else in the other lane, and a group id whose two clips562+ /// somewhere else on another lane, and a group id whose clips disagree
424- /// disagree about their span is not one take (see [`links_are_consistent`],563+ /// about their span is not one take (see [`links_are_consistent`], which
425- /// which refuses to load one).564+ /// refuses to load one).
426 ///565 ///
427 /// Metadata only: no mapping changes, in any lane.566 /// Metadata only: no mapping changes, in any lane.
428 pub fn split(&mut self, timeline_frame: u32) -> bool {567 pub fn split(&mut self, timeline_frame: u32) -> bool {
429- let cut = Lane::ALL568+ let cut: Vec<Option<Clip>> = self
430- .map(|l| splittable(self.lane(l), timeline_frame).map(|idx| self.lane(l)[idx]));569+ .lanes
570+ .iter()
571+ .map(|l| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
572+ .collect();
431 if cut.iter().all(Option::is_none) {573 if cut.iter().all(Option::is_none) {
432 return false;574 return false;
433 }575 }
434 self.snapshot();576 self.snapshot();
435- let same = |f: fn(&Clip) -> u32| match cut {
436- [Some(a), Some(b)] => f(&a) == f(&b),
437- _ => false,
438- };
439- let (left, right) = (self.new_link(), self.new_link());
440 // Each side is its own question: two clips may start together and end577 // Each side is its own question: two clips may start together and end
441- // apart, and the halves that do line up stay one take.578+ // apart, and every lane whose halves do line up stays one take.
442- let ids = [579+ let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();
443- (left, right),580+ let ends: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.end())).collect();
444- (581+ let left = self.group_ids(&starts);
445- if same(|c| c.start) {582+ let right = self.group_ids(&ends);
446- left583+ for ((data, left), right) in self.lanes.iter_mut().zip(left).zip(right) {
447- } else {584+ let Some(idx) = splittable(&data.clips, timeline_frame) else {
448- self.new_link()
449- },
450- if same(Clip::end) {
451- right
452- } else {
453- self.new_link()
454- },
455- ),
456- ];
457- for (lane, (left, right)) in self.lanes.iter_mut().zip(ids) {
458- let Some(idx) = splittable(lane, timeline_frame) else {
459 continue;585 continue;
460 };586 };
461- let mut tail = lane[idx];587+ let mut tail = data.clips[idx];
462 tail.in_frame += timeline_frame - tail.start;588 tail.in_frame += timeline_frame - tail.start;
463 tail.start = timeline_frame;589 tail.start = timeline_frame;
464- tail.link = Some(right);590+ tail.link = right;
465- lane[idx].out_frame = tail.in_frame;591+ data.clips[idx].out_frame = tail.in_frame;
466- lane[idx].link = Some(left);592+ data.clips[idx].link = left;
467- lane.insert(idx + 1, tail);593+ data.clips.insert(idx + 1, tail);
468 }594 }
469 true595 true
470 }596 }
@@ -479,29 +605,26 @@ impl Project {
479 /// reason.605 /// reason.
480 pub fn regroup(&mut self, timeline_frame: u32) -> bool {606 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
481 // What each lane would end up covering, if it joins here at all.607 // What each lane would end up covering, if it joins here at all.
482- let joined = Lane::ALL.map(|l| {608+ let joined: Vec<Option<(u32, u32)>> = self
483- joinable(self.lane(l), timeline_frame)609+ .lanes
484- .map(|idx| (self.lane(l)[idx].start, self.lane(l)[idx + 1].end()))610+ .iter()
485- });611+ .map(|l| {
612+ joinable(&l.clips, timeline_frame)
613+ .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
614+ })
615+ .collect();
486 if joined.iter().all(Option::is_none) {616 if joined.iter().all(Option::is_none) {
487 return false;617 return false;
488 }618 }
489 self.snapshot();619 self.snapshot();
490- let link = self.new_link();620+ let ids = self.group_ids(&joined);
491- let ids = [621+ for (data, link) in self.lanes.iter_mut().zip(ids) {
492- link,622+ let Some(idx) = joinable(&data.clips, timeline_frame) else {
493- match joined {
494- [Some(a), Some(b)] if a == b => link,
495- _ => self.new_link(),
496- },
497- ];
498- for (lane, link) in self.lanes.iter_mut().zip(ids) {
499- let Some(idx) = joinable(lane, timeline_frame) else {
500 continue;623 continue;
501 };624 };
502- lane[idx].out_frame = lane[idx + 1].out_frame;625+ data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
503- lane[idx].link = Some(link);626+ data.clips[idx].link = link;
504- lane.remove(idx + 1);627+ data.clips.remove(idx + 1);
505 }628 }
506 true629 true
507 }630 }
@@ -518,10 +641,12 @@ impl Project {
518 /// back over the clip it came from -- would put that id on two clips of one641 /// back over the clip it came from -- would put that id on two clips of one
519 /// lane, which is what a link may never mean (see [`links_are_consistent`]).642 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
520 /// `None` rather than a fresh id because a one-lane placement has nothing on643 /// `None` rather than a fresh id because a one-lane placement has nothing on
521- /// the other lane to be grouped *with*; [`Project::regroup`] is how clips644+ /// another lane to be grouped *with*; [`Project::regroup`] is how clips
522 /// become a group again.645 /// become a group again.
646+ ///
647+ /// Refused for an empty `clip` and for a lane that is not there.
523 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {648 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
524- if clip.out_frame <= clip.in_frame {649+ if clip.out_frame <= clip.in_frame || self.index(lane).is_none() {
525 return false;650 return false;
526 }651 }
527 self.snapshot();652 self.snapshot();
@@ -530,15 +655,15 @@ impl Project {
530 link: None,655 link: None,
531 ..clip656 ..clip
532 };657 };
533- let lane = &mut self.lanes[lane.index()];658+ let clips = self.lane_mut(lane).expect("checked above");
534- clear(lane, clip.start, clip.end());659+ clear(clips, clip.start, clip.end());
535- let idx = lane.partition_point(|c| c.start < clip.start);660+ let idx = clips.partition_point(|c| c.start < clip.start);
536- lane.insert(idx, clip);661+ clips.insert(idx, clip);
537- debug_assert!(sorted_disjoint(lane));662+ debug_assert!(sorted_disjoint(clips));
538 true663 true
539 }664 }
540 665
541- /// Insert `clip` into *both* lanes at `timeline_frame` as one new group,666+ /// Insert `clip` into *every* lane at `timeline_frame` as one new group,
542 /// pushing everything from there on later by its length -- the grouped,667 /// pushing everything from there on later by its length -- the grouped,
543 /// rippling paste a clipboard does. Mid-clip the clip it lands in is split668 /// rippling paste a clipboard does. Mid-clip the clip it lands in is split
544 /// around it; at or past the end of the timeline it is appended, because a669 /// around it; at or past the end of the timeline it is appended, because a
@@ -560,33 +685,34 @@ impl Project {
560 link: Some(self.new_link()),685 link: Some(self.new_link()),
561 ..clip686 ..clip
562 };687 };
563- for lane in &mut self.lanes {688+ for data in &mut self.lanes {
564- open_room(lane, at, clip.len());689+ open_room(&mut data.clips, at, clip.len());
565- let idx = lane.partition_point(|c| c.start < at);690+ let idx = data.clips.partition_point(|c| c.start < at);
566- lane.insert(idx, clip);691+ data.clips.insert(idx, clip);
567- debug_assert!(sorted_disjoint(lane));692+ debug_assert!(sorted_disjoint(&data.clips));
568 }693 }
569 true694 true
570 }695 }
571 696
572 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or697 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
573- /// silence, and nothing else moves. Refused for an out-of-range index and698+ /// silence, and nothing else moves. Refused for an out-of-range index (which
574- /// for the lift that would leave *both* lanes empty -- an empty timeline is699+ /// a lane that is not there always is) and for the lift that would leave
575- /// the front-end's state, not a project's (see the never-empty invariant).700+ /// *every* lane empty -- an empty timeline is the front-end's state, not a
701+ /// project's (see the never-empty invariant).
576 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {702 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
577- let placed: usize = self.lanes.iter().map(Vec::len).sum();703+ let placed: usize = self.lanes.iter().map(|l| l.clips.len()).sum();
578 if idx >= self.lane(lane).len() || placed == 1 {704 if idx >= self.lane(lane).len() || placed == 1 {
579 return false;705 return false;
580 }706 }
581 self.snapshot();707 self.snapshot();
582- self.lanes[lane.index()].remove(idx);708+ self.lane_mut(lane).expect("checked above").remove(idx);
583 true709 true
584 }710 }
585 711
586 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close712 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
587 /// the hole: everything after slides back by `len`. The rippling delete --713 /// the hole: everything after slides back by `len`. The rippling delete --
588 /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an714 /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an
589- /// empty range and when it would leave both lanes empty.715+ /// empty range and when it would leave every lane empty.
590 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {716 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
591 if len == 0 {717 if len == 0 {
592 return false;718 return false;
@@ -594,8 +720,9 @@ impl Project {
594 let survivors: usize = self720 let survivors: usize = self
595 .lanes721 .lanes
596 .iter()722 .iter()
597- .map(|lane| {723+ .map(|l| {
598- lane.iter()724+ l.clips
725+ .iter()
599 .filter(|c| c.start < at || c.end() > at + len)726 .filter(|c| c.start < at || c.end() > at + len)
600 .count()727 .count()
601 })728 })
@@ -604,17 +731,17 @@ impl Project {
604 return false;731 return false;
605 }732 }
606 self.snapshot();733 self.snapshot();
607- for lane in &mut self.lanes {734+ for data in &mut self.lanes {
608- clear(lane, at, at + len);735+ clear(&mut data.clips, at, at + len);
609- for c in lane.iter_mut().filter(|c| c.start >= at) {736+ for c in data.clips.iter_mut().filter(|c| c.start >= at) {
610 c.start -= len;737 c.start -= len;
611 }738 }
612- debug_assert!(sorted_disjoint(lane));739+ debug_assert!(sorted_disjoint(&data.clips));
613 }740 }
614 true741 true
615 }742 }
616 743
617- /// Remove the video clip at `idx` and everything under it, closing the gap744+ /// Remove the `V1` clip at `idx` and everything under it, closing the gap
618 /// -- the whole-group delete a single-lane front-end means. `false` for a745 /// -- the whole-group delete a single-lane front-end means. `false` for a
619 /// bad index. Changes the mapping: the caller must reseek.746 /// bad index. Changes the mapping: the caller must reseek.
620 pub fn delete(&mut self, idx: usize) -> bool {747 pub fn delete(&mut self, idx: usize) -> bool {
@@ -624,8 +751,8 @@ impl Project {
624 self.ripple_delete(clip.start, clip.len())751 self.ripple_delete(clip.start, clip.len())
625 }752 }
626 753
627- /// Restore both lanes from before the last successful edit. `false` when754+ /// Restore every lane from before the last successful edit -- the clips and
628- /// there is nothing left to undo.755+ /// the lane list both. `false` when there is nothing left to undo.
629 pub fn undo(&mut self) -> bool {756 pub fn undo(&mut self) -> bool {
630 match self.history.pop() {757 match self.history.pop() {
631 Some(prev) => {758 Some(prev) => {
@@ -638,7 +765,7 @@ impl Project {
638 765
639 /// Half-open `(source, start, end)` segments in *source* seconds, from766 /// Half-open `(source, start, end)` segments in *source* seconds, from
640 /// `timeline_frame` to the end of the timeline -- the play list for the767 /// `timeline_frame` to the end of the timeline -- the play list for the
641- /// audio worker, read off the **audio** lane. A `None` source is a gap: the768+ /// audio worker, read off **`A1`**. A `None` source is a gap: the
642 /// worker synthesises that many seconds of silence, which is what keeps the769 /// worker synthesises that many seconds of silence, which is what keeps the
643 /// audio master clock counting across a hole instead of stalling on it.770 /// audio master clock counting across a hole instead of stalling on it.
644 /// The first entry is partial when the position is mid-clip. Empty when the771 /// The first entry is partial when the position is mid-clip. Empty when the
@@ -647,7 +774,7 @@ impl Project {
647 if !(fps.is_finite() && fps > 0.0) {774 if !(fps.is_finite() && fps > 0.0) {
648 return Vec::new();775 return Vec::new();
649 }776 }
650- self.spans_from(Lane::Audio, timeline_frame)777+ self.spans_from(Lane::A1, timeline_frame)
651 .iter()778 .iter()
652 .map(|span| match span.from {779 .map(|span| match span.from {
653 // A clip's window is in *source* seconds: where in the file it780 // A clip's window is in *source* seconds: where in the file it
@@ -674,6 +801,51 @@ impl Project {
674 self.next_link = self.next_link.saturating_add(1);801 self.next_link = self.next_link.saturating_add(1);
675 id802 id
676 }803 }
804+
805+ /// One fresh group id per *distinct* key, in lane order, and `None` where a
806+ /// lane has no key -- how [`split`](Project::split) and
807+ /// [`regroup`](Project::regroup) hand out ids across however many lanes.
808+ /// Lanes sharing a key end up sharing an id, which is exactly the rule
809+ /// [`links_are_consistent`] enforces: one id, one span.
810+ fn group_ids<K: PartialEq>(&mut self, keys: &[Option<K>]) -> Vec<Option<u32>> {
811+ // Linear, over a handful of lanes: a hash of a lane list would cost
812+ // more than it saves and would not be deterministic for free.
813+ let mut seen: Vec<(&K, u32)> = Vec::new();
814+ let mut out = Vec::with_capacity(keys.len());
815+ for key in keys {
816+ out.push(
817+ key.as_ref()
818+ .map(|k| match seen.iter().find(|(other, _)| *other == k) {
819+ Some(&(_, id)) => id,
820+ None => {
821+ let id = self.new_link();
822+ seen.push((k, id));
823+ id
824+ }
825+ }),
826+ );
827+ }
828+ out
829+ }
830+}
831+
832+/// The handle of every lane, in storage order -- the one definition of what
833+/// [`Lane::ord`] counts.
834+fn handles(lanes: &[LaneData]) -> Vec<Lane> {
835+ let (mut video, mut audio) = (0, 0);
836+ lanes
837+ .iter()
838+ .map(|l| match l.kind {
839+ LaneKind::Video => {
840+ video += 1;
841+ Lane::new(LaneKind::Video, video - 1)
842+ }
843+ LaneKind::Audio => {
844+ audio += 1;
845+ Lane::new(LaneKind::Audio, audio - 1)
846+ }
847+ })
848+ .collect()
677 }849 }
678 850
679 /// Index of the clip covering `frame`, or `None` for a gap or past the end.851 /// Index of the clip covering `frame`, or `None` for a gap or past the end.
@@ -709,39 +881,53 @@ fn sorted_disjoint(clips: &[Clip]) -> bool {
709 && clips.windows(2).all(|w| w[0].end() <= w[1].start)881 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
710 }882 }
711 883
712-/// The grouping invariant, checked in release at [`Project::from_parts`]: a link884+/// The grouping invariant, checked in release at [`Project::from_parts`] and
713-/// id names **at most one** clip per lane, and when it names one in each, the two885+/// asserted by the tests after every edit: a link id names **at most one** clip
714-/// cover the same timeline span -- that is all "these move together" can mean.886+/// per lane, and every clip carrying it covers the same timeline span -- that is
887+/// all "these move together" can mean.
888+///
889+/// Deliberately *not* a pairing of two lanes: with N lanes a take may run on
890+/// `V1`, `V2` and `A1` at once, and the rule that makes an id meaningful is span
891+/// identity, not which lane (or which `ord`) the partner sits on. Two lanes are
892+/// the case where it reads as "the picture and its sound".
715 ///893 ///
716-/// A link the *other* lane does not carry is legal and is not an error: lifting894+/// A link no other lane carries is legal and is not an error: lifting one half
717-/// one half of a group ([`Project::lift`]) leaves exactly that, and a save of895+/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
718-/// that timeline has to load again.896+/// timeline has to load again.
719-fn links_are_consistent(lanes: &[Vec<Clip>; 2]) -> crate::Result<()> {897+fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
720- let find = |lane: &Vec<Clip>, id: u32| lane.iter().find(|c| c.link == Some(id)).copied();898+ let handles = handles(lanes);
721- for (lane, name) in lanes.iter().zip(["video", "audio"]) {899+ for (data, lane) in lanes.iter().zip(&handles) {
722- for (i, c) in lane.iter().enumerate() {900+ for (i, c) in data.clips.iter().enumerate() {
723 let Some(id) = c.link else { continue };901 let Some(id) = c.link else { continue };
724- if lane[..i].iter().any(|prev| prev.link == Some(id)) {902+ if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
725- return Err(format!("link {id} names two clips in the {name} lane").into());903+ return Err(
904+ format!("link {id} names two clips in the {} lane", lane.label()).into(),
905+ );
726 }906 }
727 }907 }
728 }908 }
729- for a in lanes[0].iter().filter(|c| c.link.is_some()) {909+ // First lane to carry an id fixes the span every other lane must agree on.
730- let id = a.link.expect("filtered");910+ let mut seen: Vec<(u32, Lane, u32, u32)> = Vec::new();
731- let Some(b) = find(&lanes[1], id) else {911+ for (data, &lane) in lanes.iter().zip(&handles) {
732- continue;912+ for c in &data.clips {
733- };913+ let Some(id) = c.link else { continue };
734- if (a.start, a.end()) != (b.start, b.end()) {914+ match seen.iter().find(|(other, ..)| *other == id) {
915+ Some(&(_, first, start, end)) => {
916+ if (start, end) != (c.start, c.end()) {
735 return Err(format!(917 return Err(format!(
736- "link {id} covers [{}, {}) in video and [{}, {}) in audio",918+ "link {id} covers [{start}, {end}) in {} and [{}, {}) in {}",
737- a.start,919+ first.label(),
738- a.end(),920+ c.start,
739- b.start,921+ c.end(),
740- b.end()922+ lane.label()
741 )923 )
742 .into());924 .into());
743 }925 }
744 }926 }
927+ None => seen.push((id, lane, c.start, c.end())),
928+ }
929+ }
930+ }
745 Ok(())931 Ok(())
746 }932 }
747 933
@@ -829,22 +1015,30 @@ mod tests {
829 }1015 }
830 }1016 }
831 1017
832- /// Both lanes with their group ids blanked, for comparing shape.1018+ /// Every lane with its group ids blanked, for comparing shape.
833- fn shape(p: &Project) -> [Vec<Clip>; 2] {1019+ fn shape(p: &Project) -> Vec<Vec<Clip>> {
834- Lane::ALL.map(|l| {1020+ p.lanes()
1021+ .into_iter()
1022+ .map(|l| {
835 p.lane(l)1023 p.lane(l)
836 .iter()1024 .iter()
837 .map(|c| Clip { link: None, ..*c })1025 .map(|c| Clip { link: None, ..*c })
838 .collect()1026 .collect()
839 })1027 })
1028+ .collect()
840 }1029 }
841 1030
842 /// The *source frame* every timeline frame reads, per lane -- the traversal1031 /// The *source frame* every timeline frame reads, per lane -- the traversal
843 /// a player performs. Deliberately not the clip index: a split changes which1032 /// a player performs. Deliberately not the clip index: a split changes which
844 /// clip a frame belongs to, and nothing else.1033 /// clip a frame belongs to, and nothing else.
845- fn traversal(p: &Project) -> Vec<[Option<u32>; 2]> {1034+ fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
846 (0..p.timeline_frames() + 2)1035 (0..p.timeline_frames() + 2)
847- .map(|f| Lane::ALL.map(|l| p.map(l, f).map(|(_, source)| source)))1036+ .map(|f| {
1037+ p.lanes()
1038+ .into_iter()
1039+ .map(|l| p.map(l, f).map(|(_, source)| source))
1040+ .collect()
1041+ })
848 .collect()1042 .collect()
849 }1043 }
850 1044
@@ -868,11 +1062,11 @@ mod tests {
868 fn single_is_the_whole_file_on_both_lanes() {1062 fn single_is_the_whole_file_on_both_lanes() {
869 let p = Project::single(FILE, 150);1063 let p = Project::single(FILE, 150);
870 assert_eq!(p.clips().len(), 1);1064 assert_eq!(p.clips().len(), 1);
871- assert_eq!(p.lane(Lane::Audio).len(), 1);1065+ assert_eq!(p.lane(Lane::A1).len(), 1);
872 assert_eq!(p.timeline_frames(), 150);1066 assert_eq!(p.timeline_frames(), 150);
873 assert_eq!(p.clip_spans(), vec![(0, 150)]);1067 assert_eq!(p.clip_spans(), vec![(0, 150)]);
874 // grouped: video and audio carry the same link1068 // grouped: video and audio carry the same link
875- assert_eq!(p.clips()[0].link, p.lane(Lane::Audio)[0].link);1069+ assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
876 assert!(p.clips()[0].link.is_some());1070 assert!(p.clips()[0].link.is_some());
877 // degenerate mapping: timeline == source1071 // degenerate mapping: timeline == source
878 assert_eq!(p.map_timeline(0), Some((0, 0)));1072 assert_eq!(p.map_timeline(0), Some((0, 0)));
@@ -889,11 +1083,11 @@ mod tests {
889 let before_shape = shape(&p);1083 let before_shape = shape(&p);
890 1084
891 assert!(p.split(4));1085 assert!(p.split(4));
892- for l in Lane::ALL {1086+ for l in p.lanes() {
893- assert_eq!(p.lane(l).len(), 2, "{l:?} split");1087+ assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
894 }1088 }
895 // The two sides are two groups, one per side, matching across the lanes.1089 // The two sides are two groups, one per side, matching across the lanes.
896- let (v, a) = (p.lane(Lane::Video), p.lane(Lane::Audio));1090+ let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
897 assert_eq!(v[0].link, a[0].link);1091 assert_eq!(v[0].link, a[0].link);
898 assert_eq!(v[1].link, a[1].link);1092 assert_eq!(v[1].link, a[1].link);
899 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");1093 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
@@ -904,8 +1098,8 @@ mod tests {
904 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");1098 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
905 assert_eq!(traversal(&p), before);1099 assert_eq!(traversal(&p), before);
906 assert_eq!(1100 assert_eq!(
907- p.lane(Lane::Video)[0].link,1101+ p.lane(Lane::V1)[0].link,
908- p.lane(Lane::Audio)[0].link,1102+ p.lane(Lane::A1)[0].link,
909 "and the rejoined clip is one group again"1103 "and the rejoined clip is one group again"
910 );1104 );
911 }1105 }
@@ -926,8 +1120,8 @@ mod tests {
926 1120
927 // ...and a frame that is a gap in both lanes has nothing to split.1121 // ...and a frame that is a gap in both lanes has nothing to split.
928 let mut p = three();1122 let mut p = three();
929- assert!(p.lift(Lane::Video, 1));1123+ assert!(p.lift(Lane::V1, 1));
930- assert!(p.lift(Lane::Audio, 1));1124+ assert!(p.lift(Lane::A1, 1));
931 assert!(!p.split(4), "a gap is not a clip");1125 assert!(!p.split(4), "a gap is not a clip");
932 }1126 }
933 1127
@@ -940,11 +1134,11 @@ mod tests {
940 // A boundary with a gap on one side, and one where the sources do not1134 // A boundary with a gap on one side, and one where the sources do not
941 // meet, are both refused.1135 // meet, are both refused.
942 let mut p = three();1136 let mut p = three();
943- assert!(p.lift(Lane::Video, 1));1137+ assert!(p.lift(Lane::V1, 1));
944- assert!(p.lift(Lane::Audio, 1));1138+ assert!(p.lift(Lane::A1, 1));
945 assert!(!p.regroup(3), "nothing starts at 3 any more");1139 assert!(!p.regroup(3), "nothing starts at 3 any more");
946 let mut p = three();1140 let mut p = three();
947- for l in Lane::ALL {1141+ for l in p.lanes() {
948 assert!(p.place(l, 3, clip(0, 100, 102, 0)));1142 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
949 }1143 }
950 assert!(!p.regroup(3), "source 100 does not follow source 3");1144 assert!(!p.regroup(3), "source 100 does not follow source 3");
@@ -975,14 +1169,14 @@ mod tests {
975 assert_eq!(p.map_timeline(9), None);1169 assert_eq!(p.map_timeline(9), None);
976 // A span is the rest of the clip from where it was asked about.1170 // A span is the rest of the clip from where it was asked about.
977 assert_eq!(1171 assert_eq!(
978- p.span_at(Lane::Video, 6),1172+ p.span_at(Lane::V1, 6),
979 Some(Span {1173 Some(Span {
980 start: 6,1174 start: 6,
981 len: 3,1175 len: 3,
982 from: Some((0, 6))1176 from: Some((0, 6))
983 })1177 })
984 );1178 );
985- assert_eq!(p.span_at(Lane::Video, 9), None);1179+ assert_eq!(p.span_at(Lane::V1, 9), None);
986 }1180 }
987 1181
988 /// The clip a copy would hand back: source `[100, 102)`, unrelated to1182 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
@@ -1070,7 +1264,7 @@ mod tests {
1070 assert!(p.delete(1));1264 assert!(p.delete(1));
1071 assert_eq!(p.timeline_frames(), 7);1265 assert_eq!(p.timeline_frames(), 7);
1072 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);1266 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
1073- assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 4)]);1267+ assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
1074 // timeline 3 used to be source 3; the gap closed so it is source 5 now1268 // timeline 3 used to be source 3; the gap closed so it is source 5 now
1075 assert_eq!(p.map_timeline(3), Some((1, 5)));1269 assert_eq!(p.map_timeline(3), Some((1, 5)));
1076 assert_eq!(p.map_timeline(6), Some((1, 8)));1270 assert_eq!(p.map_timeline(6), Some((1, 8)));
@@ -1100,32 +1294,32 @@ mod tests {
1100 fn a_lift_leaves_a_gap_and_moves_nothing() {1294 fn a_lift_leaves_a_gap_and_moves_nothing() {
1101 let mut p = three();1295 let mut p = three();
1102 let video_before = shape(&p)[0].clone();1296 let video_before = shape(&p)[0].clone();
1103- assert!(p.lift(Lane::Audio, 1));1297+ assert!(p.lift(Lane::A1, 1));
1104 assert_eq!(shape(&p)[0], video_before, "the picture never moved");1298 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
1105 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");1299 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
1106- assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (5, 4)]);1300+ assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
1107 // The hole is a gap: mapped as nothing, spanned as a gap of its length.1301 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
1108- assert_eq!(p.map(Lane::Audio, 4), None);1302+ assert_eq!(p.map(Lane::A1, 4), None);
1109 assert_eq!(1303 assert_eq!(
1110- p.span_at(Lane::Audio, 3),1304+ p.span_at(Lane::A1, 3),
1111 Some(Span {1305 Some(Span {
1112 start: 3,1306 start: 3,
1113 len: 2,1307 len: 2,
1114 from: None1308 from: None
1115 })1309 })
1116 );1310 );
1117- assert_eq!(p.map(Lane::Video, 4), Some((1, 4)), "video plays on");1311+ assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
1118 assert!(p.undo());1312 assert!(p.undo());
1119- assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 2), (5, 4)]);1313+ assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
1120 }1314 }
1121 1315
1122 #[test]1316 #[test]
1123 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {1317 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
1124 let mut p = three();1318 let mut p = three();
1125- assert!(p.lift(Lane::Audio, 2));1319+ assert!(p.lift(Lane::A1, 2));
1126 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");1320 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
1127 assert_eq!(1321 assert_eq!(
1128- p.span_at(Lane::Audio, 5),1322+ p.span_at(Lane::A1, 5),
1129 Some(Span {1323 Some(Span {
1130 start: 5,1324 start: 5,
1131 len: 4,1325 len: 4,
@@ -1133,11 +1327,11 @@ mod tests {
1133 }),1327 }),
1134 "the audio lane holds silence to the end of the picture"1328 "the audio lane holds silence to the end of the picture"
1135 );1329 );
1136- assert_eq!(p.span_at(Lane::Audio, 9), None);1330+ assert_eq!(p.span_at(Lane::A1, 9), None);
1137 // Every lane covers the timeline exactly, gaps included.1331 // Every lane covers the timeline exactly, gaps included.
1138- for l in Lane::ALL {1332+ for l in p.lanes() {
1139 let spans = p.spans_from(l, 0);1333 let spans = p.spans_from(l, 0);
1140- assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{l:?}");1334+ assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
1141 assert_eq!(spans[0].start, 0);1335 assert_eq!(spans[0].start, 0);
1142 }1336 }
1143 }1337 }
@@ -1145,9 +1339,9 @@ mod tests {
1145 #[test]1339 #[test]
1146 fn the_last_clip_of_the_last_lane_cannot_be_lifted() {1340 fn the_last_clip_of_the_last_lane_cannot_be_lifted() {
1147 let mut p = Project::single(FILE, 9);1341 let mut p = Project::single(FILE, 9);
1148- assert!(p.lift(Lane::Audio, 0), "a silent timeline is fine");1342+ assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
1149- assert!(!p.lift(Lane::Video, 0), "an empty one is not");1343+ assert!(!p.lift(Lane::V1, 0), "an empty one is not");
1150- assert!(!p.lift(Lane::Audio, 0), "index past the end");1344+ assert!(!p.lift(Lane::A1, 0), "index past the end");
1151 assert_eq!(p.timeline_frames(), 9);1345 assert_eq!(p.timeline_frames(), 9);
1152 }1346 }
1153 1347
@@ -1157,7 +1351,7 @@ mod tests {
1157 let audio_before = shape(&p)[1].clone();1351 let audio_before = shape(&p)[1].clone();
1158 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second1352 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
1159 // is trimmed, nothing shifts.1353 // is trimmed, nothing shifts.
1160- assert!(p.place(Lane::Video, 4, clip(0, 100, 102, 0)));1354+ assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
1161 assert_eq!(1355 assert_eq!(
1162 shape(&p)[0],1356 shape(&p)[0],
1163 vec![1357 vec![
@@ -1172,23 +1366,23 @@ mod tests {
1172 1366
1173 // Placed inside one clip, it splits it in two.1367 // Placed inside one clip, it splits it in two.
1174 let mut p = Project::single(FILE, 9);1368 let mut p = Project::single(FILE, 9);
1175- assert!(p.place(Lane::Video, 4, clip(0, 100, 101, 0)));1369+ assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
1176 assert_eq!(1370 assert_eq!(
1177 shape(&p)[0],1371 shape(&p)[0],
1178 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]1372 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
1179 );1373 );
1180 // ...and placed past the end it makes a gap, which is the whole point.1374 // ...and placed past the end it makes a gap, which is the whole point.
1181- assert!(p.place(Lane::Video, 20, clip(0, 100, 102, 0)));1375+ assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
1182 assert_eq!(p.timeline_frames(), 22);1376 assert_eq!(p.timeline_frames(), 22);
1183 assert_eq!(1377 assert_eq!(
1184- p.span_at(Lane::Video, 9),1378+ p.span_at(Lane::V1, 9),
1185 Some(Span {1379 Some(Span {
1186 start: 9,1380 start: 9,
1187 len: 11,1381 len: 11,
1188 from: None1382 from: None
1189 })1383 })
1190 );1384 );
1191- assert!(!p.place(Lane::Video, 0, clip(0, 7, 7, 0)), "empty clip");1385+ assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
1192 }1386 }
1193 1387
1194 #[test]1388 #[test]
@@ -1266,7 +1460,7 @@ mod tests {
1266 #[test]1460 #[test]
1267 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {1461 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
1268 let mut p = three();1462 let mut p = three();
1269- assert!(p.lift(Lane::Audio, 1)); // silence over timeline [3, 5)1463+ assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
1270 assert_eq!(1464 assert_eq!(
1271 p.segments_from(0, FPS),1465 p.segments_from(0, FPS),
1272 vec![1466 vec![
@@ -1285,8 +1479,8 @@ mod tests {
1285 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]1479 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
1286 );1480 );
1287 // ...and a lane that is nothing but gap is a run of silence.1481 // ...and a lane that is nothing but gap is a run of silence.
1288- assert!(p.lift(Lane::Audio, 0));1482+ assert!(p.lift(Lane::A1, 0));
1289- assert!(p.lift(Lane::Audio, 0));1483+ assert!(p.lift(Lane::A1, 0));
1290 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);1484 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
1291 }1485 }
1292 1486
@@ -1410,10 +1604,10 @@ mod tests {
1410 // Import a second file, undo it: source 1 is now an orphan.1604 // Import a second file, undo it: source 1 is now an orphan.
1411 let mut p = two_sources();1605 let mut p = two_sources();
1412 assert!(p.undo());1606 assert!(p.undo());
1413- let (sources, video, audio) = p.without_orphan_sources();1607+ let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");
1414 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");1608 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
1415 assert_eq!(video, three().clips(), "the clips are untouched");1609 assert_eq!(video, three().clips(), "the clips are untouched");
1416- assert_eq!(audio, three().lane(Lane::Audio));1610+ assert_eq!(audio, three().lane(Lane::A1));
1417 1611
1418 // Three sources where only the middle one is orphaned: the survivors1612 // Three sources where only the middle one is orphaned: the survivors
1419 // renumber, and the clips follow.1613 // renumber, and the clips follow.
@@ -1421,7 +1615,7 @@ mod tests {
1421 assert_eq!(p.import(FILE2, 0), 1);1615 assert_eq!(p.import(FILE2, 0), 1);
1422 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);1616 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
1423 assert!(p.append_clip(2, 4));1617 assert!(p.append_clip(2, 4));
1424- let (sources, video, audio) = p.without_orphan_sources();1618+ let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");
1425 assert_eq!(1619 assert_eq!(
1426 sources,1620 sources,
1427 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]1621 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
@@ -1435,7 +1629,7 @@ mod tests {
1435 1629
1436 #[test]1630 #[test]
1437 fn from_parts_has_no_history_and_checks_the_invariants() {1631 fn from_parts_has_no_history_and_checks_the_invariants() {
1438- let (sources, video, audio) = three().without_orphan_sources();1632+ let (sources, video, audio) = three().without_orphan_sources().expect("two lanes");
1439 let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone())1633 let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone())
1440 .expect("valid parts");1634 .expect("valid parts");
1441 assert_eq!(p.clips(), three().clips());1635 assert_eq!(p.clips(), three().clips());
@@ -1467,9 +1661,13 @@ mod tests {
1467 }1661 }
1468 1662
1469 /// The grouping rules, at the untrusted door and after every edit that can1663 /// The grouping rules, at the untrusted door and after every edit that can
1470- /// touch a link. A link id is at most one clip per lane and, when both lanes1664+ /// touch a link. A link id is at most one clip per lane and, wherever it is
1471- /// carry it, one span -- and no sequence of edits may produce otherwise,1665+ /// carried, one span -- and no sequence of edits may produce otherwise,
1472 /// because what an edit produces is what a save writes and a load reads.1666 /// because what an edit produces is what a save writes and a load reads.
1667+ ///
1668+ /// Amended for the lane model: the two errors name their lane `V1`/`A1`
1669+ /// rather than "video"/"audio", because with N lanes "the video lane" is no
1670+ /// longer a lane. Same causes, same door, same claim.
1473 #[test]1671 #[test]
1474 fn a_link_id_is_never_two_clips_of_one_lane() {1672 fn a_link_id_is_never_two_clips_of_one_lane() {
1475 let sources = vec![Source::new(FILE, 0)];1673 let sources = vec![Source::new(FILE, 0)];
@@ -1489,18 +1687,18 @@ mod tests {
1489 };1687 };
1490 assert!(1688 assert!(
1491 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())1689 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
1492- .contains("link 7 names two clips in the video lane"),1690+ .contains("link 7 names two clips in the V1 lane"),
1493 "a duplicate id inside one lane is refused by name"1691 "a duplicate id inside one lane is refused by name"
1494 );1692 );
1495 assert!(1693 assert!(
1496 err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])1694 err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])
1497- .contains("link 2 covers [0, 5) in video and [0, 3) in audio"),1695+ .contains("link 2 covers [0, 5) in V1 and [0, 3) in A1"),
1498 "a pair that does not cover one span is refused by name"1696 "a pair that does not cover one span is refused by name"
1499 );1697 );
1500 // A one-sided link is *not* an error: it is what a lift leaves behind.1698 // A one-sided link is *not* an error: it is what a lift leaves behind.
1501 let mut p = Project::single(FILE, 9);1699 let mut p = Project::single(FILE, 9);
1502- assert!(p.lift(Lane::Audio, 0));1700+ assert!(p.lift(Lane::A1, 0));
1503- let (sources, video, audio) = p.clone().without_orphan_sources();1701+ let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");
1504 assert!(1702 assert!(
1505 Project::from_parts(sources, video, audio).is_ok(),1703 Project::from_parts(sources, video, audio).is_ok(),
1506 "a lifted lane's project has to load again"1704 "a lifted lane's project has to load again"
@@ -1508,8 +1706,11 @@ mod tests {
1508 1706
1509 // The edits: nothing below may break either rule.1707 // The edits: nothing below may break either rule.
1510 let consistent = |p: &Project, what: &str| {1708 let consistent = |p: &Project, what: &str| {
1511- let lanes = Lane::ALL.map(|l| p.lane(l).to_vec());1709+ assert!(
1512- assert!(links_are_consistent(&lanes).is_ok(), "{what}: {lanes:?}");1710+ links_are_consistent(&p.lanes).is_ok(),
1711+ "{what}: {:?}",
1712+ p.lanes
1713+ );
1513 };1714 };
1514 let mut p = three();1715 let mut p = three();
1515 let copied = p.clips()[0];1716 let copied = p.clips()[0];
@@ -1517,19 +1718,16 @@ mod tests {
1517 copied.link.is_some(),1718 copied.link.is_some(),
1518 "the clipboard clip carries its group"1719 "the clipboard clip carries its group"
1519 );1720 );
1520- assert!(p.lift(Lane::Video, 0));1721+ assert!(p.lift(Lane::V1, 0));
1521- assert!(p.place(Lane::Video, 0, copied));1722+ assert!(p.place(Lane::V1, 0, copied));
1522- assert!(p.place(Lane::Video, 20, copied), "and again, further out");1723+ assert!(p.place(Lane::V1, 20, copied), "and again, further out");
1523 assert_eq!(1724 assert_eq!(
1524 p.clips().iter().filter(|c| c.link == copied.link).count(),1725 p.clips().iter().filter(|c| c.link == copied.link).count(),
1525 0,1726 0,
1526 "a placement belongs to no group, so it cannot duplicate one"1727 "a placement belongs to no group, so it cannot duplicate one"
1527 );1728 );
1528 consistent(&p, "lift + place twice");1729 consistent(&p, "lift + place twice");
1529- assert!(1730+ assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
1530- p.place(Lane::Audio, 4, copied),
1531- "over a linked clip's middle"
1532- );
1533 consistent(&p, "place through a grouped clip");1731 consistent(&p, "place through a grouped clip");
1534 assert!(p.paste(6, copied), "a rippling paste through another");1732 assert!(p.paste(6, copied), "a rippling paste through another");
1535 consistent(&p, "paste");1733 consistent(&p, "paste");
@@ -1548,13 +1746,13 @@ mod tests {
1548 #[test]1746 #[test]
1549 fn every_reachable_state_reloads() {1747 fn every_reachable_state_reloads() {
1550 let mut p = Project::single(FILE, 150);1748 let mut p = Project::single(FILE, 150);
1551- assert!(p.place(Lane::Audio, 3, clip(0, 0, 50, 0)));1749+ assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
1552 assert!(p.split(10), "the lanes are cut apart at 10");1750 assert!(p.split(10), "the lanes are cut apart at 10");
1553 reloads(&p, "place on one lane, then split");1751 reloads(&p, "place on one lane, then split");
1554 1752
1555 let mut p = Project::single(FILE, 150);1753 let mut p = Project::single(FILE, 150);
1556 assert!(p.split(30));1754 assert!(p.split(30));
1557- assert!(p.lift(Lane::Video, 0), "the picture goes, the sound stays");1755+ assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
1558 assert!(p.regroup(30), "only the audio lane can rejoin");1756 assert!(p.regroup(30), "only the audio lane can rejoin");
1559 assert!(p.split(60));1757 assert!(p.split(60));
1560 reloads(&p, "lift, regroup one lane, split");1758 reloads(&p, "lift, regroup one lane, split");
@@ -1571,7 +1769,7 @@ mod tests {
1571 &p,1769 &p,
1572 "a second audio stream of the same file, placed and split",1770 "a second audio stream of the same file, placed and split",
1573 );1771 );
1574- let (sources, ..) = p.without_orphan_sources();1772+ let (sources, ..) = p.without_orphan_sources().expect("two lanes");
1575 assert_eq!(1773 assert_eq!(
1576 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),1774 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
1577 [0, 1],1775 [0, 1],
@@ -1599,18 +1797,10 @@ mod tests {
1599 // A clipboard copy carries the group id of the take it came from1797 // A clipboard copy carries the group id of the take it came from
1600 // -- the input that made a placement duplicate an id.1798 // -- the input that made a placement duplicate an id.
1601 let copied = *p1799 let copied = *p
1602- .lane(if next(2) == 0 {1800+ .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
1603- Lane::Video
1604- } else {
1605- Lane::Audio
1606- })
1607 .get(next(4) as usize)1801 .get(next(4) as usize)
1608 .unwrap_or(&clip(0, 0, 5, 0));1802 .unwrap_or(&clip(0, 0, 5, 0));
1609- let lane = if next(2) == 0 {1803+ let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
1610- Lane::Video
1611- } else {
1612- Lane::Audio
1613- };
1614 let idx = next(4) as usize;1804 let idx = next(4) as usize;
1615 let _ = match next(9) {1805 let _ = match next(9) {
1616 0 => p.split(frame),1806 0 => p.split(frame),
@@ -1631,9 +1821,311 @@ mod tests {
1631 /// The save/load round trip a project must survive: the parts a save writes,1821 /// The save/load round trip a project must survive: the parts a save writes,
1632 /// handed back to the constructor a load goes through.1822 /// handed back to the constructor a load goes through.
1633 fn reloads(p: &Project, what: &str) {1823 fn reloads(p: &Project, what: &str) {
1634- let (sources, video, audio) = p.clone().without_orphan_sources();1824+ let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");
1635 if let Err(e) = Project::from_parts(sources, video, audio) {1825 if let Err(e) = Project::from_parts(sources, video, audio) {
1636 panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes);1826 panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes);
1637 }1827 }
1638 }1828 }
1829+
1830+ /// What [`reloads`] proves for a timeline the file format cannot hold yet:
1831+ /// the two invariants [`Project::from_parts`] checks that are about *lanes*
1832+ /// -- each one sorted and disjoint, and one span per group id -- asserted
1833+ /// directly, since a save of more than two lanes is refused on purpose.
1834+ fn invariants_hold(p: &Project, what: &str) {
1835+ for lane in p.lanes() {
1836+ assert!(
1837+ sorted_disjoint(p.lane(lane)),
1838+ "{what}: {} is out of order or overlaps itself: {:?}",
1839+ lane.label(),
1840+ p.lane(lane)
1841+ );
1842+ }
1843+ if let Err(e) = links_are_consistent(&p.lanes) {
1844+ panic!("{what}: {e}\n{:?}", p.lanes);
1845+ }
1846+ }
1847+
1848+ /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
1849+ /// edited without any other lane hearing about it. A handle naming a lane
1850+ /// that is not there reads as empty and refuses to mutate.
1851+ #[test]
1852+ fn a_third_lane_is_a_peer() {
1853+ let mut p = three();
1854+ assert_eq!(p.lane_count(LaneKind::Video), 1);
1855+ assert_eq!(p.lane_count(LaneKind::Audio), 1);
1856+ let v2 = p.add_lane(LaneKind::Video);
1857+ assert_eq!(v2, Lane::new(LaneKind::Video, 1));
1858+ assert_eq!(v2.label(), "V2");
1859+ assert_eq!(p.lane_count(LaneKind::Video), 2);
1860+ assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
1861+ assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
1862+
1863+ // A handle for a lane that is not there: empty, and no mutation takes.
1864+ let v3 = Lane::new(LaneKind::Video, 2);
1865+ assert!(p.lane(v3).is_empty());
1866+ assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
1867+ assert!(!p.lift(v3, 0));
1868+ assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
1869+
1870+ // Placing on V2 moves nothing else, and the lane can outrun the rest.
1871+ let before = shape(&p);
1872+ assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
1873+ assert_eq!(shape(&p)[0], before[0], "V1 never moved");
1874+ assert_eq!(shape(&p)[1], before[1], "A1 never moved");
1875+ assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
1876+ assert_eq!(
1877+ p.timeline_frames(),
1878+ 16,
1879+ "the last lane to end sets the length"
1880+ );
1881+ assert_eq!(p.map(v2, 5), Some((0, 21)));
1882+ assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
1883+ assert_eq!(
1884+ p.span_at(v2, 0),
1885+ Some(Span {
1886+ start: 0,
1887+ len: 4,
1888+ from: None
1889+ })
1890+ );
1891+ // Every lane still covers the whole timeline, gaps included.
1892+ for l in p.lanes() {
1893+ let spans = p.spans_from(l, 0);
1894+ assert_eq!(
1895+ spans.iter().map(|s| s.len).sum::<u32>(),
1896+ 16,
1897+ "{}",
1898+ l.label()
1899+ );
1900+ }
1901+ // ...and playback still reads V1 and A1, whatever else is there.
1902+ assert_eq!(p.clips(), p.lane(Lane::V1));
1903+ assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
1904+ let segments = p.segments_from(0, FPS);
1905+ assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
1906+ assert_eq!(
1907+ segments[3],
1908+ (None, 0.0, 7.0 / FPS),
1909+ "A1 keeps the clock counting over the picture V2 added"
1910+ );
1911+ invariants_hold(&p, "place on V2");
1912+
1913+ // A lift is that lane's business too, and the lane list undoes.
1914+ assert!(p.lift(v2, 0));
1915+ assert!(p.lane(v2).is_empty());
1916+ assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
1917+ assert!(p.undo());
1918+ assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
1919+ assert!(p.undo());
1920+ assert!(p.lane(v2).is_empty(), "the placement came off V2");
1921+ assert!(p.undo(), "and one more step takes the lane itself back");
1922+ assert_eq!(p.lane_count(LaneKind::Video), 1);
1923+ assert_eq!(shape(&p), shape(&three()));
1924+ }
1925+
1926+ /// The grouping rule across more than two lanes: a link id is one *span*,
1927+ /// on however many lanes carry it -- not a video/audio pair and not a
1928+ /// pairing by `ord`. So a split shares an id with every lane whose half
1929+ /// lines up, and gives its own to every lane whose half does not.
1930+ #[test]
1931+ fn a_group_id_is_one_span_across_every_lane() {
1932+ let mut p = Project::single(FILE, 9);
1933+ let v2 = p.add_lane(LaneKind::Video);
1934+ assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "three lanes, one span");
1935+ assert!(p.split(4));
1936+ let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
1937+ p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
1938+ };
1939+ let (left, right) = (side(&p, 0), side(&p, 1));
1940+ assert!(
1941+ left[0].is_some() && left.iter().all(|id| *id == left[0]),
1942+ "one id for three left halves: {left:?}"
1943+ );
1944+ assert!(right.iter().all(|id| *id == right[0]), "{right:?}");
1945+ assert_ne!(left[0], right[0], "the halves are no longer one take");
1946+ invariants_hold(&p, "split across three lanes");
1947+
1948+ // V2 ends early: same start, so the left halves are one take; different
1949+ // end, so the right halves cannot be.
1950+ let mut p = Project::single(FILE, 9);
1951+ let v2 = p.add_lane(LaneKind::Video);
1952+ assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
1953+ assert!(p.split(3));
1954+ assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "same [0, 3)");
1955+ assert_ne!(
1956+ p.lane(Lane::V1)[1].link,
1957+ p.lane(v2)[1].link,
1958+ "[3,9) vs [3,6)"
1959+ );
1960+ assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
1961+ invariants_hold(&p, "split where one lane ends early");
1962+
1963+ // The inverse rejoins all three, and groups them the same way.
1964+ assert!(p.regroup(3));
1965+ assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
1966+ assert_ne!(
1967+ p.lane(Lane::V1)[0].link,
1968+ p.lane(v2)[0].link,
1969+ "V2 rejoins into a span of its own"
1970+ );
1971+ invariants_hold(&p, "regroup across three lanes");
1972+
1973+ // ...and the rule is enforced, not merely produced: two video lanes
1974+ // carrying one id over two spans is refused, by lane name.
1975+ let linked = |out_frame, link| Clip {
1976+ start: 0,
1977+ in_frame: 0,
1978+ out_frame,
1979+ source: 0,
1980+ link: Some(link),
1981+ };
1982+ let lanes = vec![
1983+ LaneData {
1984+ kind: LaneKind::Video,
1985+ clips: vec![linked(3, 4)],
1986+ },
1987+ LaneData {
1988+ kind: LaneKind::Video,
1989+ clips: vec![linked(5, 4)],
1990+ },
1991+ ];
1992+ assert_eq!(
1993+ links_are_consistent(&lanes).unwrap_err().to_string(),
1994+ "link 4 covers [0, 3) in V1 and [0, 5) in V2"
1995+ );
1996+ }
1997+
1998+ /// A group is a set of clips over one span, at most one per lane: a picture
1999+ /// may be grouped with sound in *any* audio lane -- there is no paired ord,
2000+ /// and the lanes in between may be empty -- and the two ways to break that
2001+ /// name the lane they broke it on. Lanes built by hand, because the rule is
2002+ /// checked at the untrusted door and no edit can produce these.
2003+ #[test]
2004+ fn a_group_may_span_any_lane() {
2005+ let lane = |kind, clips: Vec<Clip>| LaneData { kind, clips };
2006+ let one = |start: u32, end: u32, link| Clip {
2007+ start,
2008+ in_frame: start,
2009+ out_frame: end,
2010+ source: 0,
2011+ link: Some(link),
2012+ };
2013+ // V1, A1, V2, A2 -- one take over [0, 4) on all four.
2014+ let kinds = [
2015+ LaneKind::Video,
2016+ LaneKind::Audio,
2017+ LaneKind::Video,
2018+ LaneKind::Audio,
2019+ ];
2020+ let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
2021+ kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
2022+ };
2023+ let take = || vec![one(0, 4, 7)];
2024+ assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
2025+ // The same take on V1 + A2 only, the lanes between it empty: legal, the
2026+ // way a lifted half is legal.
2027+ let across = build([take(), Vec::new(), Vec::new(), take()]);
2028+ assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
2029+ // Disagreeing about the span is not, and the message names both lanes.
2030+ let apart = build([take(), Vec::new(), Vec::new(), vec![one(0, 6, 7)]]);
2031+ assert_eq!(
2032+ links_are_consistent(&apart).unwrap_err().to_string(),
2033+ "link 7 covers [0, 4) in V1 and [0, 6) in A2"
2034+ );
2035+ // ...and one id twice in one lane is still that lane's error, by name.
2036+ let twice = build([
2037+ Vec::new(),
2038+ Vec::new(),
2039+ vec![one(0, 4, 7), one(4, 8, 7)],
2040+ Vec::new(),
2041+ ]);
2042+ assert_eq!(
2043+ links_are_consistent(&twice).unwrap_err().to_string(),
2044+ "link 7 names two clips in the V2 lane"
2045+ );
2046+ }
2047+
2048+ /// The model runs ahead of the file format on purpose, so a save of what the
2049+ /// format cannot hold is refused by name rather than silently dropping a
2050+ /// lane -- and a two-lane project still writes exactly the parts it always
2051+ /// did.
2052+ #[test]
2053+ fn a_save_refuses_more_lanes_than_the_format_holds() {
2054+ let mut p = three();
2055+ let before = p.without_orphan_sources().expect("two lanes save");
2056+ let v2 = p.add_lane(LaneKind::Video);
2057+ let err = p.without_orphan_sources().expect_err("refused").to_string();
2058+ assert!(
2059+ err.contains("2 video lanes") && err.contains("newer format"),
2060+ "{err}"
2061+ );
2062+ // Even empty: what cannot be written must not be quietly left behind.
2063+ assert!(p.lane(v2).is_empty());
2064+ assert!(p.undo(), "and the lane undoes");
2065+ assert_eq!(
2066+ p.without_orphan_sources().expect("saveable again"),
2067+ before,
2068+ "byte for byte the same parts a two-lane save always wrote"
2069+ );
2070+
2071+ let mut p = three();
2072+ p.add_lane(LaneKind::Audio);
2073+ assert!(
2074+ p.without_orphan_sources()
2075+ .unwrap_err()
2076+ .to_string()
2077+ .contains("2 audio lanes")
2078+ );
2079+ }
2080+
2081+ /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
2082+ /// three lanes and may grow more: every lane's own order and the one
2083+ /// span-per-id rule, after every op. Amended rather than merged into that
2084+ /// test because a >2-lane project cannot round-trip through the v2 file
2085+ /// format -- [`invariants_hold`] checks what a reload would have checked.
2086+ #[test]
2087+ fn random_edit_sequences_keep_many_lanes_consistent() {
2088+ for seed in 0..200u64 {
2089+ let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
2090+ let mut next = move |n: u32| {
2091+ rng ^= rng << 13;
2092+ rng ^= rng >> 7;
2093+ rng ^= rng << 17;
2094+ (rng >> 33) as u32 % n
2095+ };
2096+ let mut p = Project::single(FILE, 40);
2097+ let v2 = p.add_lane(LaneKind::Video);
2098+ assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
2099+ let lanes = [Lane::V1, Lane::A1, v2];
2100+ for step in 0..24 {
2101+ let frame = next(44);
2102+ let copied = *p
2103+ .lane(lanes[next(3) as usize])
2104+ .get(next(4) as usize)
2105+ .unwrap_or(&clip(0, 0, 5, 0));
2106+ let lane = lanes[next(3) as usize];
2107+ let idx = next(4) as usize;
2108+ let _ = match next(10) {
2109+ 0 => p.split(frame),
2110+ 1 => p.regroup(frame),
2111+ 2 => p.lift(lane, idx),
2112+ 3 => p.place(lane, frame, copied),
2113+ 4 => p.paste(frame, copied),
2114+ 5 => p.ripple_delete(frame, next(9)),
2115+ 6 => p.delete(idx),
2116+ 7 => p.undo(),
2117+ 8 => {
2118+ p.add_lane(if next(2) == 0 {
2119+ LaneKind::Video
2120+ } else {
2121+ LaneKind::Audio
2122+ });
2123+ true
2124+ }
2125+ _ => p.append_clip(0, 1 + next(9)),
2126+ };
2127+ invariants_hold(&p, &format!("seed {seed}, step {step}"));
2128+ }
2129+ }
2130+ }
1639 }2131 }
crates/engine/tests/audio_files.rsmodified+9 -9
@@ -131,15 +131,15 @@ fn a_song_joins_a_video_timeline_on_the_audio_lane() {
131 assert_eq!(session.sources().len(), 2);131 assert_eq!(session.sources().len(), 2);
132 // The video lane never hears about it: one clip, the one the file opened132 // The video lane never hears about it: one clip, the one the file opened
133 // with. The audio lane has two.133 // with. The audio lane has two.
134- assert_eq!(session.lane_clips(Lane::Video).len(), 1, "video lane");134+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "video lane");
135- assert_eq!(session.lane_clips(Lane::Audio).len(), 2, "audio lane");135+ assert_eq!(session.lane_clips(Lane::A1).len(), 2, "audio lane");
136- let song = session.lane_clips(Lane::Audio)[1];136+ let song = session.lane_clips(Lane::A1)[1];
137 assert_eq!((song.source, song.in_frame, song.len()), (1, 0, 90));137 assert_eq!((song.source, song.in_frame, song.len()), (1, 0, 90));
138 138
139 // And it plays: the segment list past the join names the song, so the139 // And it plays: the segment list past the join names the song, so the
140 // worker opens it rather than running silent.140 // worker opens it rather than running silent.
141 session.seek(before + 1.0);141 session.seek(before + 1.0);
142- assert!(session.lane_spans_by_source(Lane::Audio).len() >= 2);142+ assert!(session.lane_spans_by_source(Lane::A1).len() >= 2);
143 }143 }
144 144
145 #[test]145 #[test]
@@ -151,7 +151,7 @@ fn a_rate_the_device_cannot_mix_is_refused_at_the_door() {
151 );151 );
152 // Refused means unchanged: no source, no clip, no length.152 // Refused means unchanged: no source, no clip, no length.
153 assert_eq!(session.sources().len(), 1);153 assert_eq!(session.sources().len(), 1);
154- assert_eq!(session.lane_clips(Lane::Audio).len(), 1);154+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
155 }155 }
156 156
157 #[test]157 #[test]
@@ -198,9 +198,9 @@ fn a_song_survives_a_save_and_a_reload() {
198 session.import(&copy("test_tone.flac")).expect("import");198 session.import(&copy("test_tone.flac")).expect("import");
199 // And one placed at the playhead, the way a library row dropped on the199 // And one placed at the playhead, the way a library row dropped on the
200 // audio lane arrives -- so the reload has both doors to restore.200 // audio lane arrives -- so the reload has both doors to restore.
201- let song = session.lane_clips(Lane::Audio)[1];201+ let song = session.lane_clips(Lane::A1)[1];
202 assert!(session.place_at(202 assert!(session.place_at(
203- Lane::Audio,203+ Lane::A1,
204 1.0,204 1.0,
205 Clip {205 Clip {
206 in_frame: 0,206 in_frame: 0,
@@ -209,7 +209,7 @@ fn a_song_survives_a_save_and_a_reload() {
209 }209 }
210 ));210 ));
211 let before = (211 let before = (
212- session.lane_spans_by_source(Lane::Audio),212+ session.lane_spans_by_source(Lane::A1),
213 session.sources().to_vec(),213 session.sources().to_vec(),
214 session.timeline_duration(),214 session.timeline_duration(),
215 );215 );
@@ -221,7 +221,7 @@ fn a_song_survives_a_save_and_a_reload() {
221 reloaded.set_gain(0.0);221 reloaded.set_gain(0.0);
222 assert_eq!(222 assert_eq!(
223 (223 (
224- reloaded.lane_spans_by_source(Lane::Audio),224+ reloaded.lane_spans_by_source(Lane::A1),
225 reloaded.sources().to_vec(),225 reloaded.sources().to_vec(),
226 reloaded.timeline_duration()226 reloaded.timeline_duration()
227 ),227 ),
crates/engine/tests/export.rsmodified+3 -3
@@ -644,7 +644,7 @@ fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() {
644 let source = asset("test_av.mp4");644 let source = asset("test_av.mp4");
645 let mut session = PlaybackSession::open(&source).expect("open source");645 let mut session = PlaybackSession::open(&source).expect("open source");
646 assert!(session.cut_at(1.0), "cut at 1 s");646 assert!(session.cut_at(1.0), "cut at 1 s");
647- assert!(session.lift_clip(Lane::Audio, 0), "lift the first second");647+ assert!(session.lift_clip(Lane::A1, 0), "lift the first second");
648 session.pause();648 session.pause();
649 let out = out_path("leading_gap");649 let out = out_path("leading_gap");
650 let handle = session.export_to(&out);650 let handle = session.export_to(&out);
@@ -695,8 +695,8 @@ fn exports_a_gapped_timeline_as_black_and_silence() {
695 assert!(session.cut_at(2.0), "split at 2 s");695 assert!(session.cut_at(2.0), "split at 2 s");
696 // Lift the middle out of *both* lanes: one second of black and silence in696 // Lift the middle out of *both* lanes: one second of black and silence in
697 // the middle of a five-second timeline, with the length unchanged.697 // the middle of a five-second timeline, with the length unchanged.
698- assert!(session.lift_clip(Lane::Video, 1));698+ assert!(session.lift_clip(Lane::V1, 1));
699- assert!(session.lift_clip(Lane::Audio, 1));699+ assert!(session.lift_clip(Lane::A1, 1));
700 session.pause();700 session.pause();
701 let timeline = session.timeline_duration();701 let timeline = session.timeline_duration();
702 let frames = (timeline * FPS).round() as u32;702 let frames = (timeline * FPS).round() as u32;
crates/engine/tests/playback.rsmodified+2 -5
@@ -935,7 +935,7 @@ fn a_video_gap_plays_black_without_shortening_the_timeline() {
935 assert!(session.cut_at(2.0), "split at 2 s");935 assert!(session.cut_at(2.0), "split at 2 s");
936 assert!(session.cut_at(3.5), "split at 3.5 s");936 assert!(session.cut_at(3.5), "split at 3.5 s");
937 assert!(937 assert!(
938- session.lift_clip(Lane::Video, 1),938+ session.lift_clip(Lane::V1, 1),
939 "lift the middle picture out"939 "lift the middle picture out"
940 );940 );
941 assert_eq!(941 assert_eq!(
@@ -997,10 +997,7 @@ fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
997 assert!(session.cut_at(1.0), "split at 1 s");997 assert!(session.cut_at(1.0), "split at 1 s");
998 assert!(session.cut_at(2.0), "split at 2 s");998 assert!(session.cut_at(2.0), "split at 2 s");
999 // Silence over [1, 2) s while the picture plays on -- the two lanes part.999 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1000- assert!(1000+ assert!(session.lift_clip(Lane::A1, 1), "lift the middle sound out");
1001- session.lift_clip(Lane::Audio, 1),
1002- "lift the middle sound out"
1003- );
1004 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");1001 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
1005 let duration = session.timeline_duration();1002 let duration = session.timeline_duration();
1006 1003
crates/engine/tests/saveload.rsmodified+1 -1
@@ -147,7 +147,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_3() {
147 "v1 clips queue up, the second starting where the first ended"147 "v1 clips queue up, the second starting where the first ended"
148 );148 );
149 assert_eq!(149 assert_eq!(
150- loaded.lane_spans_by_source(engine::project::Lane::Audio),150+ loaded.lane_spans_by_source(engine::project::Lane::A1),
151 loaded.clip_spans_by_source(),151 loaded.clip_spans_by_source(),
152 "both lanes, fully grouped: a v1 timeline had no holes"152 "both lanes, fully grouped: a v1 timeline had no holes"
153 );153 );