From ac60b8075948f22707ef6ee7d2382887c7f523cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 23:37:33 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20.veproj=20save/load?= =?UTF-8?q?=20=E2=80=94=20relocatable,=20validated,=20atomic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 1 + crates/engine/src/playback.rs | 167 +++++++++++--- crates/engine/src/project.rs | 107 +++++++++ crates/engine/src/veproj.rs | 382 ++++++++++++++++++++++++++++++++ crates/engine/tests/saveload.rs | 278 +++++++++++++++++++++++ 5 files changed, 905 insertions(+), 30 deletions(-) create mode 100644 crates/engine/src/veproj.rs create mode 100644 crates/engine/tests/saveload.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7900765..44a04e9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod hw; pub mod mux; pub mod playback; pub mod project; +pub mod veproj; pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession}; pub use clock::PlaybackClock; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 73b5296..bd16271 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -11,7 +11,7 @@ //! Drift policy stays with the caller -- this type answers "what time is it", //! the renderer decides which frame that means. -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; @@ -132,10 +132,98 @@ impl PlaybackSession { }) } + /// Opens a project file written by [`save_project`](Self::save_project): + /// the whole timeline, restored to where its playhead stood, paused like + /// [`open`](Self::open). + /// + /// A *new* session rather than a reload of this one, so a load that fails + /// leaves the caller's current session untouched -- atomic by + /// construction. Every named file is opened and checked here: source 0 + /// defines the timeline exactly as `open` does, every other source has to + /// match it the way [`import`](Self::import) demands, and every clip has to + /// still be inside the file it plays from. A source that vanished or + /// shrank since the save is a refusal naming it, not a silently shorter + /// timeline -- the disappearing-file tolerance elsewhere in this type + /// applies only *after* a project has loaded. + /// + /// The undo history is not saved: `undo` is `false` on a fresh load. + pub fn open_project(path: &Path) -> crate::Result { + let doc = crate::veproj::load(path)?; + let first = doc.sources.first().ok_or("the project names no sources")?; + // Source 0 both scaffolds the session and defines the timeline, so it + // is opened for playback rather than merely probed. + let (meta, frames, cancel) = DecodeSession::open_at(first, 0) + .map_err(|e| format!("source {}: {e}", first.display()))?; + let audio = open_audio(first); + let first_audio = AudioSession::probe(first)?; + + let mut counts = vec![meta.frame_count]; + for source in &doc.sources[1..] { + let (other, _) = + Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?; + matches_timeline(source, &other, &meta, &first_audio) + .map_err(|e| format!("source {}: {e}", source.display()))?; + counts.push(other.frame_count); + } + for (i, clip) in doc.clips.iter().enumerate() { + if clip.out_frame > counts[clip.source] { + return Err(format!( + "clip {i} ends at frame {} but {} has {} frames", + clip.out_frame, + doc.sources[clip.source].display(), + counts[clip.source] + ) + .into()); + } + } + + let playhead = doc.playhead; + let project = Project::from_parts(doc.sources, doc.clips) + .ok_or("the project's clips do not fit its sources")?; + let range = project.clips()[0]; + let mut session = Self { + meta, + frames, + cancel, + clock: PlaybackClock::new(match audio { + Some(_) => ClockSource::Audio, + None => ClockSource::Wall, + }), + audio, + project, + range, + timeline_start: 0, + eos: false, + }; + // The scaffolding above opened source 0 from its first frame and the + // whole of its audio; this puts both onto the clip the playhead is + // actually in -- a seek replaces the decoder and supersedes the audio + // worker by epoch, exactly as it does after an edit. It also clamps, + // so a playhead past a hand-shortened timeline lands on the last frame. + session.seek(f64::from(playhead) / meta.frame_rate); + Ok(session) + } + pub fn meta(&self) -> &VideoMeta { &self.meta } + /// The files this timeline plays from, index 0 first -- a caller needs it + /// to name an export or a window after the media rather than the project. + pub fn sources(&self) -> &[PathBuf] { + self.project.sources() + } + + /// Writes the timeline to `path` as a `.veproj`, atomically (see + /// [`crate::veproj`]). Sources no clip plays from are left out, and the + /// playhead is saved with it so a reopened project resumes where it stood. + pub fn save_project(&self, path: &Path) -> crate::Result<()> { + let (sources, clips) = self.project.without_orphan_sources(); + let playhead = secs_to_frame(self.now(), self.meta.frame_rate) + .min(self.project.timeline_frames().saturating_sub(1)); + crate::veproj::save(path, &sources, &clips, playhead) + } + /// The next decoded frame, its `index` rewritten from a source frame to a /// *timeline* frame -- the only frame space that leaves the engine, and the /// one [`PlaybackSession::now`] is in. @@ -274,36 +362,8 @@ impl PlaybackSession { /// a refusal. pub fn import(&mut self, path: &Path) -> crate::Result<()> { let (meta, _) = Demuxer::open(path)?; - if (meta.width, meta.height) != (self.meta.width, self.meta.height) { - return Err(format!( - "{}x{} does not match the timeline's {}x{}", - meta.width, meta.height, self.meta.width, self.meta.height - ) - .into()); - } - // Container frame rates are computed from timescales, so never `==`. - if (meta.frame_rate - self.meta.frame_rate).abs() > 0.01 { - return Err(format!( - "{:.3} fps does not match the timeline's {:.3} fps", - meta.frame_rate, self.meta.frame_rate - ) - .into()); - } - // Whole-probe equality: rate, layout and the esds fields, which the - // audio worker holds every source to anyway. Both silent is a match. - let probe = AudioSession::probe(path)?; let first = AudioSession::probe(&self.project.sources()[0])?; - if probe != first { - return Err(match (probe, first) { - (None, _) => "the file is silent, the timeline has audio".to_string(), - (_, None) => "the file has audio, the timeline is silent".to_string(), - (Some(a), Some(b)) => format!( - "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", - a.params.sample_rate, a.channels, b.params.sample_rate, b.channels - ), - } - .into()); - } + matches_timeline(path, &meta, &self.meta, &first)?; let old_end = self.timeline_duration(); let source = self.project.import(path); @@ -502,6 +562,53 @@ impl PlaybackSession { } } +/// Whether `path`, already demuxed to `meta`, may join a timeline whose +/// parameters are `timeline` and whose audio probes as `first`: same +/// dimensions, same frame rate, same audio parameters or both silent -- one +/// timeline this slice means one set of encoder/device parameters. +/// +/// The `Err` names the property that disagrees, and those strings are what a +/// front-end shows verbatim; [`PlaybackSession::import`] and +/// [`PlaybackSession::open_project`] share them so a file refused at import is +/// refused in the same words at load. +fn matches_timeline( + path: &Path, + meta: &VideoMeta, + timeline: &VideoMeta, + first: &Option, +) -> crate::Result<()> { + if (meta.width, meta.height) != (timeline.width, timeline.height) { + return Err(format!( + "{}x{} does not match the timeline's {}x{}", + meta.width, meta.height, timeline.width, timeline.height + ) + .into()); + } + // Container frame rates are computed from timescales, so never `==`. + if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 { + return Err(format!( + "{:.3} fps does not match the timeline's {:.3} fps", + meta.frame_rate, timeline.frame_rate + ) + .into()); + } + // Whole-probe equality: rate, layout and the esds fields, which the audio + // worker holds every source to anyway. Both silent is a match. + let probe = AudioSession::probe(path)?; + if probe != *first { + return Err(match (probe, first) { + (None, _) => "the file is silent, the timeline has audio".to_string(), + (_, None) => "the file has audio, the timeline is silent".to_string(), + (Some(a), Some(b)) => format!( + "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", + a.params.sample_rate, a.channels, b.params.sample_rate, b.channels + ), + } + .into()); + } + Ok(()) +} + /// `None` for a silent session -- no audio track, no plugin, no daemon, or a /// track the decoder refuses. Dropping the receiver on the way out stops the /// audio decode worker, so a failure here leaves nothing running. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index b14416a..7a4dded 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -67,6 +67,26 @@ impl Project { } } + /// A project rebuilt from a saved edit list -- the load half of + /// [`crate::veproj`]. History is *not* saved, so [`Project::undo`] is + /// `false` until the first edit of the new session. `None` when the parts + /// would break an invariant every other constructor keeps: no clips, an + /// empty clip, or a clip naming a source that is not there. + pub fn from_parts(sources: Vec, clips: Vec) -> Option { + if clips.is_empty() + || clips + .iter() + .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame) + { + return None; + } + Some(Self { + sources: sources.iter().map(|s| canonical(s)).collect(), + clips, + history: Vec::new(), + }) + } + pub fn clips(&self) -> &[Clip] { &self.clips } @@ -109,6 +129,30 @@ impl Project { true } + /// The sources a clip actually names, with the clips reindexed onto them + /// -- what a save writes. Indexes are forever *inside* a session (see + /// [`Project::append_clip`]), so an undone import leaves an orphan source + /// entry behind; writing that orphan to a project file would let a file + /// nothing plays refuse a future load. New indexes are assigned in order of + /// first use, so the same project always emits the same bytes. + pub fn without_orphan_sources(&self) -> (Vec, Vec) { + let mut moved = vec![None; self.sources.len()]; + let mut sources = Vec::new(); + let mut clips = self.clips.clone(); + for c in &mut clips { + let old = c.source; + c.source = match moved[old] { + Some(new) => new, + None => { + sources.push(self.sources[old].clone()); + moved[old] = Some(sources.len() - 1); + sources.len() - 1 + } + }; + } + (sources, clips) + } + /// Length of the timeline in frames. pub fn timeline_frames(&self) -> u32 { self.clips.iter().map(Clip::len).sum() @@ -685,4 +729,67 @@ mod tests { "segments must cover exactly the timeline: {played}" ); } + + #[test] + fn orphan_sources_are_pruned_and_the_clips_reindexed() { + // Import a second file, undo it: source 1 is now an orphan. + let mut p = two_sources(); + assert!(p.undo()); + let (sources, clips) = p.without_orphan_sources(); + assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone"); + assert_eq!(clips, three().clips(), "the clips are untouched"); + + // Three sources where only the middle one is orphaned: the survivors + // renumber, and the clips follow. + let mut p = Project::single(FILE, 9); + assert_eq!(p.import(FILE2), 1); + assert_eq!(p.import("/nonexistent/c.mp4"), 2); + assert!(p.append_clip(2, 4)); + let (sources, clips) = p.without_orphan_sources(); + assert_eq!( + sources, + vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")] + ); + assert_eq!(clips.iter().map(|c| c.source).collect::>(), [0, 1]); + // ...and what comes out is loadable, with the same timeline. + let reloaded = Project::from_parts(sources, clips).expect("from_parts"); + assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); + assert_eq!(reloaded.sources().len(), 2); + } + + #[test] + fn from_parts_has_no_history_and_checks_the_invariants() { + let (sources, clips) = three().without_orphan_sources(); + let mut p = Project::from_parts(sources.clone(), clips.clone()).expect("valid parts"); + assert_eq!(p.clips(), three().clips()); + assert!(!p.undo(), "a loaded project has nothing to undo"); + assert!(p.cut(4), "...and is editable from there"); + assert!(p.undo()); + + assert!(Project::from_parts(sources.clone(), Vec::new()).is_none()); + assert!( + Project::from_parts( + sources.clone(), + vec![Clip { + source: 1, + in_frame: 0, + out_frame: 3 + }] + ) + .is_none(), + "clip names a source that is not there" + ); + assert!( + Project::from_parts( + sources, + vec![Clip { + source: 0, + in_frame: 3, + out_frame: 3 + }] + ) + .is_none(), + "empty clip" + ); + } } diff --git a/crates/engine/src/veproj.rs b/crates/engine/src/veproj.rs new file mode 100644 index 0000000..038b4e5 --- /dev/null +++ b/crates/engine/src/veproj.rs @@ -0,0 +1,382 @@ +//! The project file: a line of text per thing, and nothing else. +//! +//! ```text +//! veproj 1 +//! playhead 90 +//! source test_av.mp4 +//! source /elsewhere/test_av2.mp4 +//! clip 0 120 0 +//! clip 0 120 1 +//! ``` +//! +//! Text because an edit list is three integers and a path, and a path is +//! *bytes* on this platform -- a JSON string would have to lossily decode one. +//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is +//! everything a line-based format cannot carry) and survives round-trip +//! exactly. Paths under the project file's own directory are written relative +//! to it, so a folder holding the media and the `.veproj` can be moved or +//! copied anywhere and still open; anything else is absolute. +//! +//! The parser is strict and every refusal names its 1-based line: a project +//! file is generated, so a line it did not generate is a corrupt file, not a +//! dialect. Structure is checked here (fields, ordering, empty clips, +//! out-of-range source indexes); whether the files on disk still match the +//! timeline is [`crate::PlaybackSession::open_project`]'s business. +//! +//! Writing goes through `.part` and a rename, as an export does, so an +//! interrupted save cannot destroy the previous version of the project. + +use std::ffi::OsString; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::path::{Path, PathBuf}; + +use crate::project::Clip; + +/// First line, exactly. The version is part of it: a v2 reader will accept a +/// `veproj 1` file, and a v1 reader refuses a `veproj 2` one by name. +const MAGIC: &[u8] = b"veproj 1"; + +/// What a project file says: an edit list plus where the playhead stood. +/// Structurally valid by construction -- see [`parse`]. +#[derive(Debug)] +pub struct Document { + /// Absolute, relative entries already joined to the file's own directory. + pub sources: Vec, + pub clips: Vec, + pub playhead: u32, +} + +/// Writes the project to `path`, atomically. `sources` should already be +/// orphan-free ([`crate::Project::without_orphan_sources`]). +pub fn save(path: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> crate::Result<()> { + let dir = path.parent().unwrap_or(Path::new("")); + let mut part = path.to_path_buf().into_os_string(); + part.push(".part"); + let part = PathBuf::from(part); + // The rename publishes the file under the caller's name in one step, on the + // same directory; until it happens the old project file is still the whole + // truth. + let result = std::fs::write(&part, emit(dir, sources, clips, playhead)) + .and_then(|()| std::fs::rename(&part, path)); + if result.is_err() { + let _ = std::fs::remove_file(&part); + } + result.map_err(Into::into) +} + +pub fn load(path: &Path) -> crate::Result { + let data = std::fs::read(path)?; + parse(&data, path.parent().unwrap_or(Path::new(""))) +} + +fn emit(dir: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(MAGIC); + out.push(b'\n'); + out.extend_from_slice(format!("playhead {playhead}\n").as_bytes()); + for s in sources { + out.extend_from_slice(b"source "); + escape(s.strip_prefix(dir).unwrap_or(s), &mut out); + out.push(b'\n'); + } + for c in clips { + out.extend_from_slice( + format!("clip {} {} {}\n", c.in_frame, c.out_frame, c.source).as_bytes(), + ); + } + out +} + +fn parse(data: &[u8], dir: &Path) -> crate::Result { + // One trailing newline is the line terminator of the last line, not an + // empty line -- any further one is, and is refused below. + let body = data.strip_suffix(b"\n").unwrap_or(data); + let mut lines = body.split(|&b| b == b'\n').enumerate(); + let (_, first) = lines.next().unwrap_or((0, &[])); + if first != MAGIC { + return Err(match first.strip_prefix(b"veproj ") { + Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)), + None => "line 1: not a veproj file".to_string(), + } + .into()); + } + + let mut doc = Document { + sources: Vec::new(), + clips: Vec::new(), + playhead: 0, + }; + let mut playhead_seen = false; + for (i, line) in lines { + let n = i + 1; + let (keyword, rest) = match line.iter().position(|&b| b == b' ') { + Some(at) => (&line[..at], &line[at + 1..]), + None => (line, &line[line.len()..]), + }; + match keyword { + b"playhead" => { + if playhead_seen || !doc.sources.is_empty() { + return Err( + format!("line {n}: playhead belongs once, before the sources").into(), + ); + } + doc.playhead = number(rest, n)?; + playhead_seen = true; + } + b"source" => { + if !doc.clips.is_empty() { + return Err(format!("line {n}: source after a clip").into()); + } + if rest.is_empty() { + return Err(format!("line {n}: source without a path").into()); + } + let path = unescape(rest, n)?; + // Relative means "next to the project file", which is what + // makes a whole folder relocatable. + doc.sources.push(if path.is_absolute() { + path + } else { + dir.join(path) + }); + } + b"clip" => { + let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect(); + if fields.len() != 3 { + return Err( + format!("line {n}: clip wants 3 fields, found {}", fields.len()).into(), + ); + } + let clip = Clip { + in_frame: number(fields[0], n)?, + out_frame: number(fields[1], n)?, + source: number(fields[2], n)? as usize, + }; + if clip.out_frame <= clip.in_frame { + return Err(format!( + "line {n}: clip [{}, {}) is empty", + clip.in_frame, clip.out_frame + ) + .into()); + } + if clip.source >= doc.sources.len() { + return Err(format!( + "line {n}: clip names source {} of {}", + clip.source, + doc.sources.len() + ) + .into()); + } + doc.clips.push(clip); + } + // Empty lines land here too: nothing in this format is optional + // whitespace. + _ => { + return Err(format!( + "line {n}: unknown keyword {:?}", + String::from_utf8_lossy(keyword) + ) + .into()); + } + } + } + if doc.clips.is_empty() { + return Err("no clips: an empty timeline is not a project".into()); + } + Ok(doc) +} + +fn number(field: &[u8], line: usize) -> crate::Result { + match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) { + Some(n) => Ok(n), + None => Err(format!( + "line {line}: {:?} is not a number", + String::from_utf8_lossy(field) + ) + .into()), + } +} + +/// The two bytes a line-based format cannot hold, and the escape byte itself. +fn escape(path: &Path, out: &mut Vec) { + for &b in path.as_os_str().as_bytes() { + match b { + b'%' => out.extend_from_slice(b"%25"), + b'\n' => out.extend_from_slice(b"%0A"), + _ => out.push(b), + } + } +} + +/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file +/// may spell a space or a quote that way, and there is no reason to refuse it. +fn unescape(field: &[u8], line: usize) -> crate::Result { + let mut out = Vec::with_capacity(field.len()); + let mut i = 0; + while i < field.len() { + if field[i] != b'%' { + out.push(field[i]); + i += 1; + continue; + } + let byte = field + .get(i + 1..i + 3) + .and_then(|h| std::str::from_utf8(h).ok()) + .and_then(|h| u8::from_str_radix(h, 16).ok()) + .ok_or_else(|| -> crate::Error { + format!("line {line}: truncated % escape in the path").into() + })?; + out.push(byte); + i += 3; + } + Ok(PathBuf::from(OsString::from_vec(out))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn clip(in_frame: u32, out_frame: u32, source: usize) -> Clip { + Clip { + in_frame, + out_frame, + source, + } + } + + /// Two sources, one under the project's own directory and one not, and a + /// clip from each -- the shape every case below starts from. + fn doc() -> (PathBuf, Vec, Vec) { + ( + PathBuf::from("/proj"), + vec![ + PathBuf::from("/proj/a.mp4"), + PathBuf::from("/elsewhere/b.mp4"), + ], + vec![clip(0, 30, 0), clip(10, 20, 1)], + ) + } + + #[test] + fn relative_and_absolute_paths_round_trip() { + let (dir, sources, clips) = doc(); + let bytes = emit(&dir, &sources, &clips, 12); + assert_eq!( + String::from_utf8_lossy(&bytes), + "veproj 1\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\nclip 0 30 0\nclip 10 20 1\n", + "the file under the project directory is written relative to it" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.sources, sources, "relative entries rejoin the dir"); + assert_eq!(back.clips, clips); + assert_eq!(back.playhead, 12); + // ...and emitting the parsed document reproduces the same bytes. + assert_eq!(emit(&dir, &back.sources, &back.clips, back.playhead), bytes); + } + + #[test] + fn escapes_survive_the_bytes_json_would_not() { + let dir = PathBuf::from("/proj"); + // A newline and a percent in a filename, plus a non-UTF-8 byte. + let nasty = PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())); + let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 5, 0)], 0); + assert_eq!( + bytes.iter().filter(|&&b| b == b'\n').count(), + 4, + "the escaped newline must not become a line break" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.sources, vec![nasty]); + } + + #[test] + fn a_wrong_first_line_is_refused_by_name() { + let dir = PathBuf::from("/proj"); + let err = parse(b"veproj 2\nsource a.mp4\nclip 0 5 0\n", &dir) + .unwrap_err() + .to_string(); + assert_eq!(err, "line 1: unsupported version 2"); + for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { + assert_eq!( + parse(junk, &dir).unwrap_err().to_string(), + "line 1: not a veproj file" + ); + } + } + + #[test] + fn malformed_lines_name_their_line_number() { + let dir = PathBuf::from("/proj"); + let cases: [(&[u8], &str); 8] = [ + ( + b"veproj 1\nsource a.mp4\nclip 0 5\n", + "line 3: clip wants 3 fields, found 2", + ), + ( + b"veproj 1\nsource a.mp4\nclip 0 five 0\n", + "line 3: \"five\" is not a number", + ), + ( + b"veproj 1\nsource a.mp4\nclip 5 5 0\n", + "line 3: clip [5, 5) is empty", + ), + ( + b"veproj 1\nsource a.mp4\nclip 7 5 0\n", + "line 3: clip [7, 5) is empty", + ), + ( + b"veproj 1\nsource a.mp4\nclip 0 5 1\n", + "line 3: clip names source 1 of 1", + ), + ( + b"veproj 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n", + "line 4: source after a clip", + ), + ( + b"veproj 1\nsource a.mp4\n\nclip 0 5 0\n", + "line 3: unknown keyword \"\"", + ), + ( + b"veproj 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n", + "line 3: playhead belongs once, before the sources", + ), + ]; + for (bytes, want) in cases { + assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want); + } + } + + #[test] + fn a_project_without_clips_is_not_a_project() { + let dir = PathBuf::from("/proj"); + assert_eq!( + parse(b"veproj 1\nsource a.mp4\n", &dir) + .unwrap_err() + .to_string(), + "no clips: an empty timeline is not a project" + ); + assert_eq!( + parse(b"veproj 1\n", &dir).unwrap_err().to_string(), + "no clips: an empty timeline is not a project" + ); + } + + /// Every truncation of a good file either parses or refuses; none panics. + #[test] + fn truncations_never_panic() { + let (dir, sources, clips) = doc(); + let bytes = emit(&dir, &sources, &clips, 12); + for cut in 0..bytes.len() { + let _ = parse(&bytes[..cut], &dir); + // ...and the same file with a byte lopped off the front, which + // shifts every field into the wrong place. + let _ = parse(&bytes[cut..], &dir); + } + // A % escape at the very end of a line has nothing to consume. + assert_eq!( + parse(b"veproj 1\nsource a%\nclip 0 5 0\n", &dir) + .unwrap_err() + .to_string(), + "line 2: truncated % escape in the path" + ); + } +} diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs new file mode 100644 index 0000000..3506020 --- /dev/null +++ b/crates/engine/tests/saveload.rs @@ -0,0 +1,278 @@ +//! Saving a project and opening it again: the timeline that comes back is the +//! one that went in, a folder of media plus its `.veproj` can be moved +//! anywhere, and every way the files on disk can have changed underneath is a +//! refusal that says which file and why. +//! +//! ```text +//! cargo test -p engine --release --test saveload -- --nocapture +//! ``` + +use std::path::{Path, PathBuf}; + +use engine::PlaybackSession; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// A fresh directory to litter. Canonical, because the saved paths are +/// relative to it and `Project` canonicalises what it is handed. +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ve_saveload_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + std::fs::canonicalize(&dir).expect("canonical scratch dir") +} + +fn copy_in(dir: &Path, name: &str) -> PathBuf { + let to = dir.join(name); + std::fs::copy(asset(name), &to).expect("copy the fixture"); + to +} + +/// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline +/// with something to lose in every field. +fn edited(dir: &Path) -> PlaybackSession { + let mut session = PlaybackSession::open(copy_in(dir, "test_av.mp4")).expect("open"); + session + .import(©_in(dir, "test_av2.mp4")) + .expect("import the second file"); + assert!(session.cut_at(2.0), "cut inside the first file"); + assert!(session.cut_at(6.5), "cut inside the second file"); + assert!(session.delete_clip(1), "drop the second half of the first"); + session.seek(3.0); + assert_eq!(session.timeline_duration(), 6.0); + session +} + +/// What has to survive a round trip, all of it public API. +fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec, f64) { + ( + session.clip_spans_by_source(), + session.sources().to_vec(), + session.timeline_duration(), + ) +} + +#[test] +fn a_saved_project_reopens_as_the_same_timeline() { + let dir = scratch("round_trip"); + let saved = edited(&dir); + let path = dir.join("edit.veproj"); + saved.save_project(&path).expect("save"); + + let mut loaded = PlaybackSession::open_project(&path).expect("open the project"); + assert_eq!(shape(&loaded), shape(&saved), "clips, sources and duration"); + assert!( + (loaded.now() - saved.now()).abs() < 1.0 / loaded.meta().frame_rate, + "playhead landed at {:.3}s, saved at {:.3}s", + loaded.now(), + saved.now() + ); + assert!(!loaded.is_playing(), "a loaded project starts paused"); + assert!(!loaded.undo(), "history is not saved"); + + // Saving what was loaded reproduces the file byte for byte -- the format + // has no state the round trip drops. + let again = dir.join("again.veproj"); + loaded + .save_project(&again) + .expect("save the loaded project"); + assert_eq!( + std::fs::read(&path).unwrap(), + std::fs::read(&again).unwrap(), + "save -> load -> save is not a fixed point" + ); + assert!(!path.with_extension("veproj.part").exists(), "left a .part"); +} + +#[test] +fn a_folder_of_media_and_its_project_can_be_moved() { + let from = scratch("relocate_from"); + let saved = edited(&from); + saved.save_project(&from.join("edit.veproj")).expect("save"); + drop(saved); + + let to = scratch("relocate_to"); + for name in ["test_av.mp4", "test_av2.mp4", "edit.veproj"] { + std::fs::copy(from.join(name), to.join(name)).expect("copy"); + } + // The originals go away entirely: nothing absolute can be resolving here. + std::fs::remove_dir_all(&from).expect("remove the original folder"); + + let moved = PlaybackSession::open_project(&to.join("edit.veproj")).expect("open the copy"); + assert_eq!(moved.timeline_duration(), 6.0); + assert!( + moved.sources().iter().all(|s| s.starts_with(&to)), + "sources did not follow the folder: {:?}", + moved.sources() + ); +} + +#[test] +fn orphan_sources_are_not_written() { + let dir = scratch("orphans"); + let mut session = PlaybackSession::open(copy_in(&dir, "test_av.mp4")).expect("open"); + session + .import(©_in(&dir, "test_av2.mp4")) + .expect("import"); + assert!(session.undo(), "take the import back"); + assert_eq!( + session.sources().len(), + 2, + "the orphan entry stays in-session" + ); + + let path = dir.join("orphan.veproj"); + session.save_project(&path).expect("save"); + let text = std::fs::read_to_string(&path).expect("read back"); + assert_eq!( + text.lines().filter(|l| l.starts_with("source ")).count(), + 1, + "the orphan reached the file:\n{text}" + ); + + // And the load survives the orphan's file disappearing, which is the whole + // point of pruning it. + std::fs::remove_file(dir.join("test_av2.mp4")).expect("unlink the orphan"); + let loaded = PlaybackSession::open_project(&path).expect("open the project"); + assert_eq!(loaded.sources().len(), 1); + assert_eq!(loaded.timeline_duration(), 5.0); +} + +#[test] +fn a_source_that_vanished_is_refused_by_name() { + let dir = scratch("missing"); + let session = edited(&dir); + let path = dir.join("edit.veproj"); + session.save_project(&path).expect("save"); + drop(session); + + let gone = dir.join("test_av2.mp4"); + std::fs::remove_file(&gone).expect("unlink"); + let err = PlaybackSession::open_project(&path) + .err() + .expect("a project whose source is gone must not open") + .to_string(); + assert!( + err.contains("test_av2.mp4"), + "the refusal must name the file: {err}" + ); + + // The first source is no different -- it is simply refused earlier. + std::fs::remove_file(dir.join("test_av.mp4")).expect("unlink"); + let err = PlaybackSession::open_project(&path) + .err() + .expect("no first source, no session") + .to_string(); + assert!(err.contains("test_av.mp4"), "{err}"); +} + +#[test] +fn a_source_that_shrank_is_refused_by_clip() { + let dir = scratch("shrunk"); + copy_in(&dir, "test_av.mp4"); + let path = dir.join("shrunk.veproj"); + // Hand-written: a clip that ran to frame 10000 of a 150-frame file, which + // is what re-encoding a source shorter leaves behind. + std::fs::write( + &path, + "veproj 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\nclip 30 10000 0\n", + ) + .expect("write"); + let err = PlaybackSession::open_project(&path) + .err() + .expect("a clip past the end of its file must not open") + .to_string(); + assert!( + err.contains("clip 1") && err.contains("test_av.mp4") && err.contains("150"), + "the refusal must name the clip, the file and its length: {err}" + ); + + // One frame short of the end is still inside the file. + std::fs::write( + &path, + "veproj 1\nplayhead 0\nsource test_av.mp4\nclip 0 150 0\n", + ) + .expect("write"); + let whole = PlaybackSession::open_project(&path).expect("the exact length is legal"); + assert_eq!(whole.timeline_duration(), 5.0); +} + +#[test] +fn a_project_that_names_itself_is_refused() { + let dir = scratch("self_reference"); + let path = dir.join("ouroboros.veproj"); + std::fs::write( + &path, + "veproj 1\nplayhead 0\nsource ouroboros.veproj\nclip 0 30 0\n", + ) + .expect("write"); + let err = PlaybackSession::open_project(&path) + .err() + .expect("a project is not a video") + .to_string(); + assert!(err.contains("ouroboros.veproj"), "{err}"); +} + +#[test] +fn malformed_files_are_numbered_errors_and_never_panics() { + let dir = scratch("malformed"); + copy_in(&dir, "test_av.mp4"); + let path = dir.join("bad.veproj"); + let good = "veproj 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n"; + + for (text, want) in [ + ("veproj 2\nsource test_av.mp4\nclip 0 30 0\n", "line 1"), + ("not a project at all\n", "line 1"), + ("veproj 1\nsource test_av.mp4\nclip 0 30\n", "line 3"), + ("veproj 1\nsource test_av.mp4\nclip 0 30 4\n", "line 3"), + ("veproj 1\nsource test_av.mp4\nclip 30 30 0\n", "line 3"), + ("veproj 1\nsource test_av.mp4\n\nclip 0 30 0\n", "line 3"), + ("veproj 1\nsource test_av.mp4\nwhat 1\n", "line 3"), + ] { + std::fs::write(&path, text).expect("write"); + let err = PlaybackSession::open_project(&path) + .err() + .unwrap_or_else(|| panic!("accepted {text:?}")) + .to_string(); + assert!(err.starts_with(want), "{text:?} -> {err}"); + } + + // Every truncation of a good file: some are valid shorter projects, none + // may panic or be reported as anything but an error. + for cut in 0..good.len() { + std::fs::write(&path, &good[..cut]).expect("write"); + let _ = PlaybackSession::open_project(&path); + } + // ...and a file that is not there at all. + std::fs::remove_file(&path).expect("unlink"); + assert!(PlaybackSession::open_project(&path).is_err()); +} + +#[test] +fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { + let dir = scratch("mismatch"); + copy_in(&dir, "test_av.mp4"); + std::fs::copy(asset("test_mismatch.mp4"), dir.join("test_av2.mp4")).expect("substitute"); + let path = dir.join("swapped.veproj"); + std::fs::write( + &path, + "veproj 1\nplayhead 0\nsource test_av.mp4\nsource test_av2.mp4\nclip 0 30 0\nclip 0 30 1\n", + ) + .expect("write"); + let err = PlaybackSession::open_project(&path) + .err() + .expect("a source that stopped matching must not open") + .to_string(); + // The suffix is `import`'s own refusal, word for word. + assert_eq!( + err, + format!( + "source {}: 640x360 does not match the timeline's 1280x720", + dir.join("test_av2.mp4").display() + ) + ); +}