forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB08af6bcTahinli3 months ago87 commits

edith.rs909 lines, 35.8 KiBHistoryRawDownload
1//! The project file: a line of text per thing, and nothing else.
2//!
3//! ```text
4//! edith 4
5//! playhead 90
6//! source 0 test_av.mp4
7//! source 1 /elsewhere/test_av2.mp4
8//! video 1 0 0 120 0 0
9//! audio 1 0 0 120 0 0
10//! video 2 120 0 120 1 -
11//! audio 2
12//! ```
13//!
14//! A source line is `source <audio stream> <path>`: which of the file's audio
15//! tracks that source plays, in the file order
16//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
17//! stream first because a path runs to the end of the line (it may hold
18//! spaces) and an optional *trailing* field could not be told from one.
19//!
20//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link>`: which lane
21//! the clip is on -- its kind and its 1-based number among the lanes of that
22//! kind, the [`crate::project::Lane::label`] a header column shows -- then where
23//! the clip sits on the timeline, the half-open source range it plays, the file
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.
27//!
28//! A lane is declared by the clips on it, in the order the lanes are displayed
29//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
30//! is the only way an empty lane could still be there on the way back. A lane
31//! number may not skip one of its kind.
32//!
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.
41//!
42//! Text because an edit list is a few integers and a path, and a path is
43//! *bytes* on this platform -- a JSON string would have to lossily decode one.
44//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
45//! everything a line-based format cannot carry) and survives round-trip
46//! exactly. Paths under the project file's own directory are written relative
47//! to it, so a folder holding the media and the `.edith` can be moved or
48//! copied anywhere and still open; anything else is absolute.
49//!
50//! The parser is strict and every refusal names its 1-based line: a project
51//! file is generated, so a line it did not generate is a corrupt file, not a
52//! dialect. Structure is checked here (fields, ordering, empty clips,
53//! out-of-range source indexes); whether the files on disk still match the
54//! timeline is [`crate::PlaybackSession::open_project`]'s business.
55//!
56//! Writing goes through `<path>.part` and a rename, as an export does, so an
57//! interrupted save cannot destroy the previous version of the project. The
58//! bytes are fsynced before the rename and the directory after it, so what a
59//! power loss can lose is a whole save, never half of one under the real name.
60
61use std::ffi::OsString;
62use std::io::Write;
63use std::os::unix::ffi::{OsStrExt, OsStringExt};
64use std::path::{Path, PathBuf};
65
66use crate::project::{Clip, Lane, LaneKind, Source};
67
68/// What [`save`] writes. Read support goes back to `edith 1`; see the module
69/// docs for what those dialects looked like.
70const MAGIC: &[u8] = b"edith 4";
71const MAGIC_V3: &[u8] = b"edith 3";
72const MAGIC_V2: &[u8] = b"edith 2";
73const MAGIC_V1: &[u8] = b"edith 1";
74
75/// What a project file says: an edit list plus where the playhead stood.
76/// Structurally valid by construction -- see [`parse`].
77#[derive(Debug)]
78pub struct Document {
79 /// Paths absolute, relative entries already joined to the file's own
80 /// directory.
81 pub sources: Vec<Source>,
82 /// Every lane, in display order, which is the order
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>)>,
86 pub playhead: u32,
87}
88
89/// Writes the project to `path`, atomically. `sources` should already be
90/// orphan-free ([`crate::Project::without_orphan_sources`]).
91pub fn save(
92 path: &Path,
93 sources: &[Source],
94 lanes: &[(LaneKind, Vec<Clip>)],
95 playhead: u32,
96) -> crate::Result<()> {
97 let dir = project_dir(path);
98 let mut part = path.to_path_buf().into_os_string();
99 part.push(".part");
100 let part = PathBuf::from(part);
101 // The rename publishes the file under the caller's name in one step, on the
102 // same directory; until it happens the old project file is still the whole
103 // truth. `sync_all` puts the bytes on the disk before that name exists, and
104 // the second one puts the name itself there.
105 let result = std::fs::File::create(&part)
106 .and_then(|mut f| {
107 f.write_all(&emit(&dir, sources, lanes, playhead))?;
108 f.sync_all()
109 })
110 .and_then(|()| std::fs::rename(&part, path))
111 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
112 if result.is_err() {
113 let _ = std::fs::remove_file(&part);
114 }
115 result.map_err(Into::into)
116}
117
118pub fn load(path: &Path) -> crate::Result<Document> {
119 let data = std::fs::read(path)?;
120 parse(&data, path.parent().unwrap_or(Path::new("")))
121}
122
123/// The directory a project file's relative source lines are measured from, in
124/// the same canonical form [`crate::Project`] keeps its sources in -- without
125/// that the prefix simply never matches and every line comes out absolute,
126/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
127/// a bare filename is `""`). Canonicalizing fails only if the directory does
128/// not exist, and then the write is about to fail anyway.
129fn project_dir(path: &Path) -> PathBuf {
130 let dir = path
131 .parent()
132 .filter(|p| !p.as_os_str().is_empty())
133 .unwrap_or(Path::new("."));
134 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
135}
136
137fn emit(dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec<Clip>)], playhead: u32) -> Vec<u8> {
138 let mut out = Vec::new();
139 out.extend_from_slice(MAGIC);
140 out.push(b'\n');
141 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
142 for s in sources {
143 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
144 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
145 out.push(b'\n');
146 }
147 // Lane by lane rather than interleaved by time: a lane reads as a list, the
148 // parser gets its sortedness check for free from the order it is in, and
149 // the lanes come back out in the order they are displayed in.
150 let (mut video, mut audio) = (0, 0);
151 for (kind, clips) in lanes {
152 let (keyword, ord) = match kind {
153 LaneKind::Video => {
154 video += 1;
155 ("video", video)
156 }
157 LaneKind::Audio => {
158 audio += 1;
159 ("audio", audio)
160 }
161 };
162 // A lane is declared by its clips; one holding nothing has to say so on
163 // a line of its own, or the lane itself would not survive the round trip.
164 if clips.is_empty() {
165 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
166 }
167 for c in clips {
168 let link = c.link.map_or("-".to_string(), |l| l.to_string());
169 out.extend_from_slice(
170 format!(
171 "{keyword} {ord} {} {} {} {} {link}\n",
172 c.start, c.in_frame, c.out_frame, c.source
173 )
174 .as_bytes(),
175 );
176 }
177 }
178 out
179}
180
181fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
182 // One trailing newline is the line terminator of the last line, not an
183 // empty line -- any further one is, and is refused below.
184 let body = data.strip_suffix(b"\n").unwrap_or(data);
185 let mut lines = body.split(|&b| b == b'\n').enumerate();
186 let (_, first) = lines.next().unwrap_or((0, &[]));
187 let v1 = first == MAGIC_V1;
188 // The dialects that wrote a source line without its stream field. Reading
189 // one is the whole of what "an old project still opens" means here.
190 let streamless = v1 || first == MAGIC_V2;
191 // ...and the one that numbers its lanes. Every older one held two.
192 let v4 = first == MAGIC;
193 if !v4 && !streamless && first != MAGIC_V3 {
194 return Err(match first.strip_prefix(b"edith ") {
195 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
196 None => "line 1: not a edith file".to_string(),
197 }
198 .into());
199 }
200
201 let mut doc = Document {
202 sources: Vec::new(),
203 // v4 declares its lanes as they come; every dialect before it held
204 // exactly `V1` and `A1`, either of which could be empty.
205 lanes: if v4 {
206 Vec::new()
207 } else {
208 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
209 },
210 playhead: 0,
211 };
212 let mut playhead_seen = false;
213 // Where the next v1 clip is placed: that dialect had no `start` field, the
214 // clips simply queued up.
215 let mut queued = 0u32;
216 for (i, line) in lines {
217 let n = i + 1;
218 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
219 Some(at) => (&line[..at], &line[at + 1..]),
220 None => (line, &line[line.len()..]),
221 };
222 match keyword {
223 b"playhead" => {
224 if playhead_seen || !doc.sources.is_empty() {
225 return Err(
226 format!("line {n}: playhead belongs once, before the sources").into(),
227 );
228 }
229 doc.playhead = number(rest, n)?;
230 playhead_seen = true;
231 }
232 b"source" => {
233 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
234 return Err(format!("line {n}: source after a clip").into());
235 }
236 // The stream comes first and the path is everything after it,
237 // spaces and all; an older dialect wrote no stream and meant 0.
238 let (audio_stream, rest) = if streamless {
239 (0, rest)
240 } else {
241 // No space at all still has to reach `number`, so a v2 line
242 // in a v3 file is refused as the missing field it is rather
243 // than as a missing path.
244 let at = rest.iter().position(|&b| b == b' ');
245 (
246 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
247 &rest[at.map_or(rest.len(), |at| at + 1)..],
248 )
249 };
250 if rest.is_empty() {
251 return Err(format!("line {n}: source without a path").into());
252 }
253 let path = unescape(rest, n)?;
254 // Relative means "next to the project file", which is what
255 // makes a whole folder relocatable.
256 doc.sources.push(Source {
257 path: if path.is_absolute() {
258 path
259 } else {
260 dir.join(path)
261 },
262 audio_stream,
263 });
264 }
265 // v1: one lane, no placement, no groups. Every clip becomes one
266 // grouped video+audio pair laid where the queue reached, which is
267 // what the file always meant.
268 b"clip" if v1 => {
269 let f = fields(rest, 3, "clip", n)?;
270 let clip = check(
271 Clip {
272 start: queued,
273 in_frame: number(f[0], n)?,
274 out_frame: number(f[1], n)?,
275 source: number(f[2], n)? as usize,
276 link: Some(doc.lanes[0].1.len() as u32),
277 },
278 &doc,
279 n,
280 )?;
281 queued = clip.end();
282 doc.lanes[0].1.push(clip);
283 doc.lanes[1].1.push(clip);
284 }
285 b"video" | b"audio" if !v1 => {
286 let kind = match keyword {
287 b"video" => LaneKind::Video,
288 _ => LaneKind::Audio,
289 };
290 // v4 names the lane, and a line naming nothing else is an empty
291 // lane's whole existence. Older dialects had one lane per kind.
292 let (ord, rest) = if v4 {
293 let at = rest.iter().position(|&b| b == b' ');
294 (
295 number(&rest[..at.unwrap_or(rest.len())], n)?,
296 &rest[at.map_or(rest.len(), |at| at + 1)..],
297 )
298 } else {
299 (1, rest)
300 };
301 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
302 if v4 && rest.is_empty() {
303 continue;
304 }
305 let f = fields(rest, 5, "clip", n)?;
306 let clip = check(
307 Clip {
308 start: number(f[0], n)?,
309 in_frame: number(f[1], n)?,
310 out_frame: number(f[2], n)?,
311 source: number(f[3], n)? as usize,
312 link: match f[4] {
313 b"-" => None,
314 field => Some(number(field, n)?),
315 },
316 },
317 &doc,
318 n,
319 )?;
320 let lane = &mut doc.lanes[at].1;
321 // The sorted, non-overlapping placement invariant, checked at
322 // the only door untrusted clips come in through.
323 if lane.last().is_some_and(|prev| prev.end() > clip.start) {
324 return Err(format!(
325 "line {n}: clip at {} overlaps the one before it, or comes before it",
326 clip.start
327 )
328 .into());
329 }
330 lane.push(clip);
331 }
332 // Empty lines land here too: nothing in this format is optional
333 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
334 // is a file mixing dialects, and is refused the same way.
335 _ => {
336 return Err(format!(
337 "line {n}: unknown keyword {:?}",
338 String::from_utf8_lossy(keyword)
339 )
340 .into());
341 }
342 }
343 }
344 if doc.lanes.iter().all(|(_, clips)| clips.is_empty()) {
345 return Err("no clips: an empty timeline is not a project".into());
346 }
347 Ok(doc)
348}
349
350/// Where the lane a v4 line names sits, appending it if this is its first line.
351/// Lanes arrive in display order, so a number that skips one of its kind is a
352/// lane that was never declared, and is refused by the name it would have had.
353fn lane_of(
354 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
355 kind: LaneKind,
356 ord: u32,
357 line: usize,
358) -> crate::Result<usize> {
359 let mut seen = 0;
360 for (at, (k, _)) in lanes.iter().enumerate() {
361 if *k == kind {
362 seen += 1;
363 if seen == ord {
364 return Ok(at);
365 }
366 }
367 }
368 if ord != seen + 1 {
369 return Err(match ord.checked_sub(1) {
370 Some(prev) => format!(
371 "line {line}: lane {} comes before {}",
372 Lane::new(kind, prev as usize).label(),
373 Lane::new(kind, seen as usize).label()
374 ),
375 None => format!("line {line}: lane numbers start at 1"),
376 }
377 .into());
378 }
379 lanes.push((kind, Vec::new()));
380 Ok(lanes.len() - 1)
381}
382
383/// Splits a line's fields, refusing the wrong count by name.
384fn fields<'a>(
385 rest: &'a [u8],
386 want: usize,
387 what: &str,
388 line: usize,
389) -> crate::Result<Vec<&'a [u8]>> {
390 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
391 if fields.len() != want {
392 return Err(format!(
393 "line {line}: {what} wants {want} fields, found {}",
394 fields.len()
395 )
396 .into());
397 }
398 Ok(fields)
399}
400
401/// The per-clip structure checks both dialects share.
402fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
403 if clip.out_frame <= clip.in_frame {
404 return Err(format!(
405 "line {line}: clip [{}, {}) is empty",
406 clip.in_frame, clip.out_frame
407 )
408 .into());
409 }
410 if clip.source >= doc.sources.len() {
411 return Err(format!(
412 "line {line}: clip names source {} of {}",
413 clip.source,
414 doc.sources.len()
415 )
416 .into());
417 }
418 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
419 // adds `start + len` as plain `u32`, which panics in debug and wraps in
420 // release on a crafted file. Bound it here, at the door.
421 if clip.start.checked_add(clip.len()).is_none() {
422 return Err(format!(
423 "line {line}: clip at {} runs past the last frame there is",
424 clip.start
425 )
426 .into());
427 }
428 Ok(clip)
429}
430
431fn number(field: &[u8], line: usize) -> crate::Result<u32> {
432 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
433 Some(n) => Ok(n),
434 None => Err(format!(
435 "line {line}: {:?} is not a number",
436 String::from_utf8_lossy(field)
437 )
438 .into()),
439 }
440}
441
442/// The two bytes a line-based format cannot hold, and the escape byte itself.
443fn escape(path: &Path, out: &mut Vec<u8>) {
444 for &b in path.as_os_str().as_bytes() {
445 match b {
446 b'%' => out.extend_from_slice(b"%25"),
447 b'\n' => out.extend_from_slice(b"%0A"),
448 _ => out.push(b),
449 }
450 }
451}
452
453/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
454/// may spell a space or a quote that way, and there is no reason to refuse it.
455fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
456 let mut out = Vec::with_capacity(field.len());
457 let mut i = 0;
458 while i < field.len() {
459 if field[i] != b'%' {
460 out.push(field[i]);
461 i += 1;
462 continue;
463 }
464 let byte = field
465 .get(i + 1..i + 3)
466 .and_then(|h| std::str::from_utf8(h).ok())
467 .and_then(|h| u8::from_str_radix(h, 16).ok())
468 .ok_or_else(|| -> crate::Error {
469 format!("line {line}: truncated % escape in the path").into()
470 })?;
471 out.push(byte);
472 i += 3;
473 }
474 Ok(PathBuf::from(OsString::from_vec(out)))
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
482 Clip {
483 start,
484 in_frame,
485 out_frame,
486 source,
487 link,
488 }
489 }
490
491 /// Two sources, one under the project's own directory and one not, a clip
492 /// from each on the video lane, and an audio lane with a gap in the middle
493 /// -- the shape every case below starts from.
494 fn source(path: &str, audio_stream: usize) -> Source {
495 Source {
496 path: PathBuf::from(path),
497 audio_stream,
498 }
499 }
500
501 /// Lanes in display order, as [`Document::lanes`] holds them.
502 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
503
504 /// `V1` then `A1`, the shape every dialect before v4 held.
505 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
506 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
507 }
508
509 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
510 (
511 PathBuf::from("/proj"),
512 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
513 two(
514 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
515 vec![clip(0, 0, 30, 0, Some(0))],
516 ),
517 )
518 }
519
520 #[test]
521 fn relative_and_absolute_paths_round_trip() {
522 let (dir, sources, lanes) = doc();
523 let bytes = emit(&dir, &sources, &lanes, 12);
524 assert_eq!(
525 String::from_utf8_lossy(&bytes),
526 "edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
527 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n",
528 "the file under the project directory is written relative to it, \
529 each with the audio stream it plays"
530 );
531 let back = parse(&bytes, &dir).expect("parse");
532 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
533 assert_eq!(
534 back.lanes, lanes,
535 "both lanes, in display order; the trailing gap needs no line"
536 );
537 assert_eq!(back.playhead, 12);
538 // ...and emitting the parsed document reproduces the same bytes.
539 assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes);
540 }
541
542 /// The whole of the bump: a project of any number of lanes writes and reads
543 /// back, in display order, empty lanes and cross-lane groups included.
544 #[test]
545 fn any_number_of_lanes_round_trips() {
546 let dir = PathBuf::from("/proj");
547 let sources = vec![source("/proj/a.mp4", 0)];
548 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
549 // shows, not video-then-audio -- with one take grouped across V1 and A2
550 // (no paired ord, the lanes between them empty of it) and an A1 holding
551 // nothing at all.
552 let lanes = vec![
553 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
554 (LaneKind::Audio, Vec::new()),
555 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
556 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
557 ];
558 let bytes = emit(&dir, &sources, &lanes, 7);
559 assert_eq!(
560 String::from_utf8_lossy(&bytes),
561 "edith 4\nplayhead 7\nsource 0 a.mp4\n\
562 video 1 0 0 30 0 4\naudio 1\nvideo 2 40 0 10 0 -\naudio 2 0 0 30 0 4\n",
563 "an empty lane is a line of its own; everything else is its clips"
564 );
565 let back = parse(&bytes, &dir).expect("parse");
566 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
567 assert_eq!(back.playhead, 7);
568 assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes);
569
570 // A lane number may not skip one of its kind: that lane was declared by
571 // nothing, and the refusal names it.
572 for (file, want) in [
573 (
574 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
575 "line 3: lane V2 comes before V1",
576 ),
577 (
578 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
579 "line 4: lane A3 comes before A1",
580 ),
581 (
582 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
583 "line 3: lane numbers start at 1",
584 ),
585 // The clip fields are still the clip fields, one lane number on.
586 (
587 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
588 "line 3: clip wants 5 fields, found 4",
589 ),
590 // ...and a v4 line in a v3 file reads as the garbled clip it is.
591 (
592 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
593 "line 3: clip wants 5 fields, found 6",
594 ),
595 ] {
596 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
597 }
598 // Lanes and nothing on them is not a project.
599 assert_eq!(
600 parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir)
601 .unwrap_err()
602 .to_string(),
603 "no clips: an empty timeline is not a project"
604 );
605 }
606
607 /// The other half of the compatibility promise: a v3 file is a v4 one
608 /// without the lane numbers, and a v2 file names no audio stream and means
609 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
610 /// they always were, and saving either writes v4 with nothing else changed.
611 #[test]
612 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
613 let dir = PathBuf::from("/proj");
614 let (_, _, lanes) = doc();
615 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
616 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
617 let old = parse(v3, &dir).expect("v3 parses");
618 assert_eq!(
619 (&old.sources, &old.lanes, old.playhead),
620 (
621 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
622 &lanes,
623 12
624 ),
625 "a v3 file loads as exactly the state its v4 twin does"
626 );
627 // ...and re-saved it *is* that twin: the magic and a lane number per
628 // clip line, and not one byte else.
629 assert_eq!(
630 emit(&dir, &old.sources, &old.lanes, old.playhead),
631 emit(&dir, &old.sources, &lanes, 12),
632 );
633
634 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
635 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
636 let back = parse(v2, &dir).expect("v2 parses");
637 assert_eq!(
638 back.sources,
639 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
640 );
641 assert_eq!(back.lanes, lanes);
642
643 let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead);
644 assert_eq!(
645 String::from_utf8_lossy(&v4),
646 "edith 4\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
647 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n",
648 "a re-saved v2 project differs only by its version, the lane \
649 numbers and the streams it always meant"
650 );
651 let again = parse(&v4, &dir).expect("v4 parses");
652 assert_eq!(again.sources, back.sources);
653 }
654
655 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
656 /// lanes, and saving it again writes v4.
657 #[test]
658 fn a_v1_file_loads_as_two_grouped_lanes() {
659 let dir = PathBuf::from("/proj");
660 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
661 let back = parse(v1, &dir).expect("v1 parses");
662 assert_eq!(
663 back.lanes[0].1,
664 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
665 "v1 clips queue up: the second starts where the first ended"
666 );
667 assert_eq!(
668 back.lanes,
669 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
670 "one take per clip, on both lanes"
671 );
672 assert_eq!(back.playhead, 5);
673 // Saved again it is v4, and that round-trips to the same document.
674 let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead);
675 assert!(v4.starts_with(b"edith 4\n"));
676 let again = parse(&v4, &dir).expect("v4 parses");
677 assert_eq!(again.lanes, back.lanes);
678 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
679 for (bytes, want) in [
680 (
681 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
682 "line 3: unknown keyword \"video\"",
683 ),
684 (
685 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
686 "line 3: unknown keyword \"clip\"",
687 ),
688 ] {
689 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
690 }
691 }
692
693 /// A gap is the absence of a line, so a lane's placements must arrive in
694 /// order and never overlap -- the invariant the whole model rests on.
695 #[test]
696 fn a_lane_out_of_order_or_overlapping_is_refused() {
697 let dir = PathBuf::from("/proj");
698 for bytes in [
699 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
700 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
701 ] {
702 let err = parse(bytes, &dir).unwrap_err().to_string();
703 assert!(err.starts_with("line 4: clip at "), "{err}");
704 }
705 // The lanes are independent, so a video line never crowds an audio one.
706 assert!(
707 parse(
708 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
709 &dir
710 )
711 .is_ok()
712 );
713 // ...and a lane may be empty as long as the other one is not.
714 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
715 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
716 }
717
718 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
719 /// and wrap in release, and a wrapped end passes the overlap check --
720 /// crafted numbers must be refused by name, in both dialects.
721 #[test]
722 fn a_clip_whose_end_overflows_is_refused() {
723 let dir = PathBuf::from("/proj");
724 for bytes in [
725 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
726 // Two of them: the second would land *before* the first once wrapped.
727 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
728 // v1 has no `start` field, but its queue reaches the same ceiling.
729 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
730 ] {
731 let err = parse(bytes, &dir).unwrap_err().to_string();
732 assert!(
733 err.contains("runs past the last frame there is"),
734 "not refused by name: {err}"
735 );
736 }
737 }
738
739 /// The relocatability promise, from the two directions a project path
740 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
741 /// clip.mp4`, whose parent is `""`) and a directory reached through a
742 /// symlink. Both used to emit absolute source lines.
743 #[test]
744 fn a_non_canonical_project_path_still_writes_relative_sources() {
745 assert_eq!(
746 project_dir(Path::new("a.edith")),
747 std::env::current_dir().expect("cwd"),
748 "a bare filename is saved into the working directory"
749 );
750
751 let dir = std::env::temp_dir().join(format!("ve_edith_link_{}", std::process::id()));
752 let _ = std::fs::remove_dir_all(&dir);
753 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
754 let dir = std::fs::canonicalize(&dir).expect("canonical scratch dir");
755 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
756 let source = dir.join("real/a.mp4");
757 let path = dir.join("link/p.edith");
758
759 let one = [clip(0, 0, 30, 0, None)];
760 let entry = Source {
761 path: source,
762 audio_stream: 1,
763 };
764 save(&path, &[entry], &two(one.to_vec(), one.to_vec()), 0).expect("save");
765 let bytes = std::fs::read(&path).expect("read back");
766 assert_eq!(
767 String::from_utf8_lossy(&bytes),
768 "edith 4\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 -\naudio 1 0 0 30 0 -\n"
769 );
770 // Loading rejoins the *given* directory, so the file is reached by the
771 // way the project was opened -- the same file, through the link, still
772 // playing the stream it was saved on.
773 assert_eq!(
774 load(&path).expect("load").sources,
775 vec![Source {
776 path: dir.join("link/a.mp4"),
777 audio_stream: 1,
778 }]
779 );
780 std::fs::remove_dir_all(&dir).expect("cleanup");
781 }
782
783 #[test]
784 fn escapes_survive_the_bytes_json_would_not() {
785 let dir = PathBuf::from("/proj");
786 // A newline and a percent in a filename, plus a non-UTF-8 byte.
787 let nasty = Source {
788 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
789 audio_stream: 0,
790 };
791 let bytes = emit(
792 &dir,
793 &[nasty.clone()],
794 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
795 0,
796 );
797 assert_eq!(
798 bytes.iter().filter(|&&b| b == b'\n').count(),
799 5,
800 "the escaped newline must not become a line break: magic, playhead, \
801 source, the clip, and the empty audio lane's own line"
802 );
803 let back = parse(&bytes, &dir).expect("parse");
804 // The spaces in it are the reason the stream field leads rather than
805 // trails: everything after the first one is path.
806 assert_eq!(back.sources, vec![nasty]);
807 }
808
809 #[test]
810 fn a_wrong_first_line_is_refused_by_name() {
811 let dir = PathBuf::from("/proj");
812 let err = parse(b"edith 5\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
813 .unwrap_err()
814 .to_string();
815 assert_eq!(err, "line 1: unsupported version 5");
816 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
817 assert_eq!(
818 parse(junk, &dir).unwrap_err().to_string(),
819 "line 1: not a edith file"
820 );
821 }
822 }
823
824 #[test]
825 fn malformed_lines_name_their_line_number() {
826 let dir = PathBuf::from("/proj");
827 let cases: [(&[u8], &str); 10] = [
828 // v3 wants the stream before the path, and a path after it.
829 (
830 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
831 "line 2: \"a.mp4\" is not a number",
832 ),
833 (
834 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
835 "line 2: source without a path",
836 ),
837 (
838 b"edith 1\nsource a.mp4\nclip 0 5\n",
839 "line 3: clip wants 3 fields, found 2",
840 ),
841 (
842 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
843 "line 3: \"five\" is not a number",
844 ),
845 (
846 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
847 "line 3: clip [5, 5) is empty",
848 ),
849 (
850 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
851 "line 3: clip [7, 5) is empty",
852 ),
853 (
854 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
855 "line 3: clip names source 1 of 1",
856 ),
857 (
858 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
859 "line 4: source after a clip",
860 ),
861 (
862 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
863 "line 3: unknown keyword \"\"",
864 ),
865 (
866 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
867 "line 3: playhead belongs once, before the sources",
868 ),
869 ];
870 for (bytes, want) in cases {
871 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
872 }
873 }
874
875 #[test]
876 fn a_project_without_clips_is_not_a_project() {
877 let dir = PathBuf::from("/proj");
878 assert_eq!(
879 parse(b"edith 1\nsource a.mp4\n", &dir)
880 .unwrap_err()
881 .to_string(),
882 "no clips: an empty timeline is not a project"
883 );
884 assert_eq!(
885 parse(b"edith 1\n", &dir).unwrap_err().to_string(),
886 "no clips: an empty timeline is not a project"
887 );
888 }
889
890 /// Every truncation of a good file either parses or refuses; none panics.
891 #[test]
892 fn truncations_never_panic() {
893 let (dir, sources, lanes) = doc();
894 let bytes = emit(&dir, &sources, &lanes, 12);
895 for cut in 0..bytes.len() {
896 let _ = parse(&bytes[..cut], &dir);
897 // ...and the same file with a byte lopped off the front, which
898 // shifts every field into the wrong place.
899 let _ = parse(&bytes[cut..], &dir);
900 }
901 // A % escape at the very end of a line has nothing to consume.
902 assert_eq!(
903 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
904 .unwrap_err()
905 .to_string(),
906 "line 2: truncated % escape in the path"
907 );
908 }
909}