forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-af1c01f7e54512ee9'

Browse files at this commit

f1ceaf327d137ebe7a3403014001cab38e872fe6Ahmet Kaan GümüşParent: 3395f94b6604dc
crates/engine/src/edith.rsmodified+273 -82
@@ -1,13 +1,14 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 34+//! edith 4
5 //! playhead 905 //! playhead 90
6 //! source 0 test_av.mp46 //! source 0 test_av.mp4
7 //! source 1 /elsewhere/test_av2.mp47 //! source 1 /elsewhere/test_av2.mp4
8-//! video 0 0 120 0 08+//! video 1 0 0 120 0 0
9-//! audio 0 0 120 0 09+//! audio 1 0 0 120 0 0
10-//! video 120 0 120 1 -10+//! video 2 120 0 120 1 -
11+//! audio 2
11 //! ```12 //! ```
12 //!13 //!
13 //! A source line is `source <audio stream> <path>`: which of the file's audio14 //! A source line is `source <audio stream> <path>`: which of the file's audio
@@ -16,18 +17,27 @@
16 //! stream first because a path runs to the end of the line (it may hold17 //! stream first because a path runs to the end of the line (it may hold
17 //! spaces) and an optional *trailing* field could not be told from one.18 //! spaces) and an optional *trailing* field could not be told from one.
18 //!19 //!
19-//! A lane line is `<lane> <start> <in> <out> <source> <link>`: where the clip20+//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link>`: which lane
20-//! sits on the timeline, the half-open source range it plays, the file it plays21+//! the clip is on -- its kind and its 1-based number among the lanes of that
21-//! from, and its group id (`-` for none). Timeline placement is explicit, so a22+//! kind, the [`crate::project::Lane::label`] a header column shows -- then where
22-//! *gap* is simply a stretch no line covers -- there is nothing to write for23+//! the clip sits on the timeline, the half-open source range it plays, the file
23-//! one, and nothing that can disagree about its length.24+//! it plays from, and its group id (`-` for none). Timeline placement is
25+//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
26+//! to write for one, and nothing that can disagree about its length.
24 //!27 //!
25-//! **Version 2** wrote `source <path>`, which is this file's stream 0 -- one28+//! A lane is declared by the clips on it, in the order the lanes are displayed
26-//! per file, whichever audio track came first. **Version 1** wrote that and one29+//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
27-//! lane, queued end to end: `clip <in> <out> <source>`. Both still load -- a v130+//! is the only way an empty lane could still be there on the way back. A lane
28-//! file's clips are laid out cumulatively and copied onto both lanes as one31+//! number may not skip one of its kind.
29-//! group each, which is exactly what a v1 timeline meant -- and saving either32+//!
30-//! again writes v3. An older reader refuses a newer file by name.33+//! **Version 3** was this without the lane number, and held one video lane and
34+//! one audio lane, no more. **Version 2** wrote `source <path>` as well, which
35+//! is this file's stream 0 -- one per file, whichever audio track came first.
36+//! **Version 1** wrote that and one lane, queued end to end: `clip <in> <out>
37+//! <source>`. All three still load -- a v1 file's clips are laid out
38+//! cumulatively and copied onto both lanes as one group each, which is exactly
39+//! what a v1 timeline meant -- and saving any of them writes v4. An older
40+//! reader refuses a newer file by name.
31 //!41 //!
32 //! Text because an edit list is a few integers and a path, and a path is42 //! Text because an edit list is a few integers and a path, and a path is
33 //! *bytes* on this platform -- a JSON string would have to lossily decode one.43 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -53,11 +63,12 @@ use std::io::Write;
53 use std::os::unix::ffi::{OsStrExt, OsStringExt};63 use std::os::unix::ffi::{OsStrExt, OsStringExt};
54 use std::path::{Path, PathBuf};64 use std::path::{Path, PathBuf};
55 65
56-use crate::project::{Clip, Source};66+use crate::project::{Clip, Lane, LaneKind, Source};
57 67
58 /// What [`save`] writes. Read support goes back to `edith 1`; see the module68 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
59 /// docs for what those dialects looked like.69 /// docs for what those dialects looked like.
60-const MAGIC: &[u8] = b"edith 3";70+const MAGIC: &[u8] = b"edith 4";
71+const MAGIC_V3: &[u8] = b"edith 3";
61 const MAGIC_V2: &[u8] = b"edith 2";72 const MAGIC_V2: &[u8] = b"edith 2";
62 const MAGIC_V1: &[u8] = b"edith 1";73 const MAGIC_V1: &[u8] = b"edith 1";
63 74
@@ -68,8 +79,10 @@ pub struct Document {
68 /// Paths absolute, relative entries already joined to the file's own79 /// Paths absolute, relative entries already joined to the file's own
69 /// directory.80 /// directory.
70 pub sources: Vec<Source>,81 pub sources: Vec<Source>,
71- pub video: Vec<Clip>,82+ /// Every lane, in display order, which is the order
72- pub audio: Vec<Clip>,83+ /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
84+ /// `A1` -- for every dialect before v4.
85+ pub lanes: Vec<(LaneKind, Vec<Clip>)>,
73 pub playhead: u32,86 pub playhead: u32,
74 }87 }
75 88
@@ -78,8 +91,7 @@ pub struct Document {
78 pub fn save(91 pub fn save(
79 path: &Path,92 path: &Path,
80 sources: &[Source],93 sources: &[Source],
81- video: &[Clip],94+ lanes: &[(LaneKind, Vec<Clip>)],
82- audio: &[Clip],
83 playhead: u32,95 playhead: u32,
84 ) -> crate::Result<()> {96 ) -> crate::Result<()> {
85 let dir = project_dir(path);97 let dir = project_dir(path);
@@ -92,7 +104,7 @@ pub fn save(
92 // the second one puts the name itself there.104 // the second one puts the name itself there.
93 let result = std::fs::File::create(&part)105 let result = std::fs::File::create(&part)
94 .and_then(|mut f| {106 .and_then(|mut f| {
95- f.write_all(&emit(&dir, sources, video, audio, playhead))?;107+ f.write_all(&emit(&dir, sources, lanes, playhead))?;
96 f.sync_all()108 f.sync_all()
97 })109 })
98 .and_then(|()| std::fs::rename(&part, path))110 .and_then(|()| std::fs::rename(&part, path))
@@ -122,7 +134,12 @@ fn project_dir(path: &Path) -> PathBuf {
122 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())134 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
123 }135 }
124 136
125-fn emit(dir: &Path, sources: &[Source], video: &[Clip], audio: &[Clip], playhead: u32) -> Vec<u8> {137+fn emit(
138+ dir: &Path,
139+ sources: &[Source],
140+ lanes: &[(LaneKind, Vec<Clip>)],
141+ playhead: u32,
142+) -> Vec<u8> {
126 let mut out = Vec::new();143 let mut out = Vec::new();
127 out.extend_from_slice(MAGIC);144 out.extend_from_slice(MAGIC);
128 out.push(b'\n');145 out.push(b'\n');
@@ -132,14 +149,31 @@ fn emit(dir: &Path, sources: &[Source], video: &[Clip], audio: &[Clip], playhead
132 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);149 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
133 out.push(b'\n');150 out.push(b'\n');
134 }151 }
135- // Lane by lane rather than interleaved by time: a lane reads as a list, and152+ // Lane by lane rather than interleaved by time: a lane reads as a list, the
136- // the parser gets its sortedness check for free from the order it is in.153+ // parser gets its sortedness check for free from the order it is in, and
137- for (keyword, clips) in [("video", video), ("audio", audio)] {154+ // the lanes come back out in the order they are displayed in.
155+ let (mut video, mut audio) = (0, 0);
156+ for (kind, clips) in lanes {
157+ let (keyword, ord) = match kind {
158+ LaneKind::Video => {
159+ video += 1;
160+ ("video", video)
161+ }
162+ LaneKind::Audio => {
163+ audio += 1;
164+ ("audio", audio)
165+ }
166+ };
167+ // A lane is declared by its clips; one holding nothing has to say so on
168+ // a line of its own, or the lane itself would not survive the round trip.
169+ if clips.is_empty() {
170+ out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
171+ }
138 for c in clips {172 for c in clips {
139 let link = c.link.map_or("-".to_string(), |l| l.to_string());173 let link = c.link.map_or("-".to_string(), |l| l.to_string());
140 out.extend_from_slice(174 out.extend_from_slice(
141 format!(175 format!(
142- "{keyword} {} {} {} {} {link}\n",176+ "{keyword} {ord} {} {} {} {} {link}\n",
143 c.start, c.in_frame, c.out_frame, c.source177 c.start, c.in_frame, c.out_frame, c.source
144 )178 )
145 .as_bytes(),179 .as_bytes(),
@@ -159,7 +193,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
159 // The dialects that wrote a source line without its stream field. Reading193 // The dialects that wrote a source line without its stream field. Reading
160 // one is the whole of what "an old project still opens" means here.194 // one is the whole of what "an old project still opens" means here.
161 let streamless = v1 || first == MAGIC_V2;195 let streamless = v1 || first == MAGIC_V2;
162- if first != MAGIC && !streamless {196+ // ...and the one that numbers its lanes. Every older one held two.
197+ let v4 = first == MAGIC;
198+ if !v4 && !streamless && first != MAGIC_V3 {
163 return Err(match first.strip_prefix(b"edith ") {199 return Err(match first.strip_prefix(b"edith ") {
164 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),200 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
165 None => "line 1: not a edith file".to_string(),201 None => "line 1: not a edith file".to_string(),
@@ -169,8 +205,13 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
169 205
170 let mut doc = Document {206 let mut doc = Document {
171 sources: Vec::new(),207 sources: Vec::new(),
172- video: Vec::new(),208+ // v4 declares its lanes as they come; every dialect before it held
173- audio: Vec::new(),209+ // exactly `V1` and `A1`, either of which could be empty.
210+ lanes: if v4 {
211+ Vec::new()
212+ } else {
213+ vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
214+ },
174 playhead: 0,215 playhead: 0,
175 };216 };
176 let mut playhead_seen = false;217 let mut playhead_seen = false;
@@ -194,7 +235,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
194 playhead_seen = true;235 playhead_seen = true;
195 }236 }
196 b"source" => {237 b"source" => {
197- if !doc.video.is_empty() || !doc.audio.is_empty() {238+ if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
198 return Err(format!("line {n}: source after a clip").into());239 return Err(format!("line {n}: source after a clip").into());
199 }240 }
200 // The stream comes first and the path is everything after it,241 // The stream comes first and the path is everything after it,
@@ -237,16 +278,35 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
237 in_frame: number(f[0], n)?,278 in_frame: number(f[0], n)?,
238 out_frame: number(f[1], n)?,279 out_frame: number(f[1], n)?,
239 source: number(f[2], n)? as usize,280 source: number(f[2], n)? as usize,
240- link: Some(doc.video.len() as u32),281+ link: Some(doc.lanes[0].1.len() as u32),
241 },282 },
242 &doc,283 &doc,
243 n,284 n,
244 )?;285 )?;
245 queued = clip.end();286 queued = clip.end();
246- doc.video.push(clip);287+ doc.lanes[0].1.push(clip);
247- doc.audio.push(clip);288+ doc.lanes[1].1.push(clip);
248 }289 }
249 b"video" | b"audio" if !v1 => {290 b"video" | b"audio" if !v1 => {
291+ let kind = match keyword {
292+ b"video" => LaneKind::Video,
293+ _ => LaneKind::Audio,
294+ };
295+ // v4 names the lane, and a line naming nothing else is an empty
296+ // lane's whole existence. Older dialects had one lane per kind.
297+ let (ord, rest) = if v4 {
298+ let at = rest.iter().position(|&b| b == b' ');
299+ (
300+ number(&rest[..at.unwrap_or(rest.len())], n)?,
301+ &rest[at.map_or(rest.len(), |at| at + 1)..],
302+ )
303+ } else {
304+ (1, rest)
305+ };
306+ let at = lane_of(&mut doc.lanes, kind, ord, n)?;
307+ if v4 && rest.is_empty() {
308+ continue;
309+ }
250 let f = fields(rest, 5, "clip", n)?;310 let f = fields(rest, 5, "clip", n)?;
251 let clip = check(311 let clip = check(
252 Clip {312 Clip {
@@ -262,10 +322,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
262 &doc,322 &doc,
263 n,323 n,
264 )?;324 )?;
265- let lane = match keyword {325+ let lane = &mut doc.lanes[at].1;
266- b"video" => &mut doc.video,
267- _ => &mut doc.audio,
268- };
269 // The sorted, non-overlapping placement invariant, checked at326 // The sorted, non-overlapping placement invariant, checked at
270 // the only door untrusted clips come in through.327 // the only door untrusted clips come in through.
271 if lane.last().is_some_and(|prev| prev.end() > clip.start) {328 if lane.last().is_some_and(|prev| prev.end() > clip.start) {
@@ -289,12 +346,45 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
289 }346 }
290 }347 }
291 }348 }
292- if doc.video.is_empty() && doc.audio.is_empty() {349+ if doc.lanes.iter().all(|(_, clips)| clips.is_empty()) {
293 return Err("no clips: an empty timeline is not a project".into());350 return Err("no clips: an empty timeline is not a project".into());
294 }351 }
295 Ok(doc)352 Ok(doc)
296 }353 }
297 354
355+/// Where the lane a v4 line names sits, appending it if this is its first line.
356+/// Lanes arrive in display order, so a number that skips one of its kind is a
357+/// lane that was never declared, and is refused by the name it would have had.
358+fn lane_of(
359+ lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
360+ kind: LaneKind,
361+ ord: u32,
362+ line: usize,
363+) -> crate::Result<usize> {
364+ let mut seen = 0;
365+ for (at, (k, _)) in lanes.iter().enumerate() {
366+ if *k == kind {
367+ seen += 1;
368+ if seen == ord {
369+ return Ok(at);
370+ }
371+ }
372+ }
373+ if ord != seen + 1 {
374+ return Err(match ord.checked_sub(1) {
375+ Some(prev) => format!(
376+ "line {line}: lane {} comes before {}",
377+ Lane::new(kind, prev as usize).label(),
378+ Lane::new(kind, seen as usize).label()
379+ ),
380+ None => format!("line {line}: lane numbers start at 1"),
381+ }
382+ .into());
383+ }
384+ lanes.push((kind, Vec::new()));
385+ Ok(lanes.len() - 1)
386+}
387+
298 /// Splits a line's fields, refusing the wrong count by name.388 /// Splits a line's fields, refusing the wrong count by name.
299 fn fields<'a>(389 fn fields<'a>(
300 rest: &'a [u8],390 rest: &'a [u8],
@@ -413,47 +503,139 @@ mod tests {
413 }503 }
414 }504 }
415 505
416- fn doc() -> (PathBuf, Vec<Source>, Vec<Clip>, Vec<Clip>) {506+ /// Lanes in display order, as [`Document::lanes`] holds them.
507+ type Lanes = Vec<(LaneKind, Vec<Clip>)>;
508+
509+ /// `V1` then `A1`, the shape every dialect before v4 held.
510+ fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
511+ vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
512+ }
513+
514+ fn doc() -> (PathBuf, Vec<Source>, Lanes) {
417 (515 (
418 PathBuf::from("/proj"),516 PathBuf::from("/proj"),
419 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],517 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
420- vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],518+ two(
421- vec![clip(0, 0, 30, 0, Some(0))],519+ vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
520+ vec![clip(0, 0, 30, 0, Some(0))],
521+ ),
422 )522 )
423 }523 }
424 524
425 #[test]525 #[test]
426 fn relative_and_absolute_paths_round_trip() {526 fn relative_and_absolute_paths_round_trip() {
427- let (dir, sources, video, audio) = doc();527+ let (dir, sources, lanes) = doc();
428- let bytes = emit(&dir, &sources, &video, &audio, 12);528+ let bytes = emit(&dir, &sources, &lanes, 12);
429 assert_eq!(529 assert_eq!(
430 String::from_utf8_lossy(&bytes),530 String::from_utf8_lossy(&bytes),
431- "edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\531+ "edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
432- video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n",532+ video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n",
433 "the file under the project directory is written relative to it, \533 "the file under the project directory is written relative to it, \
434 each with the audio stream it plays"534 each with the audio stream it plays"
435 );535 );
436 let back = parse(&bytes, &dir).expect("parse");536 let back = parse(&bytes, &dir).expect("parse");
437 assert_eq!(back.sources, sources, "relative entries rejoin the dir");537 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
438- assert_eq!(back.video, video);
439 assert_eq!(538 assert_eq!(
440- back.audio, audio,539+ back.lanes, lanes,
441- "the trailing gap needs no line of its own"540+ "both lanes, in display order; the trailing gap needs no line"
442 );541 );
443 assert_eq!(back.playhead, 12);542 assert_eq!(back.playhead, 12);
444 // ...and emitting the parsed document reproduces the same bytes.543 // ...and emitting the parsed document reproduces the same bytes.
544+ assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes);
545+ }
546+
547+ /// The whole of the bump: a project of any number of lanes writes and reads
548+ /// back, in display order, empty lanes and cross-lane groups included.
549+ #[test]
550+ fn any_number_of_lanes_round_trips() {
551+ let dir = PathBuf::from("/proj");
552+ let sources = vec![source("/proj/a.mp4", 0)];
553+ // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
554+ // shows, not video-then-audio -- with one take grouped across V1 and A2
555+ // (no paired ord, the lanes between them empty of it) and an A1 holding
556+ // nothing at all.
557+ let lanes = vec![
558+ (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
559+ (LaneKind::Audio, Vec::new()),
560+ (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
561+ (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
562+ ];
563+ let bytes = emit(&dir, &sources, &lanes, 7);
445 assert_eq!(564 assert_eq!(
446- emit(&dir, &back.sources, &back.video, &back.audio, back.playhead),565+ String::from_utf8_lossy(&bytes),
447- bytes566+ "edith 4\nplayhead 7\nsource 0 a.mp4\n\
567+ video 1 0 0 30 0 4\naudio 1\nvideo 2 40 0 10 0 -\naudio 2 0 0 30 0 4\n",
568+ "an empty lane is a line of its own; everything else is its clips"
569+ );
570+ let back = parse(&bytes, &dir).expect("parse");
571+ assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
572+ assert_eq!(back.playhead, 7);
573+ assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes);
574+
575+ // A lane number may not skip one of its kind: that lane was declared by
576+ // nothing, and the refusal names it.
577+ for (file, want) in [
578+ (
579+ "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
580+ "line 3: lane V2 comes before V1",
581+ ),
582+ (
583+ "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
584+ "line 4: lane A3 comes before A1",
585+ ),
586+ (
587+ "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
588+ "line 3: lane numbers start at 1",
589+ ),
590+ // The clip fields are still the clip fields, one lane number on.
591+ (
592+ "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
593+ "line 3: clip wants 5 fields, found 4",
594+ ),
595+ // ...and a v4 line in a v3 file reads as the garbled clip it is.
596+ (
597+ "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
598+ "line 3: clip wants 5 fields, found 6",
599+ ),
600+ ] {
601+ assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
602+ }
603+ // Lanes and nothing on them is not a project.
604+ assert_eq!(
605+ parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir)
606+ .unwrap_err()
607+ .to_string(),
608+ "no clips: an empty timeline is not a project"
448 );609 );
449 }610 }
450 611
451- /// The other half of the compatibility promise: a v2 file names no audio612+ /// The other half of the compatibility promise: a v3 file is a v4 one
452- /// stream and means stream 0 -- what the whole dialect could play -- and613+ /// without the lane numbers, and a v2 file names no audio stream and means
453- /// saving it again writes v3 saying so, with nothing else changed.614+ /// stream 0 -- what the whole dialect could play. Both load as the two lanes
615+ /// they always were, and saving either writes v4 with nothing else changed.
454 #[test]616 #[test]
455- fn a_v2_file_loads_as_stream_0() {617+ fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
456 let dir = PathBuf::from("/proj");618 let dir = PathBuf::from("/proj");
619+ let (_, _, lanes) = doc();
620+ let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
621+ video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
622+ let old = parse(v3, &dir).expect("v3 parses");
623+ assert_eq!(
624+ (&old.sources, &old.lanes, old.playhead),
625+ (
626+ &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
627+ &lanes,
628+ 12
629+ ),
630+ "a v3 file loads as exactly the state its v4 twin does"
631+ );
632+ // ...and re-saved it *is* that twin: the magic and a lane number per
633+ // clip line, and not one byte else.
634+ assert_eq!(
635+ emit(&dir, &old.sources, &old.lanes, old.playhead),
636+ emit(&dir, &old.sources, &lanes, 12),
637+ );
638+
457 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\639 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
458 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";640 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
459 let back = parse(v2, &dir).expect("v2 parses");641 let back = parse(v2, &dir).expect("v2 parses");
@@ -461,40 +643,43 @@ mod tests {
461 back.sources,643 back.sources,
462 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],644 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
463 );645 );
464- let (_, _, video, audio) = doc();646+ assert_eq!(back.lanes, lanes);
465- assert_eq!((&back.video, &back.audio), (&video, &audio));
466 647
467- let v3 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);648+ let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead);
468 assert_eq!(649 assert_eq!(
469- String::from_utf8_lossy(&v3),650+ String::from_utf8_lossy(&v4),
470- "edith 3\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\651+ "edith 4\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
471- video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n",652+ video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n",
472- "a re-saved v2 project differs only by its version and the streams \653+ "a re-saved v2 project differs only by its version, the lane \
473- it always meant"654+ numbers and the streams it always meant"
474 );655 );
475- let again = parse(&v3, &dir).expect("v3 parses");656+ let again = parse(&v4, &dir).expect("v4 parses");
476 assert_eq!(again.sources, back.sources);657 assert_eq!(again.sources, back.sources);
477 }658 }
478 659
479 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of660 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
480- /// lanes, and saving it again writes v3.661+ /// lanes, and saving it again writes v4.
481 #[test]662 #[test]
482 fn a_v1_file_loads_as_two_grouped_lanes() {663 fn a_v1_file_loads_as_two_grouped_lanes() {
483 let dir = PathBuf::from("/proj");664 let dir = PathBuf::from("/proj");
484 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";665 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
485 let back = parse(v1, &dir).expect("v1 parses");666 let back = parse(v1, &dir).expect("v1 parses");
486 assert_eq!(667 assert_eq!(
487- back.video,668+ back.lanes[0].1,
488 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],669 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
489 "v1 clips queue up: the second starts where the first ended"670 "v1 clips queue up: the second starts where the first ended"
490 );671 );
491- assert_eq!(back.audio, back.video, "one take per clip, on both lanes");672+ assert_eq!(
673+ back.lanes,
674+ two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
675+ "one take per clip, on both lanes"
676+ );
492 assert_eq!(back.playhead, 5);677 assert_eq!(back.playhead, 5);
493- // Saved again it is v3, and that round-trips to the same document.678+ // Saved again it is v4, and that round-trips to the same document.
494- let v3 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);679+ let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead);
495- assert!(v3.starts_with(b"edith 3\n"));680+ assert!(v4.starts_with(b"edith 4\n"));
496- let again = parse(&v3, &dir).expect("v3 parses");681+ let again = parse(&v4, &dir).expect("v4 parses");
497- assert_eq!((again.video, again.audio), (back.video, back.audio));682+ assert_eq!(again.lanes, back.lanes);
498 // A dialect may not be mixed: lane lines under v1, `clip` under v2.683 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
499 for (bytes, want) in [684 for (bytes, want) in [
500 (685 (
@@ -532,7 +717,7 @@ mod tests {
532 );717 );
533 // ...and a lane may be empty as long as the other one is not.718 // ...and a lane may be empty as long as the other one is not.
534 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");719 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
535- assert!(only_audio.video.is_empty());720+ assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
536 }721 }
537 722
538 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug723 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
@@ -581,11 +766,11 @@ mod tests {
581 path: source,766 path: source,
582 audio_stream: 1,767 audio_stream: 1,
583 };768 };
584- save(&path, &[entry], &one, &one, 0).expect("save");769+ save(&path, &[entry], &two(one.to_vec(), one.to_vec()), 0).expect("save");
585 let bytes = std::fs::read(&path).expect("read back");770 let bytes = std::fs::read(&path).expect("read back");
586 assert_eq!(771 assert_eq!(
587 String::from_utf8_lossy(&bytes),772 String::from_utf8_lossy(&bytes),
588- "edith 3\nplayhead 0\nsource 1 a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n"773+ "edith 4\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 -\naudio 1 0 0 30 0 -\n"
589 );774 );
590 // Loading rejoins the *given* directory, so the file is reached by the775 // Loading rejoins the *given* directory, so the file is reached by the
591 // way the project was opened -- the same file, through the link, still776 // way the project was opened -- the same file, through the link, still
@@ -608,11 +793,17 @@ mod tests {
608 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),793 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
609 audio_stream: 0,794 audio_stream: 0,
610 };795 };
611- let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 0, 5, 0, None)], &[], 0);796+ let bytes = emit(
797+ &dir,
798+ &[nasty.clone()],
799+ &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
800+ 0,
801+ );
612 assert_eq!(802 assert_eq!(
613 bytes.iter().filter(|&&b| b == b'\n').count(),803 bytes.iter().filter(|&&b| b == b'\n').count(),
614- 4,804+ 5,
615- "the escaped newline must not become a line break"805+ "the escaped newline must not become a line break: magic, playhead, \
806+ source, the clip, and the empty audio lane's own line"
616 );807 );
617 let back = parse(&bytes, &dir).expect("parse");808 let back = parse(&bytes, &dir).expect("parse");
618 // The spaces in it are the reason the stream field leads rather than809 // The spaces in it are the reason the stream field leads rather than
@@ -623,10 +814,10 @@ mod tests {
623 #[test]814 #[test]
624 fn a_wrong_first_line_is_refused_by_name() {815 fn a_wrong_first_line_is_refused_by_name() {
625 let dir = PathBuf::from("/proj");816 let dir = PathBuf::from("/proj");
626- let err = parse(b"edith 4\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)817+ let err = parse(b"edith 5\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
627 .unwrap_err()818 .unwrap_err()
628 .to_string();819 .to_string();
629- assert_eq!(err, "line 1: unsupported version 4");820+ assert_eq!(err, "line 1: unsupported version 5");
630 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {821 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
631 assert_eq!(822 assert_eq!(
632 parse(junk, &dir).unwrap_err().to_string(),823 parse(junk, &dir).unwrap_err().to_string(),
@@ -704,8 +895,8 @@ mod tests {
704 /// Every truncation of a good file either parses or refuses; none panics.895 /// Every truncation of a good file either parses or refuses; none panics.
705 #[test]896 #[test]
706 fn truncations_never_panic() {897 fn truncations_never_panic() {
707- let (dir, sources, video, audio) = doc();898+ let (dir, sources, lanes) = doc();
708- let bytes = emit(&dir, &sources, &video, &audio, 12);899+ let bytes = emit(&dir, &sources, &lanes, 12);
709 for cut in 0..bytes.len() {900 for cut in 0..bytes.len() {
710 let _ = parse(&bytes[..cut], &dir);901 let _ = parse(&bytes[..cut], &dir);
711 // ...and the same file with a byte lopped off the front, which902 // ...and the same file with a byte lopped off the front, which
crates/engine/src/playback.rsmodified+12 -7
@@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24 use crate::decode::{DecodeSession, Frame, Worker};24 use crate::decode::{DecodeSession, Frame, Worker};
25 use crate::demux::{Demuxer, VideoMeta};25 use crate::demux::{Demuxer, VideoMeta};
26-use crate::project::{Clip, Lane, Project, Source, Span};26+use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
27 27
28 /// How long the feeder waits out a full ring. The ring holds a second, so this28 /// How long the feeder waits out a full ring. The ring holds a second, so this
29 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.29 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
@@ -219,16 +219,21 @@ impl PlaybackSession {
219 // (or hand-edited) project files are the one door this can come in219 // (or hand-edited) project files are the one door this can come in
220 // through, so it is refused by name here rather than becoming a clip220 // through, so it is refused by name here rather than becoming a clip
221 // that decodes to nothing.221 // that decodes to nothing.
222- for clip in &doc.video {222+ for clip in doc
223+ .lanes
224+ .iter()
225+ .filter(|(kind, _)| *kind == LaneKind::Video)
226+ .flat_map(|(_, clips)| clips)
227+ {
223 if crate::is_audio(&doc.sources[clip.source].path) {228 if crate::is_audio(&doc.sources[clip.source].path) {
224 return Err(format!(229 return Err(format!(
225- "{} has no picture: it can only play on the audio lane",230+ "{} has no picture: it can only play on an audio lane",
226 doc.sources[clip.source].path.display()231 doc.sources[clip.source].path.display()
227 )232 )
228 .into());233 .into());
229 }234 }
230 }235 }
231- for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {236+ for (i, clip) in doc.lanes.iter().flat_map(|(_, clips)| clips).enumerate() {
232 if clip.out_frame > counts[clip.source] {237 if clip.out_frame > counts[clip.source] {
233 return Err(format!(238 return Err(format!(
234 "clip {i} ends at frame {} but {} has {} frames",239 "clip {i} ends at frame {} but {} has {} frames",
@@ -241,7 +246,7 @@ impl PlaybackSession {
241 }246 }
242 247
243 let playhead = doc.playhead;248 let playhead = doc.playhead;
244- let project = Project::from_parts(doc.sources, doc.video, doc.audio)?;249+ let project = Project::from_parts(doc.sources, doc.lanes)?;
245 let span = project.span_at(Lane::V1, 0).expect("never empty");250 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: the251 // 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) and252 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -295,10 +300,10 @@ impl PlaybackSession {
295 /// [`crate::edith`]). Sources no clip plays from are left out, and the300 /// [`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.301 /// playhead is saved with it so a reopened project resumes where it stood.
297 pub fn save_project(&self, path: &Path) -> crate::Result<()> {302 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
298- let (sources, video, audio) = self.project.without_orphan_sources()?;303+ let (sources, lanes) = self.project.without_orphan_sources();
299 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)304 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
300 .min(self.project.timeline_frames().saturating_sub(1));305 .min(self.project.timeline_frames().saturating_sub(1));
301- crate::edith::save(path, &sources, &video, &audio, playhead)306+ crate::edith::save(path, &sources, &lanes, playhead)
302 }307 }
303 308
304 /// The next decoded frame, its `index` rewritten from a source frame to a309 /// The next decoded frame, its `index` rewritten from a source frame to a
crates/engine/src/project.rsmodified+123 -99
@@ -157,9 +157,8 @@ struct LaneData {
157 }157 }
158 158
159 impl LaneData {159 impl LaneData {
160- /// The two lanes a project starts with and the only two a `.edith` file160+ /// The two lanes a project starts with: `V1` then `A1`, in display order.
161- /// holds: `V1` then `A1`, in display order. One place, because every door161+ /// One place, because a freshly opened file is exactly this pair.
162- /// that builds a project from the outside builds exactly this pair.
163 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {162 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
164 vec![163 vec![
165 LaneData {164 LaneData {
@@ -235,24 +234,26 @@ impl Project {
235 }234 }
236 235
237 /// A project rebuilt from a saved edit list -- the load half of236 /// A project rebuilt from a saved edit list -- the load half of
238- /// [`crate::edith`], which is a two-lane format, so this door takes `V1` and237+ /// [`crate::edith`]. The lanes come in display order, each with its kind, and
239- /// `A1` and nothing else (see [`Project::without_orphan_sources`], which238+ /// an `ord` is a lane's position among the lanes of that kind, exactly as
240- /// refuses to *write* more). History is *not* saved, so [`Project::undo`] is239+ /// [`Project::lanes`] hands them back. History is *not* saved, so
241- /// `false` until the first edit of the new session. This is the one door240+ /// [`Project::undo`] is `false` until the first edit of the new session.
242- /// untrusted parts come in through, so every invariant every other241+ /// This is the one door untrusted parts come in through, so every invariant
243- /// constructor keeps is checked here, by name and in release: both lanes242+ /// every other constructor keeps is checked here, by name and in release:
244- /// empty, an empty clip, a clip naming a source that is not there, a clip243+ /// every lane empty, an empty clip, a clip naming a source that is not
245- /// whose end overflows, a lane that is unsorted or self-overlapping, and244+ /// there, a clip whose end overflows, a lane that is unsorted or
246- /// the grouping rules of [`Clip::link`] below.245+ /// self-overlapping, and the grouping rules of [`Clip::link`] below.
247 pub fn from_parts(246 pub fn from_parts(
248 sources: Vec<Source>,247 sources: Vec<Source>,
249- video: Vec<Clip>,248+ lanes: Vec<(LaneKind, Vec<Clip>)>,
250- audio: Vec<Clip>,
251 ) -> crate::Result<Self> {249 ) -> crate::Result<Self> {
252- if video.is_empty() && audio.is_empty() {250+ if lanes.iter().all(|(_, clips)| clips.is_empty()) {
253- return Err("both lanes are empty: that is not a project".into());251+ return Err("every lane is empty: that is not a project".into());
254 }252 }
255- let lanes = LaneData::two_lanes(video, audio);253+ let lanes: Vec<LaneData> = lanes
254+ .into_iter()
255+ .map(|(kind, clips)| LaneData { kind, clips })
256+ .collect();
256 for (data, lane) in lanes.iter().zip(handles(&lanes)) {257 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
257 let name = lane.label();258 let name = lane.label();
258 for c in &data.clips {259 for c in &data.clips {
@@ -421,29 +422,13 @@ impl Project {
421 /// [`Project::append_clip`]), so an undone import leaves an orphan source422 /// [`Project::append_clip`]), so an undone import leaves an orphan source
422 /// entry behind; writing that orphan to a project file would let a file423 /// entry behind; writing that orphan to a project file would let a file
423 /// nothing plays refuse a future load. New indexes are assigned in order of424 /// nothing plays refuse a future load. New indexes are assigned in order of
424- /// first use -- video lane first, then audio -- so the same project always425+ /// first use -- lane by lane, in display order -- so the same project always
425 /// emits the same bytes.426 /// emits the same bytes.
426 ///427 ///
427- /// Refused, by name, for a timeline with more than one lane of a kind: the428+ /// Every lane comes out, in display order and with its kind: that is what a
428- /// `.edith` format has one line keyword per kind, so writing a third lane429+ /// v4 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
429- /// would silently drop it. The model runs ahead of the format here on430+ /// takes back.
430- /// purpose -- the bump is its own slice -- and a refused save is the one431+ pub fn without_orphan_sources(&self) -> (Vec<Source>, Vec<(LaneKind, Vec<Clip>)>) {
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- }
447 let mut moved = vec![None; self.sources.len()];432 let mut moved = vec![None; self.sources.len()];
448 let mut sources = Vec::new();433 let mut sources = Vec::new();
449 let mut lanes = self.lanes.clone();434 let mut lanes = self.lanes.clone();
@@ -458,14 +443,10 @@ impl Project {
458 }443 }
459 };444 };
460 }445 }
461- let (mut video, mut audio) = (Vec::new(), Vec::new());446+ (
462- for data in lanes {447+ sources,
463- match data.kind {448+ lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
464- LaneKind::Video => video = data.clips,449+ )
465- LaneKind::Audio => audio = data.clips,
466- }
467- }
468- Ok((sources, video, audio))
469 }450 }
470 451
471 /// Length of the timeline in frames: where the *last* lane runs out. A lane452 /// Length of the timeline in frames: where the *last* lane runs out. A lane
@@ -1015,6 +996,11 @@ mod tests {
1015 }996 }
1016 }997 }
1017 998
999+ /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
1000+ fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
1001+ vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
1002+ }
1003+
1018 /// Every lane with its group ids blanked, for comparing shape.1004 /// Every lane with its group ids blanked, for comparing shape.
1019 fn shape(p: &Project) -> Vec<Vec<Clip>> {1005 fn shape(p: &Project) -> Vec<Vec<Clip>> {
1020 p.lanes()1006 p.lanes()
@@ -1604,10 +1590,13 @@ mod tests {
1604 // Import a second file, undo it: source 1 is now an orphan.1590 // Import a second file, undo it: source 1 is now an orphan.
1605 let mut p = two_sources();1591 let mut p = two_sources();
1606 assert!(p.undo());1592 assert!(p.undo());
1607- let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");1593+ let (sources, lanes) = p.without_orphan_sources();
1608 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");1594 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
1609- assert_eq!(video, three().clips(), "the clips are untouched");1595+ assert_eq!(
1610- assert_eq!(audio, three().lane(Lane::A1));1596+ lanes,
1597+ two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
1598+ "the clips are untouched"
1599+ );
1611 1600
1612 // Three sources where only the middle one is orphaned: the survivors1601 // Three sources where only the middle one is orphaned: the survivors
1613 // renumber, and the clips follow.1602 // renumber, and the clips follow.
@@ -1615,31 +1604,35 @@ mod tests {
1615 assert_eq!(p.import(FILE2, 0), 1);1604 assert_eq!(p.import(FILE2, 0), 1);
1616 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);1605 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
1617 assert!(p.append_clip(2, 4));1606 assert!(p.append_clip(2, 4));
1618- let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");1607+ let (sources, lanes) = p.without_orphan_sources();
1619 assert_eq!(1608 assert_eq!(
1620 sources,1609 sources,
1621 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]1610 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
1622 );1611 );
1623- assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);1612+ assert_eq!(
1613+ lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
1614+ [0, 1]
1615+ );
1624 // ...and what comes out is loadable, with the same timeline.1616 // ...and what comes out is loadable, with the same timeline.
1625- let reloaded = Project::from_parts(sources, video, audio).expect("from_parts");1617+ let reloaded = Project::from_parts(sources, lanes).expect("from_parts");
1626 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());1618 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
1627 assert_eq!(reloaded.sources().len(), 2);1619 assert_eq!(reloaded.sources().len(), 2);
1628 }1620 }
1629 1621
1630 #[test]1622 #[test]
1631 fn from_parts_has_no_history_and_checks_the_invariants() {1623 fn from_parts_has_no_history_and_checks_the_invariants() {
1632- let (sources, video, audio) = three().without_orphan_sources().expect("two lanes");1624+ let (sources, lanes) = three().without_orphan_sources();
1633- let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone())1625+ let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
1634- .expect("valid parts");1626+ let mut p = Project::from_parts(sources.clone(), lanes.clone()).expect("valid parts");
1635 assert_eq!(p.clips(), three().clips());1627 assert_eq!(p.clips(), three().clips());
1636 assert!(!p.undo(), "a loaded project has nothing to undo");1628 assert!(!p.undo(), "a loaded project has nothing to undo");
1637 assert!(p.split(4), "...and is editable from there");1629 assert!(p.split(4), "...and is editable from there");
1638 assert!(p.undo());1630 assert!(p.undo());
1639 1631
1640- // A lane may be empty; both may not.1632+ // A lane may be empty; every lane may not, and neither may no lane.
1641- assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_ok());1633+ assert!(Project::from_parts(sources.clone(), two(video.clone(), Vec::new())).is_ok());
1642- assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err());1634+ assert!(Project::from_parts(sources.clone(), two(Vec::new(), Vec::new())).is_err());
1635+ assert!(Project::from_parts(sources.clone(), Vec::new()).is_err());
1643 let bad: [Vec<Clip>; 5] = [1636 let bad: [Vec<Clip>; 5] = [
1644 vec![clip(0, 0, 3, 1)], // source that is not there1637 vec![clip(0, 0, 3, 1)], // source that is not there
1645 vec![clip(0, 3, 3, 0)], // empty clip1638 vec![clip(0, 3, 3, 0)], // empty clip
@@ -1649,13 +1642,27 @@ mod tests {
1649 ];1642 ];
1650 for clips in bad {1643 for clips in bad {
1651 assert!(1644 assert!(
1652- Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_err(),1645+ Project::from_parts(sources.clone(), two(clips.clone(), Vec::new())).is_err(),
1653 "{clips:?}"1646 "{clips:?}"
1654 );1647 );
1655- assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_err());1648+ assert!(
1649+ Project::from_parts(sources.clone(), two(video.clone(), clips.clone())).is_err()
1650+ );
1651+ // ...and on a third lane, which is checked by the same walk.
1652+ assert!(
1653+ Project::from_parts(
1654+ sources.clone(),
1655+ vec![
1656+ (LaneKind::Video, video.clone()),
1657+ (LaneKind::Audio, audio.clone()),
1658+ (LaneKind::Video, clips),
1659+ ]
1660+ )
1661+ .is_err()
1662+ );
1656 }1663 }
1657 // Group ids survive a load, and the next split gets a fresh one.1664 // Group ids survive a load, and the next split gets a fresh one.
1658- let mut p = Project::from_parts(sources, video, audio).expect("valid parts");1665+ let mut p = Project::from_parts(sources, lanes).expect("valid parts");
1659 assert!(p.split(4));1666 assert!(p.split(4));
1660 assert!(p.clips().iter().all(|c| c.link.is_some()));1667 assert!(p.clips().iter().all(|c| c.link.is_some()));
1661 }1668 }
@@ -1681,7 +1688,7 @@ mod tests {
1681 1688
1682 // The door: named errors, one per cause.1689 // The door: named errors, one per cause.
1683 let err = |video: Vec<Clip>, audio: Vec<Clip>| {1690 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
1684- Project::from_parts(sources.clone(), video, audio)1691+ Project::from_parts(sources.clone(), two(video, audio))
1685 .expect_err("refused")1692 .expect_err("refused")
1686 .to_string()1693 .to_string()
1687 };1694 };
@@ -1698,9 +1705,9 @@ mod tests {
1698 // A one-sided link is *not* an error: it is what a lift leaves behind.1705 // A one-sided link is *not* an error: it is what a lift leaves behind.
1699 let mut p = Project::single(FILE, 9);1706 let mut p = Project::single(FILE, 9);
1700 assert!(p.lift(Lane::A1, 0));1707 assert!(p.lift(Lane::A1, 0));
1701- let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");1708+ let (sources, lanes) = p.clone().without_orphan_sources();
1702 assert!(1709 assert!(
1703- Project::from_parts(sources, video, audio).is_ok(),1710+ Project::from_parts(sources, lanes).is_ok(),
1704 "a lifted lane's project has to load again"1711 "a lifted lane's project has to load again"
1705 );1712 );
1706 1713
@@ -1769,7 +1776,7 @@ mod tests {
1769 &p,1776 &p,
1770 "a second audio stream of the same file, placed and split",1777 "a second audio stream of the same file, placed and split",
1771 );1778 );
1772- let (sources, ..) = p.without_orphan_sources().expect("two lanes");1779+ let (sources, _) = p.without_orphan_sources();
1773 assert_eq!(1780 assert_eq!(
1774 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),1781 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
1775 [0, 1],1782 [0, 1],
@@ -1819,18 +1826,27 @@ mod tests {
1819 }1826 }
1820 1827
1821 /// The save/load round trip a project must survive: the parts a save writes,1828 /// The save/load round trip a project must survive: the parts a save writes,
1822- /// handed back to the constructor a load goes through.1829+ /// handed back to the constructor a load goes through -- every lane of them,
1830+ /// and the reloaded timeline has to be the same lanes in the same order.
1823 fn reloads(p: &Project, what: &str) {1831 fn reloads(p: &Project, what: &str) {
1824- let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");1832+ let (sources, lanes) = p.clone().without_orphan_sources();
1825- if let Err(e) = Project::from_parts(sources, video, audio) {1833+ match Project::from_parts(sources, lanes) {
1826- panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes);1834+ Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
1835+ Ok(back) => {
1836+ assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
1837+ // Placements, not whole clips: an orphan prune renumbers the
1838+ // sources a clip names, which is the point of it.
1839+ let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
1840+ p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
1841+ };
1842+ assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
1843+ }
1827 }1844 }
1828 }1845 }
1829 1846
1830- /// What [`reloads`] proves for a timeline the file format cannot hold yet:1847+ /// The two invariants [`Project::from_parts`] checks that are about *lanes*
1831- /// the two invariants [`Project::from_parts`] checks that are about *lanes*
1832 /// -- each one sorted and disjoint, and one span per group id -- asserted1848 /// -- 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.1849+ /// directly, where the point is the invariant rather than the round trip.
1834 fn invariants_hold(p: &Project, what: &str) {1850 fn invariants_hold(p: &Project, what: &str) {
1835 for lane in p.lanes() {1851 for lane in p.lanes() {
1836 assert!(1852 assert!(
@@ -2045,44 +2061,51 @@ mod tests {
2045 );2061 );
2046 }2062 }
2047 2063
2048- /// The model runs ahead of the file format on purpose, so a save of what the2064+ /// Every lane a save writes comes out, in display order and with its kind --
2049- /// format cannot hold is refused by name rather than silently dropping a2065+ /// an empty one included, since it is state a front-end shows -- and a
2050- /// lane -- and a two-lane project still writes exactly the parts it always2066+ /// two-lane project still writes exactly the parts it always did.
2051- /// did.
2052 #[test]2067 #[test]
2053- fn a_save_refuses_more_lanes_than_the_format_holds() {2068+ fn a_save_writes_every_lane_it_has() {
2054 let mut p = three();2069 let mut p = three();
2055- let before = p.without_orphan_sources().expect("two lanes save");2070+ let before = p.without_orphan_sources();
2071+ assert_eq!(before.1.len(), 2, "V1 and A1");
2056 let v2 = p.add_lane(LaneKind::Video);2072 let v2 = p.add_lane(LaneKind::Video);
2057- let err = p.without_orphan_sources().expect_err("refused").to_string();2073+ assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
2058- assert!(2074+ let a2 = p.add_lane(LaneKind::Audio);
2059- err.contains("2 video lanes") && err.contains("newer format"),2075+ let (sources, lanes) = p.without_orphan_sources();
2060- "{err}"2076+ assert_eq!(
2077+ lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
2078+ [
2079+ LaneKind::Video,
2080+ LaneKind::Audio,
2081+ LaneKind::Video,
2082+ LaneKind::Audio
2083+ ],
2084+ "display order, not video-then-audio"
2061 );2085 );
2062- // Even empty: what cannot be written must not be quietly left behind.2086+ assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
2063- assert!(p.lane(v2).is_empty());2087+ assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
2064- assert!(p.undo(), "and the lane undoes");2088+ // ...and all four load again as the same four.
2089+ let back = Project::from_parts(sources, lanes).expect("four lanes load");
2090+ assert_eq!(back.lanes(), p.lanes());
2091+ assert_eq!(back.lane(a2), p.lane(a2));
2092+
2093+ // Taking the lanes back leaves exactly what a two-lane save wrote.
2094+ for _ in 0..3 {
2095+ assert!(p.undo());
2096+ }
2065 assert_eq!(2097 assert_eq!(
2066- p.without_orphan_sources().expect("saveable again"),2098+ p.without_orphan_sources(),
2067 before,2099 before,
2068 "byte for byte the same parts a two-lane save always wrote"2100 "byte for byte the same parts a two-lane save always wrote"
2069 );2101 );
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 }2102 }
2080 2103
2081 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with2104 /// [`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 one2105+ /// three lanes and grows more: every lane's own order and the one
2083- /// span-per-id rule, after every op. Amended rather than merged into that2106+ /// span-per-id rule after every op, *and* the reload the v4 format restored
2084- /// test because a >2-lane project cannot round-trip through the v2 file2107+ /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
2085- /// format -- [`invariants_hold`] checks what a reload would have checked.2108+ /// project of any number of lanes.
2086 #[test]2109 #[test]
2087 fn random_edit_sequences_keep_many_lanes_consistent() {2110 fn random_edit_sequences_keep_many_lanes_consistent() {
2088 for seed in 0..200u64 {2111 for seed in 0..200u64 {
@@ -2125,6 +2148,7 @@ mod tests {
2125 _ => p.append_clip(0, 1 + next(9)),2148 _ => p.append_clip(0, 1 + next(9)),
2126 };2149 };
2127 invariants_hold(&p, &format!("seed {seed}, step {step}"));2150 invariants_hold(&p, &format!("seed {seed}, step {step}"));
2151+ reloads(&p, &format!("seed {seed}, step {step}"));
2128 }2152 }
2129 }2153 }
2130 }2154 }
crates/engine/tests/audio_files.rsmodified+1 -1
@@ -240,7 +240,7 @@ fn a_song_survives_a_save_and_a_reload() {
240 .expect("write");240 .expect("write");
241 let e = refusal(PlaybackSession::open_project(&broken));241 let e = refusal(PlaybackSession::open_project(&broken));
242 assert!(242 assert!(
243- e.ends_with("has no picture: it can only play on the audio lane"),243+ e.ends_with("has no picture: it can only play on an audio lane"),
244 "{e}"244 "{e}"
245 );245 );
246 let _ = std::fs::remove_dir_all(&dir);246 let _ = std::fs::remove_dir_all(&dir);
crates/engine/tests/export.rsmodified+4 -2
@@ -200,8 +200,10 @@ fn exports_the_audio_stream_the_timeline_plays() {
200 path: multi.clone(),200 path: multi.clone(),
201 audio_stream: 1,201 audio_stream: 1,
202 }],202 }],
203- vec![whole],203+ vec![
204- vec![whole],204+ (engine::project::LaneKind::Video, vec![whole]),
205+ (engine::project::LaneKind::Audio, vec![whole]),
206+ ],
205 )207 )
206 .expect("a one-source project on stream 1");208 .expect("a one-source project on stream 1");
207 let out = out_path("stream1");209 let out = out_path("stream1");
crates/engine/tests/saveload.rsmodified+60 -5
@@ -126,9 +126,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<Source>, f64
126 126
127 /// The version-1 promise: a file written before the lanes existed still opens,127 /// The version-1 promise: a file written before the lanes existed still opens,
128 /// as one grouped video+audio pair per clip laid end to end, and saving it128 /// as one grouped video+audio pair per clip laid end to end, and saving it
129-/// again writes version 3 -- which reopens as the same timeline.129+/// again writes version 4 -- which reopens as the same timeline.
130 #[test]130 #[test]
131-fn a_version_1_project_loads_fully_grouped_and_saves_as_version_3() {131+fn a_version_1_project_loads_fully_grouped_and_saves_as_version_4() {
132 let dir = scratch("v1");132 let dir = scratch("v1");
133 copy_in(&dir, "test_av.mp4");133 copy_in(&dir, "test_av.mp4");
134 let path = dir.join("old.edith");134 let path = dir.join("old.edith");
@@ -156,11 +156,11 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_3() {
156 "playhead kept"156 "playhead kept"
157 );157 );
158 158
159- // Saved again it is v3, and v3 round-trips to the same timeline.159+ // Saved again it is v4, and v4 round-trips to the same timeline.
160 let v2 = dir.join("new.edith");160 let v2 = dir.join("new.edith");
161 loaded.save_project(&v2).expect("save");161 loaded.save_project(&v2).expect("save");
162 let text = std::fs::read_to_string(&v2).expect("read back");162 let text = std::fs::read_to_string(&v2).expect("read back");
163- assert!(text.starts_with("edith 3\n"), "{text}");163+ assert!(text.starts_with("edith 4\n"), "{text}");
164 assert_eq!(164 assert_eq!(
165 text.lines().filter(|l| l.starts_with("video ")).count(),165 text.lines().filter(|l| l.starts_with("video ")).count(),
166 2,166 2,
@@ -198,6 +198,56 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_3() {
198 );198 );
199 }199 }
200 200
201+/// What version 4 is for: a project file holds any number of lanes, in the
202+/// order they are displayed in, and one holding nothing is still a lane. The
203+/// timeline is built by hand because the format is what this checks -- no UI
204+/// adds a lane yet -- and the file it writes back has to be the one it read.
205+#[test]
206+fn a_version_4_project_holds_more_than_two_lanes() {
207+ use engine::project::{Lane, LaneKind};
208+
209+ let dir = scratch("v4_lanes");
210+ copy_in(&dir, "test_av.mp4");
211+ let path = dir.join("many.edith");
212+ // V1, A1, V2, A2 in display order: a take grouped across V1 and A2 (link 3,
213+ // one span on two lanes that are not a pair), a lone clip on V2, and an
214+ // empty A1 that has only its own line to say it is there.
215+ let text = "edith 4\nplayhead 0\nsource 0 test_av.mp4\n\
216+ video 1 0 0 30 0 3\naudio 1\nvideo 2 40 0 20 0 -\naudio 2 0 0 30 0 3\n";
217+ std::fs::write(&path, text).expect("write a v4 file");
218+
219+ let loaded = PlaybackSession::open_project(&path).expect("a four-lane project opens");
220+ let v2 = Lane::new(LaneKind::Video, 1);
221+ let a2 = Lane::new(LaneKind::Audio, 1);
222+ assert_eq!(loaded.lane_clips(Lane::V1).len(), 1);
223+ assert!(loaded.lane_clips(Lane::A1).is_empty(), "A1 holds nothing");
224+ assert_eq!(
225+ loaded
226+ .lane_clips(v2)
227+ .iter()
228+ .map(|c| (c.start, c.end()))
229+ .collect::<Vec<_>>(),
230+ vec![(40, 60)],
231+ "V2 is a lane of its own, gap and all"
232+ );
233+ assert_eq!(
234+ loaded.lane_clips(a2)[0].link,
235+ loaded.lane_clips(Lane::V1)[0].link,
236+ "the group spans V1 and A2, which are not a pair"
237+ );
238+ assert_eq!(loaded.timeline_duration(), 60.0 / loaded.meta().frame_rate);
239+
240+ // ...and saving it writes back the same bytes: the lane list, its order and
241+ // the empty lane all survive the round trip.
242+ let again = dir.join("again.edith");
243+ loaded.save_project(&again).expect("save");
244+ assert_eq!(
245+ std::fs::read_to_string(&again).expect("read back"),
246+ text,
247+ "a four-lane project is written as it was read"
248+ );
249+}
250+
201 #[test]251 #[test]
202 fn a_saved_project_reopens_as_the_same_timeline() {252 fn a_saved_project_reopens_as_the_same_timeline() {
203 let dir = scratch("round_trip");253 let dir = scratch("round_trip");
@@ -409,9 +459,14 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
409 459
410 for (text, want) in [460 for (text, want) in [
411 (461 (
412- "edith 4\nsource 0 test_av.mp4\nvideo 0 0 30 0 -\n",462+ "edith 5\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 -\n",
413 "line 1",463 "line 1",
414 ),464 ),
465+ // A lane number that skips one of its kind: V2 was never declared.
466+ (
467+ "edith 4\nsource 0 test_av.mp4\nvideo 2 0 0 30 0 -\n",
468+ "line 3",
469+ ),
415 // A v2 source line in a v3 file: the stream field is not optional.470 // A v2 source line in a v3 file: the stream field is not optional.
416 ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 2"),471 ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 2"),
417 ("not a project at all\n", "line 1"),472 ("not a project at all\n", "line 1"),