forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

saveload.rs388 lines, 14.3 KiBHistoryRawDownload
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 `.edith` 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
10use std::path::{Path, PathBuf};
11
12use engine::PlaybackSession;
13
14fn 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.
22fn 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
29fn 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.
37fn 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.
51fn 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/// The version-1 promise: a file written before the lanes existed still opens,
60/// as one grouped video+audio pair per clip laid end to end, and saving it
61/// again writes version 2 -- which reopens as the same timeline.
62#[test]
63fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() {
64 let dir = scratch("v1");
65 copy_in(&dir, "test_av.mp4");
66 let path = dir.join("old.edith");
67 // 60 frames of picture from two clips: [0,30) then [60,90) of the source.
68 std::fs::write(
69 &path,
70 "edith 1\nplayhead 45\nsource test_av.mp4\nclip 0 30 0\nclip 60 90 0\n",
71 )
72 .expect("write a v1 file");
73
74 let loaded = PlaybackSession::open_project(&path).expect("a v1 file still opens");
75 let fps = loaded.meta().frame_rate;
76 assert_eq!(
77 loaded.clip_spans_by_source(),
78 vec![(0.0, 30.0 / fps, 0), (30.0 / fps, 30.0 / fps, 0)],
79 "v1 clips queue up, the second starting where the first ended"
80 );
81 assert_eq!(
82 loaded.lane_spans_by_source(engine::project::Lane::Audio),
83 loaded.clip_spans_by_source(),
84 "both lanes, fully grouped: a v1 timeline had no holes"
85 );
86 assert!(
87 (loaded.now() - 45.0 / fps).abs() < 1.0 / fps,
88 "playhead kept"
89 );
90
91 // Saved again it is v2, and v2 round-trips to the same timeline.
92 let v2 = dir.join("new.edith");
93 loaded.save_project(&v2).expect("save");
94 let text = std::fs::read_to_string(&v2).expect("read back");
95 assert!(text.starts_with("edith 2\n"), "{text}");
96 assert_eq!(
97 text.lines().filter(|l| l.starts_with("video ")).count(),
98 2,
99 "{text}"
100 );
101 assert_eq!(
102 text.lines().filter(|l| l.starts_with("audio ")).count(),
103 2,
104 "{text}"
105 );
106 let again = PlaybackSession::open_project(&v2).expect("open the v2 file");
107 assert_eq!(shape(&again), shape(&loaded));
108 // ...and re-saving it is byte-identical, so a round trip is stable.
109 let third = dir.join("third.edith");
110 again.save_project(&third).expect("save");
111 assert_eq!(std::fs::read(&third).expect("read"), text.as_bytes());
112}
113
114#[test]
115fn a_saved_project_reopens_as_the_same_timeline() {
116 let dir = scratch("round_trip");
117 let saved = edited(&dir);
118 let path = dir.join("edit.edith");
119 saved.save_project(&path).expect("save");
120
121 let mut loaded = PlaybackSession::open_project(&path).expect("open the project");
122 assert_eq!(shape(&loaded), shape(&saved), "clips, sources and duration");
123 assert!(
124 (loaded.now() - saved.now()).abs() < 1.0 / loaded.meta().frame_rate,
125 "playhead landed at {:.3}s, saved at {:.3}s",
126 loaded.now(),
127 saved.now()
128 );
129 assert!(!loaded.is_playing(), "a loaded project starts paused");
130 assert!(!loaded.undo(), "history is not saved");
131
132 // Saving what was loaded reproduces the file byte for byte -- the format
133 // has no state the round trip drops.
134 let again = dir.join("again.edith");
135 loaded
136 .save_project(&again)
137 .expect("save the loaded project");
138 assert_eq!(
139 std::fs::read(&path).unwrap(),
140 std::fs::read(&again).unwrap(),
141 "save -> load -> save is not a fixed point"
142 );
143 assert!(!path.with_extension("edith.part").exists(), "left a .part");
144}
145
146#[test]
147fn a_folder_of_media_and_its_project_can_be_moved() {
148 let from = scratch("relocate_from");
149 let saved = edited(&from);
150 saved.save_project(&from.join("edit.edith")).expect("save");
151 drop(saved);
152
153 let to = scratch("relocate_to");
154 for name in ["test_av.mp4", "test_av2.mp4", "edit.edith"] {
155 std::fs::copy(from.join(name), to.join(name)).expect("copy");
156 }
157 // The originals go away entirely: nothing absolute can be resolving here.
158 std::fs::remove_dir_all(&from).expect("remove the original folder");
159
160 let moved = PlaybackSession::open_project(&to.join("edit.edith")).expect("open the copy");
161 assert_eq!(moved.timeline_duration(), 6.0);
162 assert!(
163 moved.sources().iter().all(|s| s.starts_with(&to)),
164 "sources did not follow the folder: {:?}",
165 moved.sources()
166 );
167}
168
169#[test]
170fn orphan_sources_are_not_written() {
171 let dir = scratch("orphans");
172 let mut session = PlaybackSession::open(copy_in(&dir, "test_av.mp4")).expect("open");
173 session
174 .import(&copy_in(&dir, "test_av2.mp4"))
175 .expect("import");
176 assert!(session.undo(), "take the import back");
177 assert_eq!(
178 session.sources().len(),
179 2,
180 "the orphan entry stays in-session"
181 );
182
183 let path = dir.join("orphan.edith");
184 session.save_project(&path).expect("save");
185 let text = std::fs::read_to_string(&path).expect("read back");
186 assert_eq!(
187 text.lines().filter(|l| l.starts_with("source ")).count(),
188 1,
189 "the orphan reached the file:\n{text}"
190 );
191
192 // And the load survives the orphan's file disappearing, which is the whole
193 // point of pruning it.
194 std::fs::remove_file(dir.join("test_av2.mp4")).expect("unlink the orphan");
195 let loaded = PlaybackSession::open_project(&path).expect("open the project");
196 assert_eq!(loaded.sources().len(), 1);
197 assert_eq!(loaded.timeline_duration(), 5.0);
198}
199
200#[test]
201fn a_source_that_vanished_is_refused_by_name() {
202 let dir = scratch("missing");
203 let session = edited(&dir);
204 let path = dir.join("edit.edith");
205 session.save_project(&path).expect("save");
206 drop(session);
207
208 let gone = dir.join("test_av2.mp4");
209 std::fs::remove_file(&gone).expect("unlink");
210 let err = PlaybackSession::open_project(&path)
211 .err()
212 .expect("a project whose source is gone must not open")
213 .to_string();
214 assert!(
215 err.contains("test_av2.mp4"),
216 "the refusal must name the file: {err}"
217 );
218
219 // The first source is no different -- it is simply refused earlier.
220 std::fs::remove_file(dir.join("test_av.mp4")).expect("unlink");
221 let err = PlaybackSession::open_project(&path)
222 .err()
223 .expect("no first source, no session")
224 .to_string();
225 assert!(err.contains("test_av.mp4"), "{err}");
226}
227
228#[test]
229fn a_source_that_shrank_is_refused_by_clip() {
230 let dir = scratch("shrunk");
231 copy_in(&dir, "test_av.mp4");
232 let path = dir.join("shrunk.edith");
233 // Hand-written: a clip that ran to frame 10000 of a 150-frame file, which
234 // is what re-encoding a source shorter leaves behind.
235 std::fs::write(
236 &path,
237 "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\nclip 30 10000 0\n",
238 )
239 .expect("write");
240 let err = PlaybackSession::open_project(&path)
241 .err()
242 .expect("a clip past the end of its file must not open")
243 .to_string();
244 assert!(
245 err.contains("clip 1") && err.contains("test_av.mp4") && err.contains("150"),
246 "the refusal must name the clip, the file and its length: {err}"
247 );
248
249 // One frame short of the end is still inside the file.
250 std::fs::write(
251 &path,
252 "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 150 0\n",
253 )
254 .expect("write");
255 let whole = PlaybackSession::open_project(&path).expect("the exact length is legal");
256 assert_eq!(whole.timeline_duration(), 5.0);
257}
258
259/// A refusal must *return*. Opening a project starts decoding source 0 before
260/// it has validated anything, so by the time a later source is refused the
261/// worker is several frames in -- and with a two-frame channel that nobody is
262/// draining, it is parked in `send`. Tearing that down in the wrong order joins
263/// a thread that is waiting for a receiver the same scope still holds, and the
264/// app hangs on a bad project file instead of showing the error.
265///
266/// The many sources are what make the park a certainty rather than a race: each
267/// one is opened and probed before the clip check that refuses, which is far
268/// longer than the few frames it takes to fill the channel.
269#[test]
270fn a_refused_project_does_not_hang_on_its_own_decoder() {
271 let dir = scratch("refusal_hang");
272 copy_in(&dir, "test_av.mp4");
273 let path = dir.join("refused.edith");
274 let mut text = String::from("edith 1\nplayhead 0\n");
275 for _ in 0..1024 {
276 text.push_str("source test_av.mp4\n");
277 }
278 // Legal until the last line, which runs off the end of a 150-frame file.
279 text.push_str("clip 0 150 0\nclip 0 10000 0\n");
280 std::fs::write(&path, &text).expect("write");
281
282 let (tx, rx) = std::sync::mpsc::sync_channel(1);
283 let probe = path.clone();
284 std::thread::spawn(move || {
285 let err = PlaybackSession::open_project(&probe)
286 .err()
287 .map(|e| e.to_string());
288 let _ = tx.send(err);
289 });
290 match rx.recv_timeout(std::time::Duration::from_secs(60)) {
291 Ok(Some(err)) => assert!(err.contains("150"), "refused, but not by name: {err}"),
292 Ok(None) => panic!("a clip past the end of its file must not open"),
293 Err(_) => panic!(
294 "open_project hung on a refusal: its own decode worker is parked in \
295 send and the teardown is waiting for it"
296 ),
297 }
298}
299
300#[test]
301fn a_project_that_names_itself_is_refused() {
302 let dir = scratch("self_reference");
303 let path = dir.join("ouroboros.edith");
304 std::fs::write(
305 &path,
306 "edith 1\nplayhead 0\nsource ouroboros.edith\nclip 0 30 0\n",
307 )
308 .expect("write");
309 let err = PlaybackSession::open_project(&path)
310 .err()
311 .expect("a project is not a video")
312 .to_string();
313 assert!(err.contains("ouroboros.edith"), "{err}");
314}
315
316#[test]
317fn malformed_files_are_numbered_errors_and_never_panics() {
318 let dir = scratch("malformed");
319 copy_in(&dir, "test_av.mp4");
320 let path = dir.join("bad.edith");
321 let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n";
322
323 for (text, want) in [
324 ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 1"),
325 ("not a project at all\n", "line 1"),
326 // Dialects do not mix: lane lines are v2's, `clip` is v1's.
327 ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 3"),
328 ("edith 1\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 3"),
329 ("edith 2\nsource test_av.mp4\nvideo 0 0 30 0\n", "line 3"),
330 (
331 "edith 2\nsource test_av.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
332 "line 4",
333 ),
334 ("edith 1\nsource test_av.mp4\nclip 0 30\n", "line 3"),
335 ("edith 1\nsource test_av.mp4\nclip 0 30 4\n", "line 3"),
336 ("edith 1\nsource test_av.mp4\nclip 30 30 0\n", "line 3"),
337 ("edith 1\nsource test_av.mp4\n\nclip 0 30 0\n", "line 3"),
338 ("edith 1\nsource test_av.mp4\nwhat 1\n", "line 3"),
339 // Crafted numbers: `start + len` used to wrap past the top of `u32`,
340 // and a wrapped end walks straight through the overlap check.
341 (
342 "edith 2\nsource test_av.mp4\nvideo 4294967290 0 30 0 -\n",
343 "line 3",
344 ),
345 ] {
346 std::fs::write(&path, text).expect("write");
347 let err = PlaybackSession::open_project(&path)
348 .err()
349 .unwrap_or_else(|| panic!("accepted {text:?}"))
350 .to_string();
351 assert!(err.starts_with(want), "{text:?} -> {err}");
352 }
353
354 // Every truncation of a good file: some are valid shorter projects, none
355 // may panic or be reported as anything but an error.
356 for cut in 0..good.len() {
357 std::fs::write(&path, &good[..cut]).expect("write");
358 let _ = PlaybackSession::open_project(&path);
359 }
360 // ...and a file that is not there at all.
361 std::fs::remove_file(&path).expect("unlink");
362 assert!(PlaybackSession::open_project(&path).is_err());
363}
364
365#[test]
366fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
367 let dir = scratch("mismatch");
368 copy_in(&dir, "test_av.mp4");
369 std::fs::copy(asset("test_mismatch.mp4"), dir.join("test_av2.mp4")).expect("substitute");
370 let path = dir.join("swapped.edith");
371 std::fs::write(
372 &path,
373 "edith 1\nplayhead 0\nsource test_av.mp4\nsource test_av2.mp4\nclip 0 30 0\nclip 0 30 1\n",
374 )
375 .expect("write");
376 let err = PlaybackSession::open_project(&path)
377 .err()
378 .expect("a source that stopped matching must not open")
379 .to_string();
380 // The suffix is `import`'s own refusal, word for word.
381 assert_eq!(
382 err,
383 format!(
384 "source {}: 640x360 does not match the timeline's 1280x720",
385 dir.join("test_av2.mp4").display()
386 )
387 );
388}