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+42 -24
@@ -11,7 +11,7 @@ use std::time::{Duration, Instant};
1111
1212 use engine::audio::StreamInfo;
1313 use engine::export::ExportSettings;
14-use engine::project::{Lane, Source};
14+use engine::project::{Lane, LaneKind, Source};
1515 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
1616 use gpui::{
1717 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
@@ -494,14 +494,34 @@ impl Player {
494494 if self.exporting().is_some() {
495495 return;
496496 }
497- let deleted = match (&mut self.session, self.selected.take()) {
498- (Some(session), Some((Lane::Video, idx))) => session.delete_clip(idx),
499- (Some(session), Some((Lane::Audio, idx))) => match video_half(session, idx) {
500- Some(video) => session.delete_clip(video),
501- None => session.lift_clip(Lane::Audio, idx),
497+ let selected = self.selected.take();
498+ // Exhaustive over the kind, and explicit about the ord: both engine
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) {
508+ Some(video) => session.delete_clip(video),
509+ None => session.lift_clip(lane, idx),
510+ },
502511 },
503512 _ => false,
504513 };
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+ }
505525 if deleted {
506526 self.reset_after_reseek();
507527 }
@@ -654,7 +674,7 @@ impl Player {
654674 // dropped on the video lane it is refused by name, and asked for by the
655675 // Add button (which names no lane) it goes to the audio one -- which is
656676 // 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) {
658678 let name = file_name(path);
659679 self.notice = Some(
660680 format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(),
@@ -1748,8 +1768,8 @@ impl Player {
17481768 ),
17491769 ),
17501770 )
1751- .child(self.lane_row(Lane::Video, "V1", duration, filled, cx))
1752- .child(self.lane_row(Lane::Audio, "A1", duration, filled, cx))
1771+ .child(self.lane_row(Lane::V1, "V1", duration, filled, cx))
1772+ .child(self.lane_row(Lane::A1, "A1", duration, filled, cx))
17531773 }
17541774
17551775 /// A notice holds its own bar, full width, until it is answered: any key
@@ -2281,9 +2301,10 @@ impl Player {
22812301 let (clips, others) = match &self.session {
22822302 Some(session) => (
22832303 session.lane_clips(lane),
2284- session.lane_clips(match lane {
2285- Lane::Video => Lane::Audio,
2286- Lane::Audio => Lane::Video,
2304+ session.lane_clips(if lane.kind == LaneKind::Video {
2305+ Lane::A1
2306+ } else {
2307+ Lane::V1
22872308 }),
22882309 ),
22892310 None => (&[][..], &[][..]),
@@ -2293,7 +2314,7 @@ impl Player {
22932314 .as_ref()
22942315 .map_or(&[][..], PlaybackSession::sources);
22952316 let (sel, sel_link) = (self.selected, self.selected_link());
2296- let audio = lane == Lane::Audio;
2317+ let audio = lane.kind == LaneKind::Audio;
22972318 let tip: SharedString = format!(
22982319 "Select — {} removes the take, {} leaves a gap, {} rejoins a cut",
22992320 self.keymap.display(ActionId::Delete),
@@ -2615,9 +2636,9 @@ fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>)
26152636 /// Both lanes' clips, which is everything the timeline knows about its sources.
26162637 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
26172638 session
2618- .lane_clips(Lane::Video)
2639+ .lane_clips(Lane::V1)
26192640 .iter()
2620- .chain(session.lane_clips(Lane::Audio))
2641+ .chain(session.lane_clips(Lane::A1))
26212642 }
26222643
26232644 /// 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 {
29893010 /// still holds that half. `None` for a half whose picture was lifted -- which is
29903011 /// what makes it a thing of its own to delete.
29913012 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?;
29933014 session
2994- .lane_clips(Lane::Video)
3015+ .lane_clips(Lane::V1)
29953016 .iter()
29963017 .position(|clip| clip.link == Some(link))
29973018 }
@@ -3590,10 +3611,7 @@ mod tests {
35903611 // The whole of source 1 went in and nothing was painted over: the
35913612 // timeline is longer by exactly that file.
35923613 assert_eq!(session.timeline_duration(), 13.0);
3593- let (video, audio) = (
3594- session.lane_clips(Lane::Video),
3595- session.lane_clips(Lane::Audio),
3596- );
3614+ let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
35973615 // One take, not a video clip with no sound under it: both lanes hold
35983616 // the same clip at the same place, in the same group.
35993617 let at = |lane: &[Clip]| {
@@ -4097,13 +4115,13 @@ mod tests {
40974115
40984116 #[test]
40994117 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));
41014119 // Clicking the video half of group 1 marks the audio half with it.
41024120 assert!(marked(v, Some(1), Some(v), Some(1)));
41034121 assert!(marked(a, Some(1), Some(v), Some(1)));
41044122 // Another group's clips stay unmarked, in either lane.
4105- assert!(!marked((Lane::Video, 1), Some(2), Some(v), Some(1)));
4106- assert!(!marked((Lane::Audio, 1), Some(2), Some(v), Some(1)));
4123+ assert!(!marked((Lane::V1, 1), Some(2), Some(v), Some(1)));
4124+ assert!(!marked((Lane::A1, 1), Some(2), Some(v), Some(1)));
41074125 // A half a lift left behind has no group: it marks itself only, which
41084126 // is what makes it separately deletable. Two ungrouped clips must not
41094127 // mark each other by both being ungrouped.
crates/engine/src/export.rsmodified+1 -1
@@ -179,7 +179,7 @@ fn run(
179179 // Spans, not clips: a gap in the video lane is part of the timeline and
180180 // gets encoded too, as black frames. The picture count is therefore
181181 // `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) {
183183 // Every clip reopens its own source file at its own in point; the
184184 // encoder is *not* reopened, so the export is one continuous stream
185185 // 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 {
149149 // One clip per lane covering the file, so timeline == source until the
150150 // first edit -- and the range opened above is exactly that clip's.
151151 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");
153153 Ok(Self {
154154 meta,
155155 frames: stream.frames,
@@ -242,7 +242,7 @@ impl PlaybackSession {
242242
243243 let playhead = doc.playhead;
244244 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");
246246 // Last, because it is the one thing here that cannot be taken back: the
247247 // feeder thread outlives the `Audio` value (it holds its own clones) and
248248 // only a session's `drop` retires it, so a refusal above this line would
@@ -295,7 +295,7 @@ impl PlaybackSession {
295295 /// [`crate::edith`]). Sources no clip plays from are left out, and the
296296 /// playhead is saved with it so a reopened project resumes where it stood.
297297 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()?;
299299 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
300300 .min(self.project.timeline_frames().saturating_sub(1));
301301 crate::edith::save(path, &sources, &video, &audio, playhead)
@@ -359,7 +359,7 @@ impl PlaybackSession {
359359 /// clip under the running worker and only the mapping stays true.
360360 fn next_clip(&mut self) -> bool {
361361 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 {
363363 return false;
364364 };
365365 // We only get here on a disconnect, so the old worker has already
@@ -423,7 +423,7 @@ impl PlaybackSession {
423423 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
424424 /// an imported clip differently from the file the session was opened with.
425425 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)
427427 }
428428
429429 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
@@ -539,7 +539,7 @@ impl PlaybackSession {
539539 // nothing, because there is nothing on the video lane to move along
540540 // with it.
541541 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),
543543 false => self.paste_at(timeline_secs, clip),
544544 })
545545 }
@@ -630,7 +630,7 @@ impl PlaybackSession {
630630 let source = self.project.import(path, 0);
631631 let at = self.project.timeline_frames();
632632 self.project.place(
633- Lane::Audio,
633+ Lane::A1,
634634 at,
635635 Clip {
636636 start: at,
@@ -752,7 +752,7 @@ impl PlaybackSession {
752752 // `target` is inside the timeline (never empty), so this always spans;
753753 // the span runs from there to the end of whatever it landed in -- a
754754 // 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) {
756756 self.start_span(span);
757757 }
758758 self.eos = false;
crates/engine/src/project.rsmodified+726 -234
@@ -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.
22 //!
3-//! A [`Project`] holds a video lane and an audio lane. Each lane is a list of
3+//! 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
46 //! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
57 //! *source* frames it plays, which file it plays it from, and -- the whole model
68 //! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
@@ -11,8 +13,10 @@
1113 //! a hole cannot disagree with its neighbours about how long it is;
1214 //! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
1315 //! splice of the list;
14-//! * the lanes are independent: deleting audio under a picture is one lane's
15-//! business, and the picture does not shift.
16+//! * the lanes are independent and are peers: deleting audio under a picture is
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.
1620 //!
1721 //! The price is one invariant this module enforces at every mutation and every
1822 //! constructor: within a lane, clips are **sorted by `start` and never overlap**
@@ -24,14 +28,17 @@
2428 //! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
2529 //!
2630 //! 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 timeline
28-//! frame and hands the two sides two fresh ids; [`Project::regroup`] is its
29-//! inverse and rejoins them.
31+//! same take and move together. An id is *not* a pairing of two lanes -- it
32+//! names at most one clip per lane and every clip carrying it covers the same
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.
3037 //!
3138 //! Editing is metadata only. [`Project::split`] changes no timeline->source
3239 //! mapping, so a running decoder stays correct across it; everything else does
33-//! and the caller must reseek. Every successful edit snapshots both lanes, so
34-//! [`Project::undo`] is an exact restore.
40+//! and the caller must reseek. Every successful edit snapshots every lane, so
41+//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
3542 //!
3643 //! A clip names its file by *index* into [`Project::sources`], which is
3744 //! append-only: an index handed out once stays valid forever, so a clip on the
@@ -96,19 +103,74 @@ impl Source {
96103 }
97104 }
98105
99-/// Which lane an operation acts on. The lanes are peers: no operation reads one
100-/// to decide what to do to the other, except the grouped ones that say so.
106+/// What a lane carries, which is what a *gap* in it means: black frames on a
107+/// video lane, silence on an audio one.
101108 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
102-pub enum Lane {
109+pub enum LaneKind {
103110 Video,
104111 Audio,
105112 }
106113
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+
107128 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);
133+
134+ pub const fn new(kind: LaneKind, ord: usize) -> Self {
135+ 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+}
109158
110- fn index(self) -> usize {
111- self as usize
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+ ]
112174 }
113175 }
114176
@@ -138,20 +200,22 @@ impl Span {
138200 pub struct Project {
139201 /// Append-only: never popped, never reordered. See the module docs.
140202 sources: Vec<Source>,
141- /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint.
142- lanes: [Vec<Clip>; 2],
143- /// Snapshots pushed *before* each successful edit; `undo` pops one.
144- history: Vec<[Vec<Clip>; 2]>,
203+ /// In display order, which is the order [`Lane::ord`] counts in: the nth
204+ /// lane of a kind here is that kind's `ord` n. Never empty.
205+ lanes: Vec<LaneData>,
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>>,
145209 /// Never rolled back by an undo: an id retired by an undone split must not
146210 /// come back and group two clips that were never together.
147211 next_link: u32,
148212 }
149213
150214 impl Project {
151- /// One clip per lane covering the whole of `path`, the two grouped -- the
152- /// state of a freshly opened video, where the timeline is the source.
153- /// `frame_count` of 0 would break the never-empty invariant, so it is
154- /// clamped to one frame.
215+ /// `V1` and `A1`, one clip each covering the whole of `path` and the two
216+ /// grouped -- the state of a freshly opened video, where the timeline is the
217+ /// source. `frame_count` of 0 would break the never-empty invariant, so it
218+ /// is clamped to one frame.
155219 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
156220 let clip = Clip {
157221 start: 0,
@@ -164,14 +228,16 @@ impl Project {
164228 // A file is opened on its first audio stream: nothing has picked
165229 // one yet, and every file with audio at all has that one.
166230 sources: vec![Source::new(path, 0)],
167- lanes: [vec![clip], vec![clip]],
231+ lanes: LaneData::two_lanes(vec![clip], vec![clip]),
168232 history: Vec::new(),
169233 next_link: 1,
170234 }
171235 }
172236
173237 /// A project rebuilt from a saved edit list -- the load half of
174- /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is
238+ /// [`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
175241 /// `false` until the first edit of the new session. This is the one door
176242 /// untrusted parts come in through, so every invariant every other
177243 /// constructor keeps is checked here, by name and in release: both lanes
@@ -186,9 +252,10 @@ impl Project {
186252 if video.is_empty() && audio.is_empty() {
187253 return Err("both lanes are empty: that is not a project".into());
188254 }
189- let lanes = [video, audio];
190- for (lane, name) in lanes.iter().zip(["video", "audio"]) {
191- for c in lane {
255+ let lanes = LaneData::two_lanes(video, audio);
256+ for (data, lane) in lanes.iter().zip(handles(&lanes)) {
257+ let name = lane.label();
258+ for c in &data.clips {
192259 if c.out_frame <= c.in_frame {
193260 return Err(format!(
194261 "{name} clip at {} plays the empty range [{}, {})",
@@ -213,14 +280,14 @@ impl Project {
213280 .into());
214281 }
215282 }
216- if !sorted_disjoint(lane) {
283+ if !sorted_disjoint(&data.clips) {
217284 return Err(format!("the {name} lane is out of order or overlaps itself").into());
218285 }
219286 }
220287 links_are_consistent(&lanes)?;
221288 let next_link = lanes
222289 .iter()
223- .flatten()
290+ .flat_map(|l| &l.clips)
224291 .filter_map(|c| c.link)
225292 .max()
226293 // Saturating so a crafted file cannot make the counter wrap: at the
@@ -237,14 +304,60 @@ impl Project {
237304 })
238305 }
239306
240- /// The video lane -- what an export renders and what a single-lane caller
241- /// still means by "the clips".
307+ /// The first video lane -- what an export renders and what a single-lane
308+ /// caller still means by "the clips".
242309 pub fn clips(&self) -> &[Clip] {
243- self.lane(Lane::Video)
310+ self.lane(Lane::V1)
244311 }
245312
313+ /// The clips of `lane`, or nothing at all for a lane that is not there.
246314 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)
248361 }
249362
250363 /// The files the clips index into, in import order; index 0 is the file the
@@ -280,7 +393,7 @@ impl Project {
280393 }
281394 }
282395
283- /// Append a whole-file clip of `source` to the end of *both* lanes, grouped
396+ /// Append a whole-file clip of `source` to the end of *every* lane, grouped
284397 /// -- an import lands as one take. One history snapshot, so an import is one
285398 /// undo step, and undoing it leaves the (harmless) source entry behind,
286399 /// because indexes are forever. Refused for an unknown source index.
@@ -297,8 +410,8 @@ impl Project {
297410 source,
298411 link: Some(self.new_link()),
299412 };
300- for lane in &mut self.lanes {
301- lane.push(clip);
413+ for data in &mut self.lanes {
414+ data.clips.push(clip);
302415 }
303416 true
304417 }
@@ -310,11 +423,31 @@ impl Project {
310423 /// nothing plays refuse a future load. New indexes are assigned in order of
311424 /// first use -- video lane first, then audio -- so the same project always
312425 /// 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+ }
314447 let mut moved = vec![None; self.sources.len()];
315448 let mut sources = Vec::new();
316449 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) {
318451 let old = c.source;
319452 c.source = match moved[old] {
320453 Some(new) => new,
@@ -325,8 +458,14 @@ impl Project {
325458 }
326459 };
327460 }
328- let [video, audio] = lanes;
329- (sources, video, audio)
461+ let (mut video, mut audio) = (Vec::new(), Vec::new());
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))
330469 }
331470
332471 /// Length of the timeline in frames: where the *last* lane runs out. A lane
@@ -334,15 +473,15 @@ impl Project {
334473 pub fn timeline_frames(&self) -> u32 {
335474 self.lanes
336475 .iter()
337- .filter_map(|lane| lane.last().map(Clip::end))
476+ .filter_map(|l| l.clips.last().map(Clip::end))
338477 .max()
339478 .unwrap_or(0)
340479 }
341480
342- /// `(timeline_start, len)` per video clip, in order -- what a UI lane needs
481+ /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
343482 /// to lay clips out. Gaps show up as the holes between consecutive entries.
344483 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
345- self.lane_spans(Lane::Video)
484+ self.lane_spans(Lane::V1)
346485 }
347486
348487 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
@@ -361,9 +500,9 @@ impl Project {
361500 ))
362501 }
363502
364- /// [`map`](Project::map) on the video lane -- the mapping a decoder follows.
503+ /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
365504 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)
367506 }
368507
369508 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
@@ -418,53 +557,40 @@ impl Project {
418557 /// placement's own start, in a gap, and past the end -- all of which would
419558 /// produce an empty clip or nothing at all.
420559 ///
421- /// The two lanes' halves share an id only where they are the *same* span:
422- /// the lanes are edited apart, so the clip being cut here may start (or
423- /// end) somewhere else in the other lane, and a group id whose two clips
424- /// disagree about their span is not one take (see [`links_are_consistent`],
425- /// which refuses to load one).
560+ /// Lanes' halves share an id only where they are the *same* span: the lanes
561+ /// are edited apart, so the clip being cut here may start (or end)
562+ /// somewhere else on another lane, and a group id whose clips disagree
563+ /// about their span is not one take (see [`links_are_consistent`], which
564+ /// refuses to load one).
426565 ///
427566 /// Metadata only: no mapping changes, in any lane.
428567 pub fn split(&mut self, timeline_frame: u32) -> bool {
429- let cut = Lane::ALL
430- .map(|l| splittable(self.lane(l), timeline_frame).map(|idx| self.lane(l)[idx]));
568+ let cut: Vec<Option<Clip>> = self
569+ .lanes
570+ .iter()
571+ .map(|l| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
572+ .collect();
431573 if cut.iter().all(Option::is_none) {
432574 return false;
433575 }
434576 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());
440577 // 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.
442- let ids = [
443- (left, right),
444- (
445- if same(|c| c.start) {
446- left
447- } 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 {
578+ // apart, and every lane whose halves do line up stays one take.
579+ let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();
580+ let ends: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.end())).collect();
581+ let left = self.group_ids(&starts);
582+ let right = self.group_ids(&ends);
583+ for ((data, left), right) in self.lanes.iter_mut().zip(left).zip(right) {
584+ let Some(idx) = splittable(&data.clips, timeline_frame) else {
459585 continue;
460586 };
461- let mut tail = lane[idx];
587+ let mut tail = data.clips[idx];
462588 tail.in_frame += timeline_frame - tail.start;
463589 tail.start = timeline_frame;
464- tail.link = Some(right);
465- lane[idx].out_frame = tail.in_frame;
466- lane[idx].link = Some(left);
467- lane.insert(idx + 1, tail);
590+ tail.link = right;
591+ data.clips[idx].out_frame = tail.in_frame;
592+ data.clips[idx].link = left;
593+ data.clips.insert(idx + 1, tail);
468594 }
469595 true
470596 }
@@ -479,29 +605,26 @@ impl Project {
479605 /// reason.
480606 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
481607 // What each lane would end up covering, if it joins here at all.
482- let joined = Lane::ALL.map(|l| {
483- joinable(self.lane(l), timeline_frame)
484- .map(|idx| (self.lane(l)[idx].start, self.lane(l)[idx + 1].end()))
485- });
608+ let joined: Vec<Option<(u32, u32)>> = self
609+ .lanes
610+ .iter()
611+ .map(|l| {
612+ joinable(&l.clips, timeline_frame)
613+ .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
614+ })
615+ .collect();
486616 if joined.iter().all(Option::is_none) {
487617 return false;
488618 }
489619 self.snapshot();
490- let link = self.new_link();
491- let ids = [
492- link,
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 {
620+ let ids = self.group_ids(&joined);
621+ for (data, link) in self.lanes.iter_mut().zip(ids) {
622+ let Some(idx) = joinable(&data.clips, timeline_frame) else {
500623 continue;
501624 };
502- lane[idx].out_frame = lane[idx + 1].out_frame;
503- lane[idx].link = Some(link);
504- lane.remove(idx + 1);
625+ data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
626+ data.clips[idx].link = link;
627+ data.clips.remove(idx + 1);
505628 }
506629 true
507630 }
@@ -518,10 +641,12 @@ impl Project {
518641 /// back over the clip it came from -- would put that id on two clips of one
519642 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
520643 /// `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 clips
644+ /// another lane to be grouped *with*; [`Project::regroup`] is how clips
522645 /// become a group again.
646+ ///
647+ /// Refused for an empty `clip` and for a lane that is not there.
523648 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() {
525650 return false;
526651 }
527652 self.snapshot();
@@ -530,15 +655,15 @@ impl Project {
530655 link: None,
531656 ..clip
532657 };
533- let lane = &mut self.lanes[lane.index()];
534- clear(lane, clip.start, clip.end());
535- let idx = lane.partition_point(|c| c.start < clip.start);
536- lane.insert(idx, clip);
537- debug_assert!(sorted_disjoint(lane));
658+ let clips = self.lane_mut(lane).expect("checked above");
659+ clear(clips, clip.start, clip.end());
660+ let idx = clips.partition_point(|c| c.start < clip.start);
661+ clips.insert(idx, clip);
662+ debug_assert!(sorted_disjoint(clips));
538663 true
539664 }
540665
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,
542667 /// pushing everything from there on later by its length -- the grouped,
543668 /// rippling paste a clipboard does. Mid-clip the clip it lands in is split
544669 /// around it; at or past the end of the timeline it is appended, because a
@@ -560,33 +685,34 @@ impl Project {
560685 link: Some(self.new_link()),
561686 ..clip
562687 };
563- for lane in &mut self.lanes {
564- open_room(lane, at, clip.len());
565- let idx = lane.partition_point(|c| c.start < at);
566- lane.insert(idx, clip);
567- debug_assert!(sorted_disjoint(lane));
688+ for data in &mut self.lanes {
689+ open_room(&mut data.clips, at, clip.len());
690+ let idx = data.clips.partition_point(|c| c.start < at);
691+ data.clips.insert(idx, clip);
692+ debug_assert!(sorted_disjoint(&data.clips));
568693 }
569694 true
570695 }
571696
572697 /// 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 and
574- /// for the lift that would leave *both* lanes empty -- an empty timeline is
575- /// the front-end's state, not a project's (see the never-empty invariant).
698+ /// silence, and nothing else moves. Refused for an out-of-range index (which
699+ /// a lane that is not there always is) and for the lift that would leave
700+ /// *every* lane empty -- an empty timeline is the front-end's state, not a
701+ /// project's (see the never-empty invariant).
576702 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();
578704 if idx >= self.lane(lane).len() || placed == 1 {
579705 return false;
580706 }
581707 self.snapshot();
582- self.lanes[lane.index()].remove(idx);
708+ self.lane_mut(lane).expect("checked above").remove(idx);
583709 true
584710 }
585711
586712 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
587713 /// the hole: everything after slides back by `len`. The rippling delete --
588714 /// [`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.
590716 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
591717 if len == 0 {
592718 return false;
@@ -594,8 +720,9 @@ impl Project {
594720 let survivors: usize = self
595721 .lanes
596722 .iter()
597- .map(|lane| {
598- lane.iter()
723+ .map(|l| {
724+ l.clips
725+ .iter()
599726 .filter(|c| c.start < at || c.end() > at + len)
600727 .count()
601728 })
@@ -604,17 +731,17 @@ impl Project {
604731 return false;
605732 }
606733 self.snapshot();
607- for lane in &mut self.lanes {
608- clear(lane, at, at + len);
609- for c in lane.iter_mut().filter(|c| c.start >= at) {
734+ for data in &mut self.lanes {
735+ clear(&mut data.clips, at, at + len);
736+ for c in data.clips.iter_mut().filter(|c| c.start >= at) {
610737 c.start -= len;
611738 }
612- debug_assert!(sorted_disjoint(lane));
739+ debug_assert!(sorted_disjoint(&data.clips));
613740 }
614741 true
615742 }
616743
617- /// Remove the video clip at `idx` and everything under it, closing the gap
744+ /// Remove the `V1` clip at `idx` and everything under it, closing the gap
618745 /// -- the whole-group delete a single-lane front-end means. `false` for a
619746 /// bad index. Changes the mapping: the caller must reseek.
620747 pub fn delete(&mut self, idx: usize) -> bool {
@@ -624,8 +751,8 @@ impl Project {
624751 self.ripple_delete(clip.start, clip.len())
625752 }
626753
627- /// Restore both lanes from before the last successful edit. `false` when
628- /// there is nothing left to undo.
754+ /// Restore every lane from before the last successful edit -- the clips and
755+ /// the lane list both. `false` when there is nothing left to undo.
629756 pub fn undo(&mut self) -> bool {
630757 match self.history.pop() {
631758 Some(prev) => {
@@ -638,7 +765,7 @@ impl Project {
638765
639766 /// Half-open `(source, start, end)` segments in *source* seconds, from
640767 /// `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: the
768+ /// audio worker, read off **`A1`**. A `None` source is a gap: the
642769 /// worker synthesises that many seconds of silence, which is what keeps the
643770 /// audio master clock counting across a hole instead of stalling on it.
644771 /// The first entry is partial when the position is mid-clip. Empty when the
@@ -647,7 +774,7 @@ impl Project {
647774 if !(fps.is_finite() && fps > 0.0) {
648775 return Vec::new();
649776 }
650- self.spans_from(Lane::Audio, timeline_frame)
777+ self.spans_from(Lane::A1, timeline_frame)
651778 .iter()
652779 .map(|span| match span.from {
653780 // A clip's window is in *source* seconds: where in the file it
@@ -674,6 +801,51 @@ impl Project {
674801 self.next_link = self.next_link.saturating_add(1);
675802 id
676803 }
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()
677849 }
678850
679851 /// Index of the clip covering `frame`, or `None` for a gap or past the end.
@@ -709,37 +881,51 @@ fn sorted_disjoint(clips: &[Clip]) -> bool {
709881 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
710882 }
711883
712-/// The grouping invariant, checked in release at [`Project::from_parts`]: a link
713-/// id names **at most one** clip per lane, and when it names one in each, the two
714-/// cover the same timeline span -- that is all "these move together" can mean.
884+/// The grouping invariant, checked in release at [`Project::from_parts`] and
885+/// asserted by the tests after every edit: a link id names **at most one** clip
886+/// per lane, and every clip carrying it covers the same timeline span -- that is
887+/// all "these move together" can mean.
715888 ///
716-/// A link the *other* lane does not carry is legal and is not an error: lifting
717-/// one half of a group ([`Project::lift`]) leaves exactly that, and a save of
718-/// that timeline has to load again.
719-fn links_are_consistent(lanes: &[Vec<Clip>; 2]) -> crate::Result<()> {
720- let find = |lane: &Vec<Clip>, id: u32| lane.iter().find(|c| c.link == Some(id)).copied();
721- for (lane, name) in lanes.iter().zip(["video", "audio"]) {
722- for (i, c) in lane.iter().enumerate() {
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".
893+///
894+/// A link no other lane carries is legal and is not an error: lifting one half
895+/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
896+/// timeline has to load again.
897+fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
898+ let handles = handles(lanes);
899+ for (data, lane) in lanes.iter().zip(&handles) {
900+ for (i, c) in data.clips.iter().enumerate() {
723901 let Some(id) = c.link else { continue };
724- if lane[..i].iter().any(|prev| prev.link == Some(id)) {
725- return Err(format!("link {id} names two clips in the {name} lane").into());
902+ if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
903+ return Err(
904+ format!("link {id} names two clips in the {} lane", lane.label()).into(),
905+ );
726906 }
727907 }
728908 }
729- for a in lanes[0].iter().filter(|c| c.link.is_some()) {
730- let id = a.link.expect("filtered");
731- let Some(b) = find(&lanes[1], id) else {
732- continue;
733- };
734- if (a.start, a.end()) != (b.start, b.end()) {
735- return Err(format!(
736- "link {id} covers [{}, {}) in video and [{}, {}) in audio",
737- a.start,
738- a.end(),
739- b.start,
740- b.end()
741- )
742- .into());
909+ // First lane to carry an id fixes the span every other lane must agree on.
910+ let mut seen: Vec<(u32, Lane, u32, u32)> = Vec::new();
911+ for (data, &lane) in lanes.iter().zip(&handles) {
912+ for c in &data.clips {
913+ let Some(id) = c.link else { continue };
914+ match seen.iter().find(|(other, ..)| *other == id) {
915+ Some(&(_, first, start, end)) => {
916+ if (start, end) != (c.start, c.end()) {
917+ return Err(format!(
918+ "link {id} covers [{start}, {end}) in {} and [{}, {}) in {}",
919+ first.label(),
920+ c.start,
921+ c.end(),
922+ lane.label()
923+ )
924+ .into());
925+ }
926+ }
927+ None => seen.push((id, lane, c.start, c.end())),
928+ }
743929 }
744930 }
745931 Ok(())
@@ -829,22 +1015,30 @@ mod tests {
8291015 }
8301016 }
8311017
832- /// Both lanes with their group ids blanked, for comparing shape.
833- fn shape(p: &Project) -> [Vec<Clip>; 2] {
834- Lane::ALL.map(|l| {
835- p.lane(l)
836- .iter()
837- .map(|c| Clip { link: None, ..*c })
838- .collect()
839- })
1018+ /// Every lane with its group ids blanked, for comparing shape.
1019+ fn shape(p: &Project) -> Vec<Vec<Clip>> {
1020+ p.lanes()
1021+ .into_iter()
1022+ .map(|l| {
1023+ p.lane(l)
1024+ .iter()
1025+ .map(|c| Clip { link: None, ..*c })
1026+ .collect()
1027+ })
1028+ .collect()
8401029 }
8411030
8421031 /// The *source frame* every timeline frame reads, per lane -- the traversal
8431032 /// a player performs. Deliberately not the clip index: a split changes which
8441033 /// 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>>> {
8461035 (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+ })
8481042 .collect()
8491043 }
8501044
@@ -868,11 +1062,11 @@ mod tests {
8681062 fn single_is_the_whole_file_on_both_lanes() {
8691063 let p = Project::single(FILE, 150);
8701064 assert_eq!(p.clips().len(), 1);
871- assert_eq!(p.lane(Lane::Audio).len(), 1);
1065+ assert_eq!(p.lane(Lane::A1).len(), 1);
8721066 assert_eq!(p.timeline_frames(), 150);
8731067 assert_eq!(p.clip_spans(), vec![(0, 150)]);
8741068 // 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);
8761070 assert!(p.clips()[0].link.is_some());
8771071 // degenerate mapping: timeline == source
8781072 assert_eq!(p.map_timeline(0), Some((0, 0)));
@@ -889,11 +1083,11 @@ mod tests {
8891083 let before_shape = shape(&p);
8901084
8911085 assert!(p.split(4));
892- for l in Lane::ALL {
893- assert_eq!(p.lane(l).len(), 2, "{l:?} split");
1086+ for l in p.lanes() {
1087+ assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
8941088 }
8951089 // 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));
8971091 assert_eq!(v[0].link, a[0].link);
8981092 assert_eq!(v[1].link, a[1].link);
8991093 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
@@ -904,8 +1098,8 @@ mod tests {
9041098 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
9051099 assert_eq!(traversal(&p), before);
9061100 assert_eq!(
907- p.lane(Lane::Video)[0].link,
908- p.lane(Lane::Audio)[0].link,
1101+ p.lane(Lane::V1)[0].link,
1102+ p.lane(Lane::A1)[0].link,
9091103 "and the rejoined clip is one group again"
9101104 );
9111105 }
@@ -926,8 +1120,8 @@ mod tests {
9261120
9271121 // ...and a frame that is a gap in both lanes has nothing to split.
9281122 let mut p = three();
929- assert!(p.lift(Lane::Video, 1));
930- assert!(p.lift(Lane::Audio, 1));
1123+ assert!(p.lift(Lane::V1, 1));
1124+ assert!(p.lift(Lane::A1, 1));
9311125 assert!(!p.split(4), "a gap is not a clip");
9321126 }
9331127
@@ -940,11 +1134,11 @@ mod tests {
9401134 // A boundary with a gap on one side, and one where the sources do not
9411135 // meet, are both refused.
9421136 let mut p = three();
943- assert!(p.lift(Lane::Video, 1));
944- assert!(p.lift(Lane::Audio, 1));
1137+ assert!(p.lift(Lane::V1, 1));
1138+ assert!(p.lift(Lane::A1, 1));
9451139 assert!(!p.regroup(3), "nothing starts at 3 any more");
9461140 let mut p = three();
947- for l in Lane::ALL {
1141+ for l in p.lanes() {
9481142 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
9491143 }
9501144 assert!(!p.regroup(3), "source 100 does not follow source 3");
@@ -975,14 +1169,14 @@ mod tests {
9751169 assert_eq!(p.map_timeline(9), None);
9761170 // A span is the rest of the clip from where it was asked about.
9771171 assert_eq!(
978- p.span_at(Lane::Video, 6),
1172+ p.span_at(Lane::V1, 6),
9791173 Some(Span {
9801174 start: 6,
9811175 len: 3,
9821176 from: Some((0, 6))
9831177 })
9841178 );
985- assert_eq!(p.span_at(Lane::Video, 9), None);
1179+ assert_eq!(p.span_at(Lane::V1, 9), None);
9861180 }
9871181
9881182 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
@@ -1070,7 +1264,7 @@ mod tests {
10701264 assert!(p.delete(1));
10711265 assert_eq!(p.timeline_frames(), 7);
10721266 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)]);
10741268 // timeline 3 used to be source 3; the gap closed so it is source 5 now
10751269 assert_eq!(p.map_timeline(3), Some((1, 5)));
10761270 assert_eq!(p.map_timeline(6), Some((1, 8)));
@@ -1100,32 +1294,32 @@ mod tests {
11001294 fn a_lift_leaves_a_gap_and_moves_nothing() {
11011295 let mut p = three();
11021296 let video_before = shape(&p)[0].clone();
1103- assert!(p.lift(Lane::Audio, 1));
1297+ assert!(p.lift(Lane::A1, 1));
11041298 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
11051299 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)]);
11071301 // 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);
11091303 assert_eq!(
1110- p.span_at(Lane::Audio, 3),
1304+ p.span_at(Lane::A1, 3),
11111305 Some(Span {
11121306 start: 3,
11131307 len: 2,
11141308 from: None
11151309 })
11161310 );
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");
11181312 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)]);
11201314 }
11211315
11221316 #[test]
11231317 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
11241318 let mut p = three();
1125- assert!(p.lift(Lane::Audio, 2));
1319+ assert!(p.lift(Lane::A1, 2));
11261320 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
11271321 assert_eq!(
1128- p.span_at(Lane::Audio, 5),
1322+ p.span_at(Lane::A1, 5),
11291323 Some(Span {
11301324 start: 5,
11311325 len: 4,
@@ -1133,11 +1327,11 @@ mod tests {
11331327 }),
11341328 "the audio lane holds silence to the end of the picture"
11351329 );
1136- assert_eq!(p.span_at(Lane::Audio, 9), None);
1330+ assert_eq!(p.span_at(Lane::A1, 9), None);
11371331 // Every lane covers the timeline exactly, gaps included.
1138- for l in Lane::ALL {
1332+ for l in p.lanes() {
11391333 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());
11411335 assert_eq!(spans[0].start, 0);
11421336 }
11431337 }
@@ -1145,9 +1339,9 @@ mod tests {
11451339 #[test]
11461340 fn the_last_clip_of_the_last_lane_cannot_be_lifted() {
11471341 let mut p = Project::single(FILE, 9);
1148- assert!(p.lift(Lane::Audio, 0), "a silent timeline is fine");
1149- assert!(!p.lift(Lane::Video, 0), "an empty one is not");
1150- assert!(!p.lift(Lane::Audio, 0), "index past the end");
1342+ assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
1343+ assert!(!p.lift(Lane::V1, 0), "an empty one is not");
1344+ assert!(!p.lift(Lane::A1, 0), "index past the end");
11511345 assert_eq!(p.timeline_frames(), 9);
11521346 }
11531347
@@ -1157,7 +1351,7 @@ mod tests {
11571351 let audio_before = shape(&p)[1].clone();
11581352 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
11591353 // 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)));
11611355 assert_eq!(
11621356 shape(&p)[0],
11631357 vec![
@@ -1172,23 +1366,23 @@ mod tests {
11721366
11731367 // Placed inside one clip, it splits it in two.
11741368 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)));
11761370 assert_eq!(
11771371 shape(&p)[0],
11781372 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
11791373 );
11801374 // ...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)));
11821376 assert_eq!(p.timeline_frames(), 22);
11831377 assert_eq!(
1184- p.span_at(Lane::Video, 9),
1378+ p.span_at(Lane::V1, 9),
11851379 Some(Span {
11861380 start: 9,
11871381 len: 11,
11881382 from: None
11891383 })
11901384 );
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");
11921386 }
11931387
11941388 #[test]
@@ -1266,7 +1460,7 @@ mod tests {
12661460 #[test]
12671461 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
12681462 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)
12701464 assert_eq!(
12711465 p.segments_from(0, FPS),
12721466 vec![
@@ -1285,8 +1479,8 @@ mod tests {
12851479 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
12861480 );
12871481 // ...and a lane that is nothing but gap is a run of silence.
1288- assert!(p.lift(Lane::Audio, 0));
1289- assert!(p.lift(Lane::Audio, 0));
1482+ assert!(p.lift(Lane::A1, 0));
1483+ assert!(p.lift(Lane::A1, 0));
12901484 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
12911485 }
12921486
@@ -1410,10 +1604,10 @@ mod tests {
14101604 // Import a second file, undo it: source 1 is now an orphan.
14111605 let mut p = two_sources();
14121606 assert!(p.undo());
1413- let (sources, video, audio) = p.without_orphan_sources();
1607+ let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");
14141608 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
14151609 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));
14171611
14181612 // Three sources where only the middle one is orphaned: the survivors
14191613 // renumber, and the clips follow.
@@ -1421,7 +1615,7 @@ mod tests {
14211615 assert_eq!(p.import(FILE2, 0), 1);
14221616 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
14231617 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");
14251619 assert_eq!(
14261620 sources,
14271621 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
@@ -1435,7 +1629,7 @@ mod tests {
14351629
14361630 #[test]
14371631 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");
14391633 let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone())
14401634 .expect("valid parts");
14411635 assert_eq!(p.clips(), three().clips());
@@ -1467,9 +1661,13 @@ mod tests {
14671661 }
14681662
14691663 /// 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 lanes
1471- /// carry it, one span -- and no sequence of edits may produce otherwise,
1664+ /// touch a link. A link id is at most one clip per lane and, wherever it is
1665+ /// carried, one span -- and no sequence of edits may produce otherwise,
14721666 /// 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.
14731671 #[test]
14741672 fn a_link_id_is_never_two_clips_of_one_lane() {
14751673 let sources = vec![Source::new(FILE, 0)];
@@ -1489,18 +1687,18 @@ mod tests {
14891687 };
14901688 assert!(
14911689 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"),
14931691 "a duplicate id inside one lane is refused by name"
14941692 );
14951693 assert!(
14961694 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"),
14981696 "a pair that does not cover one span is refused by name"
14991697 );
15001698 // A one-sided link is *not* an error: it is what a lift leaves behind.
15011699 let mut p = Project::single(FILE, 9);
1502- assert!(p.lift(Lane::Audio, 0));
1503- let (sources, video, audio) = p.clone().without_orphan_sources();
1700+ assert!(p.lift(Lane::A1, 0));
1701+ let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");
15041702 assert!(
15051703 Project::from_parts(sources, video, audio).is_ok(),
15061704 "a lifted lane's project has to load again"
@@ -1508,8 +1706,11 @@ mod tests {
15081706
15091707 // The edits: nothing below may break either rule.
15101708 let consistent = |p: &Project, what: &str| {
1511- let lanes = Lane::ALL.map(|l| p.lane(l).to_vec());
1512- assert!(links_are_consistent(&lanes).is_ok(), "{what}: {lanes:?}");
1709+ assert!(
1710+ links_are_consistent(&p.lanes).is_ok(),
1711+ "{what}: {:?}",
1712+ p.lanes
1713+ );
15131714 };
15141715 let mut p = three();
15151716 let copied = p.clips()[0];
@@ -1517,19 +1718,16 @@ mod tests {
15171718 copied.link.is_some(),
15181719 "the clipboard clip carries its group"
15191720 );
1520- assert!(p.lift(Lane::Video, 0));
1521- assert!(p.place(Lane::Video, 0, copied));
1522- assert!(p.place(Lane::Video, 20, copied), "and again, further out");
1721+ assert!(p.lift(Lane::V1, 0));
1722+ assert!(p.place(Lane::V1, 0, copied));
1723+ assert!(p.place(Lane::V1, 20, copied), "and again, further out");
15231724 assert_eq!(
15241725 p.clips().iter().filter(|c| c.link == copied.link).count(),
15251726 0,
15261727 "a placement belongs to no group, so it cannot duplicate one"
15271728 );
15281729 consistent(&p, "lift + place twice");
1529- assert!(
1530- p.place(Lane::Audio, 4, copied),
1531- "over a linked clip's middle"
1532- );
1730+ assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
15331731 consistent(&p, "place through a grouped clip");
15341732 assert!(p.paste(6, copied), "a rippling paste through another");
15351733 consistent(&p, "paste");
@@ -1548,13 +1746,13 @@ mod tests {
15481746 #[test]
15491747 fn every_reachable_state_reloads() {
15501748 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)));
15521750 assert!(p.split(10), "the lanes are cut apart at 10");
15531751 reloads(&p, "place on one lane, then split");
15541752
15551753 let mut p = Project::single(FILE, 150);
15561754 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");
15581756 assert!(p.regroup(30), "only the audio lane can rejoin");
15591757 assert!(p.split(60));
15601758 reloads(&p, "lift, regroup one lane, split");
@@ -1571,7 +1769,7 @@ mod tests {
15711769 &p,
15721770 "a second audio stream of the same file, placed and split",
15731771 );
1574- let (sources, ..) = p.without_orphan_sources();
1772+ let (sources, ..) = p.without_orphan_sources().expect("two lanes");
15751773 assert_eq!(
15761774 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
15771775 [0, 1],
@@ -1599,18 +1797,10 @@ mod tests {
15991797 // A clipboard copy carries the group id of the take it came from
16001798 // -- the input that made a placement duplicate an id.
16011799 let copied = *p
1602- .lane(if next(2) == 0 {
1603- Lane::Video
1604- } else {
1605- Lane::Audio
1606- })
1800+ .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
16071801 .get(next(4) as usize)
16081802 .unwrap_or(&clip(0, 0, 5, 0));
1609- let lane = if next(2) == 0 {
1610- Lane::Video
1611- } else {
1612- Lane::Audio
1613- };
1803+ let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
16141804 let idx = next(4) as usize;
16151805 let _ = match next(9) {
16161806 0 => p.split(frame),
@@ -1631,9 +1821,311 @@ mod tests {
16311821 /// The save/load round trip a project must survive: the parts a save writes,
16321822 /// handed back to the constructor a load goes through.
16331823 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");
16351825 if let Err(e) = Project::from_parts(sources, video, audio) {
16361826 panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes);
16371827 }
16381828 }
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+ }
16392131 }
crates/engine/tests/audio_files.rsmodified+9 -9
@@ -131,15 +131,15 @@ fn a_song_joins_a_video_timeline_on_the_audio_lane() {
131131 assert_eq!(session.sources().len(), 2);
132132 // The video lane never hears about it: one clip, the one the file opened
133133 // with. The audio lane has two.
134- assert_eq!(session.lane_clips(Lane::Video).len(), 1, "video lane");
135- assert_eq!(session.lane_clips(Lane::Audio).len(), 2, "audio lane");
136- let song = session.lane_clips(Lane::Audio)[1];
134+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "video lane");
135+ assert_eq!(session.lane_clips(Lane::A1).len(), 2, "audio lane");
136+ let song = session.lane_clips(Lane::A1)[1];
137137 assert_eq!((song.source, song.in_frame, song.len()), (1, 0, 90));
138138
139139 // And it plays: the segment list past the join names the song, so the
140140 // worker opens it rather than running silent.
141141 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);
143143 }
144144
145145 #[test]
@@ -151,7 +151,7 @@ fn a_rate_the_device_cannot_mix_is_refused_at_the_door() {
151151 );
152152 // Refused means unchanged: no source, no clip, no length.
153153 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);
155155 }
156156
157157 #[test]
@@ -198,9 +198,9 @@ fn a_song_survives_a_save_and_a_reload() {
198198 session.import(&copy("test_tone.flac")).expect("import");
199199 // And one placed at the playhead, the way a library row dropped on the
200200 // 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];
202202 assert!(session.place_at(
203- Lane::Audio,
203+ Lane::A1,
204204 1.0,
205205 Clip {
206206 in_frame: 0,
@@ -209,7 +209,7 @@ fn a_song_survives_a_save_and_a_reload() {
209209 }
210210 ));
211211 let before = (
212- session.lane_spans_by_source(Lane::Audio),
212+ session.lane_spans_by_source(Lane::A1),
213213 session.sources().to_vec(),
214214 session.timeline_duration(),
215215 );
@@ -221,7 +221,7 @@ fn a_song_survives_a_save_and_a_reload() {
221221 reloaded.set_gain(0.0);
222222 assert_eq!(
223223 (
224- reloaded.lane_spans_by_source(Lane::Audio),
224+ reloaded.lane_spans_by_source(Lane::A1),
225225 reloaded.sources().to_vec(),
226226 reloaded.timeline_duration()
227227 ),
crates/engine/tests/export.rsmodified+3 -3
@@ -644,7 +644,7 @@ fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() {
644644 let source = asset("test_av.mp4");
645645 let mut session = PlaybackSession::open(&source).expect("open source");
646646 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");
648648 session.pause();
649649 let out = out_path("leading_gap");
650650 let handle = session.export_to(&out);
@@ -695,8 +695,8 @@ fn exports_a_gapped_timeline_as_black_and_silence() {
695695 assert!(session.cut_at(2.0), "split at 2 s");
696696 // Lift the middle out of *both* lanes: one second of black and silence in
697697 // the middle of a five-second timeline, with the length unchanged.
698- assert!(session.lift_clip(Lane::Video, 1));
699- assert!(session.lift_clip(Lane::Audio, 1));
698+ assert!(session.lift_clip(Lane::V1, 1));
699+ assert!(session.lift_clip(Lane::A1, 1));
700700 session.pause();
701701 let timeline = session.timeline_duration();
702702 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() {
935935 assert!(session.cut_at(2.0), "split at 2 s");
936936 assert!(session.cut_at(3.5), "split at 3.5 s");
937937 assert!(
938- session.lift_clip(Lane::Video, 1),
938+ session.lift_clip(Lane::V1, 1),
939939 "lift the middle picture out"
940940 );
941941 assert_eq!(
@@ -997,10 +997,7 @@ fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
997997 assert!(session.cut_at(1.0), "split at 1 s");
998998 assert!(session.cut_at(2.0), "split at 2 s");
999999 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1000- assert!(
1001- session.lift_clip(Lane::Audio, 1),
1002- "lift the middle sound out"
1003- );
1000+ assert!(session.lift_clip(Lane::A1, 1), "lift the middle sound out");
10041001 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
10051002 let duration = session.timeline_duration();
10061003
crates/engine/tests/saveload.rsmodified+1 -1
@@ -147,7 +147,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_3() {
147147 "v1 clips queue up, the second starting where the first ended"
148148 );
149149 assert_eq!(
150- loaded.lane_spans_by_source(engine::project::Lane::Audio),
150+ loaded.lane_spans_by_source(engine::project::Lane::A1),
151151 loaded.clip_spans_by_source(),
152152 "both lanes, fully grouped: a v1 timeline had no holes"
153153 );