forge
Explore
Log in

Don't you dare go Hollow

.veproj save/load — relocatable, validated, atomic

Browse files at this commit

ac60b8075948f22707ef6ee7d2382887c7f523ccAhmet Kaan GümüşParent: a178b73
  • feat
    • .veproj save/load — relocatable, validated, atomic
Show full message
✨ feat(engine): .veproj save/load — relocatable, validated, atomic

A project file is line-based text: `veproj 1`, an optional playhead, one
`source` line per file and one `clip` line per range. Text because a path is
bytes on this platform and a JSON string could not carry one losslessly, so the
path field is byte-escaped instead; paths under the project's own directory are
written relative to it, which makes a folder of media plus its .veproj movable
anywhere. The parser is strict and every refusal names its 1-based line, and
writing goes through .part + rename as an export does.

Loading is a new session, never a mutation of the old one: source 0 defines the
timeline, every other source passes the same checks import applies (in the same
words), and every clip has to still fit inside the file it plays from -- a
source that vanished or shrank is a refusal that names it, not a silently
shorter timeline. Sources no clip plays from are pruned at save, so an import
that was undone cannot leave a file behind that blocks a future load.
crates/engine/src/lib.rsmodified+1 -0
@@ -11,6 +11,7 @@ pub mod hw;
11 pub mod mux;11 pub mod mux;
12 pub mod playback;12 pub mod playback;
13 pub mod project;13 pub mod project;
14+pub mod veproj;
14 15
15 pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession};16 pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession};
16 pub use clock::PlaybackClock;17 pub use clock::PlaybackClock;
crates/engine/src/playback.rsmodified+137 -30
@@ -11,7 +11,7 @@
11 //! Drift policy stays with the caller -- this type answers "what time is it",11 //! Drift policy stays with the caller -- this type answers "what time is it",
12 //! the renderer decides which frame that means.12 //! the renderer decides which frame that means.
13 13
14-use std::path::Path;14+use std::path::{Path, PathBuf};
15 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};15 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
16 use std::sync::mpsc::{Receiver, TryRecvError};16 use std::sync::mpsc::{Receiver, TryRecvError};
17 use std::sync::{Arc, Mutex};17 use std::sync::{Arc, Mutex};
@@ -132,10 +132,98 @@ impl PlaybackSession {
132 })132 })
133 }133 }
134 134
135+ /// Opens a project file written by [`save_project`](Self::save_project):
136+ /// the whole timeline, restored to where its playhead stood, paused like
137+ /// [`open`](Self::open).
138+ ///
139+ /// A *new* session rather than a reload of this one, so a load that fails
140+ /// leaves the caller's current session untouched -- atomic by
141+ /// construction. Every named file is opened and checked here: source 0
142+ /// defines the timeline exactly as `open` does, every other source has to
143+ /// match it the way [`import`](Self::import) demands, and every clip has to
144+ /// still be inside the file it plays from. A source that vanished or
145+ /// shrank since the save is a refusal naming it, not a silently shorter
146+ /// timeline -- the disappearing-file tolerance elsewhere in this type
147+ /// applies only *after* a project has loaded.
148+ ///
149+ /// The undo history is not saved: `undo` is `false` on a fresh load.
150+ pub fn open_project(path: &Path) -> crate::Result<Self> {
151+ let doc = crate::veproj::load(path)?;
152+ let first = doc.sources.first().ok_or("the project names no sources")?;
153+ // Source 0 both scaffolds the session and defines the timeline, so it
154+ // is opened for playback rather than merely probed.
155+ let (meta, frames, cancel) = DecodeSession::open_at(first, 0)
156+ .map_err(|e| format!("source {}: {e}", first.display()))?;
157+ let audio = open_audio(first);
158+ let first_audio = AudioSession::probe(first)?;
159+
160+ let mut counts = vec![meta.frame_count];
161+ for source in &doc.sources[1..] {
162+ let (other, _) =
163+ Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?;
164+ matches_timeline(source, &other, &meta, &first_audio)
165+ .map_err(|e| format!("source {}: {e}", source.display()))?;
166+ counts.push(other.frame_count);
167+ }
168+ for (i, clip) in doc.clips.iter().enumerate() {
169+ if clip.out_frame > counts[clip.source] {
170+ return Err(format!(
171+ "clip {i} ends at frame {} but {} has {} frames",
172+ clip.out_frame,
173+ doc.sources[clip.source].display(),
174+ counts[clip.source]
175+ )
176+ .into());
177+ }
178+ }
179+
180+ let playhead = doc.playhead;
181+ let project = Project::from_parts(doc.sources, doc.clips)
182+ .ok_or("the project's clips do not fit its sources")?;
183+ let range = project.clips()[0];
184+ let mut session = Self {
185+ meta,
186+ frames,
187+ cancel,
188+ clock: PlaybackClock::new(match audio {
189+ Some(_) => ClockSource::Audio,
190+ None => ClockSource::Wall,
191+ }),
192+ audio,
193+ project,
194+ range,
195+ timeline_start: 0,
196+ eos: false,
197+ };
198+ // The scaffolding above opened source 0 from its first frame and the
199+ // whole of its audio; this puts both onto the clip the playhead is
200+ // actually in -- a seek replaces the decoder and supersedes the audio
201+ // worker by epoch, exactly as it does after an edit. It also clamps,
202+ // so a playhead past a hand-shortened timeline lands on the last frame.
203+ session.seek(f64::from(playhead) / meta.frame_rate);
204+ Ok(session)
205+ }
206+
135 pub fn meta(&self) -> &VideoMeta {207 pub fn meta(&self) -> &VideoMeta {
136 &self.meta208 &self.meta
137 }209 }
138 210
211+ /// The files this timeline plays from, index 0 first -- a caller needs it
212+ /// to name an export or a window after the media rather than the project.
213+ pub fn sources(&self) -> &[PathBuf] {
214+ self.project.sources()
215+ }
216+
217+ /// Writes the timeline to `path` as a `.veproj`, atomically (see
218+ /// [`crate::veproj`]). Sources no clip plays from are left out, and the
219+ /// playhead is saved with it so a reopened project resumes where it stood.
220+ pub fn save_project(&self, path: &Path) -> crate::Result<()> {
221+ let (sources, clips) = self.project.without_orphan_sources();
222+ let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
223+ .min(self.project.timeline_frames().saturating_sub(1));
224+ crate::veproj::save(path, &sources, &clips, playhead)
225+ }
226+
139 /// The next decoded frame, its `index` rewritten from a source frame to a227 /// The next decoded frame, its `index` rewritten from a source frame to a
140 /// *timeline* frame -- the only frame space that leaves the engine, and the228 /// *timeline* frame -- the only frame space that leaves the engine, and the
141 /// one [`PlaybackSession::now`] is in.229 /// one [`PlaybackSession::now`] is in.
@@ -274,36 +362,8 @@ impl PlaybackSession {
274 /// a refusal.362 /// a refusal.
275 pub fn import(&mut self, path: &Path) -> crate::Result<()> {363 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
276 let (meta, _) = Demuxer::open(path)?;364 let (meta, _) = Demuxer::open(path)?;
277- if (meta.width, meta.height) != (self.meta.width, self.meta.height) {
278- return Err(format!(
279- "{}x{} does not match the timeline's {}x{}",
280- meta.width, meta.height, self.meta.width, self.meta.height
281- )
282- .into());
283- }
284- // Container frame rates are computed from timescales, so never `==`.
285- if (meta.frame_rate - self.meta.frame_rate).abs() > 0.01 {
286- return Err(format!(
287- "{:.3} fps does not match the timeline's {:.3} fps",
288- meta.frame_rate, self.meta.frame_rate
289- )
290- .into());
291- }
292- // Whole-probe equality: rate, layout and the esds fields, which the
293- // audio worker holds every source to anyway. Both silent is a match.
294- let probe = AudioSession::probe(path)?;
295 let first = AudioSession::probe(&self.project.sources()[0])?;365 let first = AudioSession::probe(&self.project.sources()[0])?;
296- if probe != first {366+ matches_timeline(path, &meta, &self.meta, &first)?;
297- return Err(match (probe, first) {
298- (None, _) => "the file is silent, the timeline has audio".to_string(),
299- (_, None) => "the file has audio, the timeline is silent".to_string(),
300- (Some(a), Some(b)) => format!(
301- "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
302- a.params.sample_rate, a.channels, b.params.sample_rate, b.channels
303- ),
304- }
305- .into());
306- }
307 367
308 let old_end = self.timeline_duration();368 let old_end = self.timeline_duration();
309 let source = self.project.import(path);369 let source = self.project.import(path);
@@ -502,6 +562,53 @@ impl PlaybackSession {
502 }562 }
503 }563 }
504 564
565+/// Whether `path`, already demuxed to `meta`, may join a timeline whose
566+/// parameters are `timeline` and whose audio probes as `first`: same
567+/// dimensions, same frame rate, same audio parameters or both silent -- one
568+/// timeline this slice means one set of encoder/device parameters.
569+///
570+/// The `Err` names the property that disagrees, and those strings are what a
571+/// front-end shows verbatim; [`PlaybackSession::import`] and
572+/// [`PlaybackSession::open_project`] share them so a file refused at import is
573+/// refused in the same words at load.
574+fn matches_timeline(
575+ path: &Path,
576+ meta: &VideoMeta,
577+ timeline: &VideoMeta,
578+ first: &Option<crate::AudioProbe>,
579+) -> crate::Result<()> {
580+ if (meta.width, meta.height) != (timeline.width, timeline.height) {
581+ return Err(format!(
582+ "{}x{} does not match the timeline's {}x{}",
583+ meta.width, meta.height, timeline.width, timeline.height
584+ )
585+ .into());
586+ }
587+ // Container frame rates are computed from timescales, so never `==`.
588+ if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {
589+ return Err(format!(
590+ "{:.3} fps does not match the timeline's {:.3} fps",
591+ meta.frame_rate, timeline.frame_rate
592+ )
593+ .into());
594+ }
595+ // Whole-probe equality: rate, layout and the esds fields, which the audio
596+ // worker holds every source to anyway. Both silent is a match.
597+ let probe = AudioSession::probe(path)?;
598+ if probe != *first {
599+ return Err(match (probe, first) {
600+ (None, _) => "the file is silent, the timeline has audio".to_string(),
601+ (_, None) => "the file has audio, the timeline is silent".to_string(),
602+ (Some(a), Some(b)) => format!(
603+ "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
604+ a.params.sample_rate, a.channels, b.params.sample_rate, b.channels
605+ ),
606+ }
607+ .into());
608+ }
609+ Ok(())
610+}
611+
505 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a612 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a
506 /// track the decoder refuses. Dropping the receiver on the way out stops the613 /// track the decoder refuses. Dropping the receiver on the way out stops the
507 /// audio decode worker, so a failure here leaves nothing running.614 /// audio decode worker, so a failure here leaves nothing running.
crates/engine/src/project.rsmodified+107 -0
@@ -67,6 +67,26 @@ impl Project {
67 }67 }
68 }68 }
69 69
70+ /// A project rebuilt from a saved edit list -- the load half of
71+ /// [`crate::veproj`]. History is *not* saved, so [`Project::undo`] is
72+ /// `false` until the first edit of the new session. `None` when the parts
73+ /// would break an invariant every other constructor keeps: no clips, an
74+ /// empty clip, or a clip naming a source that is not there.
75+ pub fn from_parts(sources: Vec<PathBuf>, clips: Vec<Clip>) -> Option<Self> {
76+ if clips.is_empty()
77+ || clips
78+ .iter()
79+ .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame)
80+ {
81+ return None;
82+ }
83+ Some(Self {
84+ sources: sources.iter().map(|s| canonical(s)).collect(),
85+ clips,
86+ history: Vec::new(),
87+ })
88+ }
89+
70 pub fn clips(&self) -> &[Clip] {90 pub fn clips(&self) -> &[Clip] {
71 &self.clips91 &self.clips
72 }92 }
@@ -109,6 +129,30 @@ impl Project {
109 true129 true
110 }130 }
111 131
132+ /// The sources a clip actually names, with the clips reindexed onto them
133+ /// -- what a save writes. Indexes are forever *inside* a session (see
134+ /// [`Project::append_clip`]), so an undone import leaves an orphan source
135+ /// entry behind; writing that orphan to a project file would let a file
136+ /// nothing plays refuse a future load. New indexes are assigned in order of
137+ /// first use, so the same project always emits the same bytes.
138+ pub fn without_orphan_sources(&self) -> (Vec<PathBuf>, Vec<Clip>) {
139+ let mut moved = vec![None; self.sources.len()];
140+ let mut sources = Vec::new();
141+ let mut clips = self.clips.clone();
142+ for c in &mut clips {
143+ let old = c.source;
144+ c.source = match moved[old] {
145+ Some(new) => new,
146+ None => {
147+ sources.push(self.sources[old].clone());
148+ moved[old] = Some(sources.len() - 1);
149+ sources.len() - 1
150+ }
151+ };
152+ }
153+ (sources, clips)
154+ }
155+
112 /// Length of the timeline in frames.156 /// Length of the timeline in frames.
113 pub fn timeline_frames(&self) -> u32 {157 pub fn timeline_frames(&self) -> u32 {
114 self.clips.iter().map(Clip::len).sum()158 self.clips.iter().map(Clip::len).sum()
@@ -685,4 +729,67 @@ mod tests {
685 "segments must cover exactly the timeline: {played}"729 "segments must cover exactly the timeline: {played}"
686 );730 );
687 }731 }
732+
733+ #[test]
734+ fn orphan_sources_are_pruned_and_the_clips_reindexed() {
735+ // Import a second file, undo it: source 1 is now an orphan.
736+ let mut p = two_sources();
737+ assert!(p.undo());
738+ let (sources, clips) = p.without_orphan_sources();
739+ assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone");
740+ assert_eq!(clips, three().clips(), "the clips are untouched");
741+
742+ // Three sources where only the middle one is orphaned: the survivors
743+ // renumber, and the clips follow.
744+ let mut p = Project::single(FILE, 9);
745+ assert_eq!(p.import(FILE2), 1);
746+ assert_eq!(p.import("/nonexistent/c.mp4"), 2);
747+ assert!(p.append_clip(2, 4));
748+ let (sources, clips) = p.without_orphan_sources();
749+ assert_eq!(
750+ sources,
751+ vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")]
752+ );
753+ assert_eq!(clips.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);
754+ // ...and what comes out is loadable, with the same timeline.
755+ let reloaded = Project::from_parts(sources, clips).expect("from_parts");
756+ assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
757+ assert_eq!(reloaded.sources().len(), 2);
758+ }
759+
760+ #[test]
761+ fn from_parts_has_no_history_and_checks_the_invariants() {
762+ let (sources, clips) = three().without_orphan_sources();
763+ let mut p = Project::from_parts(sources.clone(), clips.clone()).expect("valid parts");
764+ assert_eq!(p.clips(), three().clips());
765+ assert!(!p.undo(), "a loaded project has nothing to undo");
766+ assert!(p.cut(4), "...and is editable from there");
767+ assert!(p.undo());
768+
769+ assert!(Project::from_parts(sources.clone(), Vec::new()).is_none());
770+ assert!(
771+ Project::from_parts(
772+ sources.clone(),
773+ vec![Clip {
774+ source: 1,
775+ in_frame: 0,
776+ out_frame: 3
777+ }]
778+ )
779+ .is_none(),
780+ "clip names a source that is not there"
781+ );
782+ assert!(
783+ Project::from_parts(
784+ sources,
785+ vec![Clip {
786+ source: 0,
787+ in_frame: 3,
788+ out_frame: 3
789+ }]
790+ )
791+ .is_none(),
792+ "empty clip"
793+ );
794+ }
688 }795 }
crates/engine/src/veproj.rsadded+382 -0
@@ -0,0 +1,382 @@
1+//! The project file: a line of text per thing, and nothing else.
2+//!
3+//! ```text
4+//! veproj 1
5+//! playhead 90
6+//! source test_av.mp4
7+//! source /elsewhere/test_av2.mp4
8+//! clip 0 120 0
9+//! clip 0 120 1
10+//! ```
11+//!
12+//! Text because an edit list is three integers and a path, and a path is
13+//! *bytes* on this platform -- a JSON string would have to lossily decode one.
14+//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
15+//! everything a line-based format cannot carry) and survives round-trip
16+//! exactly. Paths under the project file's own directory are written relative
17+//! to it, so a folder holding the media and the `.veproj` can be moved or
18+//! copied anywhere and still open; anything else is absolute.
19+//!
20+//! The parser is strict and every refusal names its 1-based line: a project
21+//! file is generated, so a line it did not generate is a corrupt file, not a
22+//! dialect. Structure is checked here (fields, ordering, empty clips,
23+//! out-of-range source indexes); whether the files on disk still match the
24+//! timeline is [`crate::PlaybackSession::open_project`]'s business.
25+//!
26+//! Writing goes through `<path>.part` and a rename, as an export does, so an
27+//! interrupted save cannot destroy the previous version of the project.
28+
29+use std::ffi::OsString;
30+use std::os::unix::ffi::{OsStrExt, OsStringExt};
31+use std::path::{Path, PathBuf};
32+
33+use crate::project::Clip;
34+
35+/// First line, exactly. The version is part of it: a v2 reader will accept a
36+/// `veproj 1` file, and a v1 reader refuses a `veproj 2` one by name.
37+const MAGIC: &[u8] = b"veproj 1";
38+
39+/// What a project file says: an edit list plus where the playhead stood.
40+/// Structurally valid by construction -- see [`parse`].
41+#[derive(Debug)]
42+pub struct Document {
43+ /// Absolute, relative entries already joined to the file's own directory.
44+ pub sources: Vec<PathBuf>,
45+ pub clips: Vec<Clip>,
46+ pub playhead: u32,
47+}
48+
49+/// Writes the project to `path`, atomically. `sources` should already be
50+/// orphan-free ([`crate::Project::without_orphan_sources`]).
51+pub fn save(path: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> crate::Result<()> {
52+ let dir = path.parent().unwrap_or(Path::new(""));
53+ let mut part = path.to_path_buf().into_os_string();
54+ part.push(".part");
55+ let part = PathBuf::from(part);
56+ // The rename publishes the file under the caller's name in one step, on the
57+ // same directory; until it happens the old project file is still the whole
58+ // truth.
59+ let result = std::fs::write(&part, emit(dir, sources, clips, playhead))
60+ .and_then(|()| std::fs::rename(&part, path));
61+ if result.is_err() {
62+ let _ = std::fs::remove_file(&part);
63+ }
64+ result.map_err(Into::into)
65+}
66+
67+pub fn load(path: &Path) -> crate::Result<Document> {
68+ let data = std::fs::read(path)?;
69+ parse(&data, path.parent().unwrap_or(Path::new("")))
70+}
71+
72+fn emit(dir: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> Vec<u8> {
73+ let mut out = Vec::new();
74+ out.extend_from_slice(MAGIC);
75+ out.push(b'\n');
76+ out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
77+ for s in sources {
78+ out.extend_from_slice(b"source ");
79+ escape(s.strip_prefix(dir).unwrap_or(s), &mut out);
80+ out.push(b'\n');
81+ }
82+ for c in clips {
83+ out.extend_from_slice(
84+ format!("clip {} {} {}\n", c.in_frame, c.out_frame, c.source).as_bytes(),
85+ );
86+ }
87+ out
88+}
89+
90+fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
91+ // One trailing newline is the line terminator of the last line, not an
92+ // empty line -- any further one is, and is refused below.
93+ let body = data.strip_suffix(b"\n").unwrap_or(data);
94+ let mut lines = body.split(|&b| b == b'\n').enumerate();
95+ let (_, first) = lines.next().unwrap_or((0, &[]));
96+ if first != MAGIC {
97+ return Err(match first.strip_prefix(b"veproj ") {
98+ Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
99+ None => "line 1: not a veproj file".to_string(),
100+ }
101+ .into());
102+ }
103+
104+ let mut doc = Document {
105+ sources: Vec::new(),
106+ clips: Vec::new(),
107+ playhead: 0,
108+ };
109+ let mut playhead_seen = false;
110+ for (i, line) in lines {
111+ let n = i + 1;
112+ let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
113+ Some(at) => (&line[..at], &line[at + 1..]),
114+ None => (line, &line[line.len()..]),
115+ };
116+ match keyword {
117+ b"playhead" => {
118+ if playhead_seen || !doc.sources.is_empty() {
119+ return Err(
120+ format!("line {n}: playhead belongs once, before the sources").into(),
121+ );
122+ }
123+ doc.playhead = number(rest, n)?;
124+ playhead_seen = true;
125+ }
126+ b"source" => {
127+ if !doc.clips.is_empty() {
128+ return Err(format!("line {n}: source after a clip").into());
129+ }
130+ if rest.is_empty() {
131+ return Err(format!("line {n}: source without a path").into());
132+ }
133+ let path = unescape(rest, n)?;
134+ // Relative means "next to the project file", which is what
135+ // makes a whole folder relocatable.
136+ doc.sources.push(if path.is_absolute() {
137+ path
138+ } else {
139+ dir.join(path)
140+ });
141+ }
142+ b"clip" => {
143+ let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
144+ if fields.len() != 3 {
145+ return Err(
146+ format!("line {n}: clip wants 3 fields, found {}", fields.len()).into(),
147+ );
148+ }
149+ let clip = Clip {
150+ in_frame: number(fields[0], n)?,
151+ out_frame: number(fields[1], n)?,
152+ source: number(fields[2], n)? as usize,
153+ };
154+ if clip.out_frame <= clip.in_frame {
155+ return Err(format!(
156+ "line {n}: clip [{}, {}) is empty",
157+ clip.in_frame, clip.out_frame
158+ )
159+ .into());
160+ }
161+ if clip.source >= doc.sources.len() {
162+ return Err(format!(
163+ "line {n}: clip names source {} of {}",
164+ clip.source,
165+ doc.sources.len()
166+ )
167+ .into());
168+ }
169+ doc.clips.push(clip);
170+ }
171+ // Empty lines land here too: nothing in this format is optional
172+ // whitespace.
173+ _ => {
174+ return Err(format!(
175+ "line {n}: unknown keyword {:?}",
176+ String::from_utf8_lossy(keyword)
177+ )
178+ .into());
179+ }
180+ }
181+ }
182+ if doc.clips.is_empty() {
183+ return Err("no clips: an empty timeline is not a project".into());
184+ }
185+ Ok(doc)
186+}
187+
188+fn number(field: &[u8], line: usize) -> crate::Result<u32> {
189+ match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
190+ Some(n) => Ok(n),
191+ None => Err(format!(
192+ "line {line}: {:?} is not a number",
193+ String::from_utf8_lossy(field)
194+ )
195+ .into()),
196+ }
197+}
198+
199+/// The two bytes a line-based format cannot hold, and the escape byte itself.
200+fn escape(path: &Path, out: &mut Vec<u8>) {
201+ for &b in path.as_os_str().as_bytes() {
202+ match b {
203+ b'%' => out.extend_from_slice(b"%25"),
204+ b'\n' => out.extend_from_slice(b"%0A"),
205+ _ => out.push(b),
206+ }
207+ }
208+}
209+
210+/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
211+/// may spell a space or a quote that way, and there is no reason to refuse it.
212+fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
213+ let mut out = Vec::with_capacity(field.len());
214+ let mut i = 0;
215+ while i < field.len() {
216+ if field[i] != b'%' {
217+ out.push(field[i]);
218+ i += 1;
219+ continue;
220+ }
221+ let byte = field
222+ .get(i + 1..i + 3)
223+ .and_then(|h| std::str::from_utf8(h).ok())
224+ .and_then(|h| u8::from_str_radix(h, 16).ok())
225+ .ok_or_else(|| -> crate::Error {
226+ format!("line {line}: truncated % escape in the path").into()
227+ })?;
228+ out.push(byte);
229+ i += 3;
230+ }
231+ Ok(PathBuf::from(OsString::from_vec(out)))
232+}
233+
234+#[cfg(test)]
235+mod tests {
236+ use super::*;
237+
238+ fn clip(in_frame: u32, out_frame: u32, source: usize) -> Clip {
239+ Clip {
240+ in_frame,
241+ out_frame,
242+ source,
243+ }
244+ }
245+
246+ /// Two sources, one under the project's own directory and one not, and a
247+ /// clip from each -- the shape every case below starts from.
248+ fn doc() -> (PathBuf, Vec<PathBuf>, Vec<Clip>) {
249+ (
250+ PathBuf::from("/proj"),
251+ vec![
252+ PathBuf::from("/proj/a.mp4"),
253+ PathBuf::from("/elsewhere/b.mp4"),
254+ ],
255+ vec![clip(0, 30, 0), clip(10, 20, 1)],
256+ )
257+ }
258+
259+ #[test]
260+ fn relative_and_absolute_paths_round_trip() {
261+ let (dir, sources, clips) = doc();
262+ let bytes = emit(&dir, &sources, &clips, 12);
263+ assert_eq!(
264+ String::from_utf8_lossy(&bytes),
265+ "veproj 1\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\nclip 0 30 0\nclip 10 20 1\n",
266+ "the file under the project directory is written relative to it"
267+ );
268+ let back = parse(&bytes, &dir).expect("parse");
269+ assert_eq!(back.sources, sources, "relative entries rejoin the dir");
270+ assert_eq!(back.clips, clips);
271+ assert_eq!(back.playhead, 12);
272+ // ...and emitting the parsed document reproduces the same bytes.
273+ assert_eq!(emit(&dir, &back.sources, &back.clips, back.playhead), bytes);
274+ }
275+
276+ #[test]
277+ fn escapes_survive_the_bytes_json_would_not() {
278+ let dir = PathBuf::from("/proj");
279+ // A newline and a percent in a filename, plus a non-UTF-8 byte.
280+ let nasty = PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec()));
281+ let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 5, 0)], 0);
282+ assert_eq!(
283+ bytes.iter().filter(|&&b| b == b'\n').count(),
284+ 4,
285+ "the escaped newline must not become a line break"
286+ );
287+ let back = parse(&bytes, &dir).expect("parse");
288+ assert_eq!(back.sources, vec![nasty]);
289+ }
290+
291+ #[test]
292+ fn a_wrong_first_line_is_refused_by_name() {
293+ let dir = PathBuf::from("/proj");
294+ let err = parse(b"veproj 2\nsource a.mp4\nclip 0 5 0\n", &dir)
295+ .unwrap_err()
296+ .to_string();
297+ assert_eq!(err, "line 1: unsupported version 2");
298+ for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
299+ assert_eq!(
300+ parse(junk, &dir).unwrap_err().to_string(),
301+ "line 1: not a veproj file"
302+ );
303+ }
304+ }
305+
306+ #[test]
307+ fn malformed_lines_name_their_line_number() {
308+ let dir = PathBuf::from("/proj");
309+ let cases: [(&[u8], &str); 8] = [
310+ (
311+ b"veproj 1\nsource a.mp4\nclip 0 5\n",
312+ "line 3: clip wants 3 fields, found 2",
313+ ),
314+ (
315+ b"veproj 1\nsource a.mp4\nclip 0 five 0\n",
316+ "line 3: \"five\" is not a number",
317+ ),
318+ (
319+ b"veproj 1\nsource a.mp4\nclip 5 5 0\n",
320+ "line 3: clip [5, 5) is empty",
321+ ),
322+ (
323+ b"veproj 1\nsource a.mp4\nclip 7 5 0\n",
324+ "line 3: clip [7, 5) is empty",
325+ ),
326+ (
327+ b"veproj 1\nsource a.mp4\nclip 0 5 1\n",
328+ "line 3: clip names source 1 of 1",
329+ ),
330+ (
331+ b"veproj 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
332+ "line 4: source after a clip",
333+ ),
334+ (
335+ b"veproj 1\nsource a.mp4\n\nclip 0 5 0\n",
336+ "line 3: unknown keyword \"\"",
337+ ),
338+ (
339+ b"veproj 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
340+ "line 3: playhead belongs once, before the sources",
341+ ),
342+ ];
343+ for (bytes, want) in cases {
344+ assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
345+ }
346+ }
347+
348+ #[test]
349+ fn a_project_without_clips_is_not_a_project() {
350+ let dir = PathBuf::from("/proj");
351+ assert_eq!(
352+ parse(b"veproj 1\nsource a.mp4\n", &dir)
353+ .unwrap_err()
354+ .to_string(),
355+ "no clips: an empty timeline is not a project"
356+ );
357+ assert_eq!(
358+ parse(b"veproj 1\n", &dir).unwrap_err().to_string(),
359+ "no clips: an empty timeline is not a project"
360+ );
361+ }
362+
363+ /// Every truncation of a good file either parses or refuses; none panics.
364+ #[test]
365+ fn truncations_never_panic() {
366+ let (dir, sources, clips) = doc();
367+ let bytes = emit(&dir, &sources, &clips, 12);
368+ for cut in 0..bytes.len() {
369+ let _ = parse(&bytes[..cut], &dir);
370+ // ...and the same file with a byte lopped off the front, which
371+ // shifts every field into the wrong place.
372+ let _ = parse(&bytes[cut..], &dir);
373+ }
374+ // A % escape at the very end of a line has nothing to consume.
375+ assert_eq!(
376+ parse(b"veproj 1\nsource a%\nclip 0 5 0\n", &dir)
377+ .unwrap_err()
378+ .to_string(),
379+ "line 2: truncated % escape in the path"
380+ );
381+ }
382+}
crates/engine/tests/saveload.rsadded+278 -0
@@ -0,0 +1,278 @@
1+//! Saving a project and opening it again: the timeline that comes back is the
2+//! one that went in, a folder of media plus its `.veproj` can be moved
3+//! anywhere, and every way the files on disk can have changed underneath is a
4+//! refusal that says which file and why.
5+//!
6+//! ```text
7+//! cargo test -p engine --release --test saveload -- --nocapture
8+//! ```
9+
10+use std::path::{Path, PathBuf};
11+
12+use engine::PlaybackSession;
13+
14+fn asset(name: &str) -> PathBuf {
15+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
16+ .join("../../assets")
17+ .join(name)
18+}
19+
20+/// A fresh directory to litter. Canonical, because the saved paths are
21+/// relative to it and `Project` canonicalises what it is handed.
22+fn scratch(name: &str) -> PathBuf {
23+ let dir = std::env::temp_dir().join(format!("ve_saveload_{name}_{}", std::process::id()));
24+ let _ = std::fs::remove_dir_all(&dir);
25+ std::fs::create_dir_all(&dir).expect("scratch dir");
26+ std::fs::canonicalize(&dir).expect("canonical scratch dir")
27+}
28+
29+fn copy_in(dir: &Path, name: &str) -> PathBuf {
30+ let to = dir.join(name);
31+ std::fs::copy(asset(name), &to).expect("copy the fixture");
32+ to
33+}
34+
35+/// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
36+/// with something to lose in every field.
37+fn edited(dir: &Path) -> PlaybackSession {
38+ let mut session = PlaybackSession::open(copy_in(dir, "test_av.mp4")).expect("open");
39+ session
40+ .import(&copy_in(dir, "test_av2.mp4"))
41+ .expect("import the second file");
42+ assert!(session.cut_at(2.0), "cut inside the first file");
43+ assert!(session.cut_at(6.5), "cut inside the second file");
44+ assert!(session.delete_clip(1), "drop the second half of the first");
45+ session.seek(3.0);
46+ assert_eq!(session.timeline_duration(), 6.0);
47+ session
48+}
49+
50+/// What has to survive a round trip, all of it public API.
51+fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<PathBuf>, f64) {
52+ (
53+ session.clip_spans_by_source(),
54+ session.sources().to_vec(),
55+ session.timeline_duration(),
56+ )
57+}
58+
59+#[test]
60+fn a_saved_project_reopens_as_the_same_timeline() {
61+ let dir = scratch("round_trip");
62+ let saved = edited(&dir);
63+ let path = dir.join("edit.veproj");
64+ saved.save_project(&path).expect("save");
65+
66+ let mut loaded = PlaybackSession::open_project(&path).expect("open the project");
67+ assert_eq!(shape(&loaded), shape(&saved), "clips, sources and duration");
68+ assert!(
69+ (loaded.now() - saved.now()).abs() < 1.0 / loaded.meta().frame_rate,
70+ "playhead landed at {:.3}s, saved at {:.3}s",
71+ loaded.now(),
72+ saved.now()
73+ );
74+ assert!(!loaded.is_playing(), "a loaded project starts paused");
75+ assert!(!loaded.undo(), "history is not saved");
76+
77+ // Saving what was loaded reproduces the file byte for byte -- the format
78+ // has no state the round trip drops.
79+ let again = dir.join("again.veproj");
80+ loaded
81+ .save_project(&again)
82+ .expect("save the loaded project");
83+ assert_eq!(
84+ std::fs::read(&path).unwrap(),
85+ std::fs::read(&again).unwrap(),
86+ "save -> load -> save is not a fixed point"
87+ );
88+ assert!(!path.with_extension("veproj.part").exists(), "left a .part");
89+}
90+
91+#[test]
92+fn a_folder_of_media_and_its_project_can_be_moved() {
93+ let from = scratch("relocate_from");
94+ let saved = edited(&from);
95+ saved.save_project(&from.join("edit.veproj")).expect("save");
96+ drop(saved);
97+
98+ let to = scratch("relocate_to");
99+ for name in ["test_av.mp4", "test_av2.mp4", "edit.veproj"] {
100+ std::fs::copy(from.join(name), to.join(name)).expect("copy");
101+ }
102+ // The originals go away entirely: nothing absolute can be resolving here.
103+ std::fs::remove_dir_all(&from).expect("remove the original folder");
104+
105+ let moved = PlaybackSession::open_project(&to.join("edit.veproj")).expect("open the copy");
106+ assert_eq!(moved.timeline_duration(), 6.0);
107+ assert!(
108+ moved.sources().iter().all(|s| s.starts_with(&to)),
109+ "sources did not follow the folder: {:?}",
110+ moved.sources()
111+ );
112+}
113+
114+#[test]
115+fn orphan_sources_are_not_written() {
116+ let dir = scratch("orphans");
117+ let mut session = PlaybackSession::open(copy_in(&dir, "test_av.mp4")).expect("open");
118+ session
119+ .import(&copy_in(&dir, "test_av2.mp4"))
120+ .expect("import");
121+ assert!(session.undo(), "take the import back");
122+ assert_eq!(
123+ session.sources().len(),
124+ 2,
125+ "the orphan entry stays in-session"
126+ );
127+
128+ let path = dir.join("orphan.veproj");
129+ session.save_project(&path).expect("save");
130+ let text = std::fs::read_to_string(&path).expect("read back");
131+ assert_eq!(
132+ text.lines().filter(|l| l.starts_with("source ")).count(),
133+ 1,
134+ "the orphan reached the file:\n{text}"
135+ );
136+
137+ // And the load survives the orphan's file disappearing, which is the whole
138+ // point of pruning it.
139+ std::fs::remove_file(dir.join("test_av2.mp4")).expect("unlink the orphan");
140+ let loaded = PlaybackSession::open_project(&path).expect("open the project");
141+ assert_eq!(loaded.sources().len(), 1);
142+ assert_eq!(loaded.timeline_duration(), 5.0);
143+}
144+
145+#[test]
146+fn a_source_that_vanished_is_refused_by_name() {
147+ let dir = scratch("missing");
148+ let session = edited(&dir);
149+ let path = dir.join("edit.veproj");
150+ session.save_project(&path).expect("save");
151+ drop(session);
152+
153+ let gone = dir.join("test_av2.mp4");
154+ std::fs::remove_file(&gone).expect("unlink");
155+ let err = PlaybackSession::open_project(&path)
156+ .err()
157+ .expect("a project whose source is gone must not open")
158+ .to_string();
159+ assert!(
160+ err.contains("test_av2.mp4"),
161+ "the refusal must name the file: {err}"
162+ );
163+
164+ // The first source is no different -- it is simply refused earlier.
165+ std::fs::remove_file(dir.join("test_av.mp4")).expect("unlink");
166+ let err = PlaybackSession::open_project(&path)
167+ .err()
168+ .expect("no first source, no session")
169+ .to_string();
170+ assert!(err.contains("test_av.mp4"), "{err}");
171+}
172+
173+#[test]
174+fn a_source_that_shrank_is_refused_by_clip() {
175+ let dir = scratch("shrunk");
176+ copy_in(&dir, "test_av.mp4");
177+ let path = dir.join("shrunk.veproj");
178+ // Hand-written: a clip that ran to frame 10000 of a 150-frame file, which
179+ // is what re-encoding a source shorter leaves behind.
180+ std::fs::write(
181+ &path,
182+ "veproj 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\nclip 30 10000 0\n",
183+ )
184+ .expect("write");
185+ let err = PlaybackSession::open_project(&path)
186+ .err()
187+ .expect("a clip past the end of its file must not open")
188+ .to_string();
189+ assert!(
190+ err.contains("clip 1") && err.contains("test_av.mp4") && err.contains("150"),
191+ "the refusal must name the clip, the file and its length: {err}"
192+ );
193+
194+ // One frame short of the end is still inside the file.
195+ std::fs::write(
196+ &path,
197+ "veproj 1\nplayhead 0\nsource test_av.mp4\nclip 0 150 0\n",
198+ )
199+ .expect("write");
200+ let whole = PlaybackSession::open_project(&path).expect("the exact length is legal");
201+ assert_eq!(whole.timeline_duration(), 5.0);
202+}
203+
204+#[test]
205+fn a_project_that_names_itself_is_refused() {
206+ let dir = scratch("self_reference");
207+ let path = dir.join("ouroboros.veproj");
208+ std::fs::write(
209+ &path,
210+ "veproj 1\nplayhead 0\nsource ouroboros.veproj\nclip 0 30 0\n",
211+ )
212+ .expect("write");
213+ let err = PlaybackSession::open_project(&path)
214+ .err()
215+ .expect("a project is not a video")
216+ .to_string();
217+ assert!(err.contains("ouroboros.veproj"), "{err}");
218+}
219+
220+#[test]
221+fn malformed_files_are_numbered_errors_and_never_panics() {
222+ let dir = scratch("malformed");
223+ copy_in(&dir, "test_av.mp4");
224+ let path = dir.join("bad.veproj");
225+ let good = "veproj 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n";
226+
227+ for (text, want) in [
228+ ("veproj 2\nsource test_av.mp4\nclip 0 30 0\n", "line 1"),
229+ ("not a project at all\n", "line 1"),
230+ ("veproj 1\nsource test_av.mp4\nclip 0 30\n", "line 3"),
231+ ("veproj 1\nsource test_av.mp4\nclip 0 30 4\n", "line 3"),
232+ ("veproj 1\nsource test_av.mp4\nclip 30 30 0\n", "line 3"),
233+ ("veproj 1\nsource test_av.mp4\n\nclip 0 30 0\n", "line 3"),
234+ ("veproj 1\nsource test_av.mp4\nwhat 1\n", "line 3"),
235+ ] {
236+ std::fs::write(&path, text).expect("write");
237+ let err = PlaybackSession::open_project(&path)
238+ .err()
239+ .unwrap_or_else(|| panic!("accepted {text:?}"))
240+ .to_string();
241+ assert!(err.starts_with(want), "{text:?} -> {err}");
242+ }
243+
244+ // Every truncation of a good file: some are valid shorter projects, none
245+ // may panic or be reported as anything but an error.
246+ for cut in 0..good.len() {
247+ std::fs::write(&path, &good[..cut]).expect("write");
248+ let _ = PlaybackSession::open_project(&path);
249+ }
250+ // ...and a file that is not there at all.
251+ std::fs::remove_file(&path).expect("unlink");
252+ assert!(PlaybackSession::open_project(&path).is_err());
253+}
254+
255+#[test]
256+fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
257+ let dir = scratch("mismatch");
258+ copy_in(&dir, "test_av.mp4");
259+ std::fs::copy(asset("test_mismatch.mp4"), dir.join("test_av2.mp4")).expect("substitute");
260+ let path = dir.join("swapped.veproj");
261+ std::fs::write(
262+ &path,
263+ "veproj 1\nplayhead 0\nsource test_av.mp4\nsource test_av2.mp4\nclip 0 30 0\nclip 0 30 1\n",
264+ )
265+ .expect("write");
266+ let err = PlaybackSession::open_project(&path)
267+ .err()
268+ .expect("a source that stopped matching must not open")
269+ .to_string();
270+ // The suffix is `import`'s own refusal, word for word.
271+ assert_eq!(
272+ err,
273+ format!(
274+ "source {}: 640x360 does not match the timeline's 1280x720",
275+ dir.join("test_av2.mp4").display()
276+ )
277+ );
278+}