forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

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