forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

edith.rs1582 lines, 62.8 KiBHistoryRawDownload
1//! The project file: a line of text per thing, and nothing else.
2//!
3//! ```text
4//! edith 7
5//! playhead 90
6//! resolution 1920 1080
7//! source 0 test_av.mp4
8//! source 1 /elsewhere/test_av2.mp4
9//! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
10//! color 0.1:1.2:0.9:-0.3
11//! video 1 0 0 120 0 0 0 0 fit
12//! audio 1 0 0 120 0 0 0 - fit
13//! video 2 120 0 120 1 - - - fill
14//! audio 2
15//! ```
16//!
17//! The `resolution` line is the **project's** picture size, which is a
18//! different thing from any source's: media of other sizes are placed on it.
19//! It belongs once, beside the playhead, and a file without one (every dialect
20//! before v7) means "source 0's own picture", which is what such a project
21//! always was.
22//!
23//! A source line is `source <audio stream> <path>`: which of the file's audio
24//! tracks that source plays, in the file order
25//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
26//! stream first because a path runs to the end of the line (it may hold
27//! spaces) and an optional *trailing* field could not be told from one.
28//!
29//! An eq line is `eq <band>...`, one band per field, each
30//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk` or
31//! `hs` ([`crate::eq::BandKind`]). Like a source it is named by *position* --
32//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
33//! curve write it once. `eq` on its own is the empty cascade, which is a
34//! setting like any other. The numbers are printed to round trip bit-exactly;
35//! anything not finite is refused, here and at [`crate::Project::set_eq`].
36//!
37//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
38//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
39//! -- the first colour line is color 0 -- printed and refused by the same rules.
40//!
41//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
42//! <color> <fit>`: which lane the clip is on -- its kind and its 1-based number
43//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
44//! column shows -- then where the clip sits on the timeline, the half-open
45//! source range it plays, the file it plays from, its group id, the eq line it
46//! plays through, the colour line it is graded by (`-` for none of those three)
47//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
48//! `stretch` or `center` ([`crate::scale::FitPolicy`]). Timeline placement is
49//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
50//! to write for one, and nothing that can disagree about its length.
51//!
52//! A lane is declared by the clips on it, in the order the lanes are displayed
53//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
54//! is the only way an empty lane could still be there on the way back. A lane
55//! number may not skip one of its kind.
56//!
57//! **Version 6** was this without the `resolution` line and without the clip's
58//! fit field -- such a project is the size of its first source and letterboxes
59//! nothing, because nothing on it could differ in size. **Version 5** was that
60//! without the colour lines and without the clip's colour
61//! field. **Version 4** was that without the eq lines and without the clip's eq
62//! field. **Version 3** was that without the lane number, and held one video
63//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
64//! well, which is this file's stream 0 -- one per file, whichever audio track
65//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
66//! <in> <out> <source>`. All five still load -- a v1 file's clips are laid out
67//! cumulatively and copied onto both lanes as one group each, which is exactly
68//! what a v1 timeline meant, and an older file simply equalizes and grades
69//! nothing -- and saving any of them writes v7. An older reader refuses a newer
70//! file by name.
71//!
72//! Text because an edit list is a few integers and a path, and a path is
73//! *bytes* on this platform -- a JSON string would have to lossily decode one.
74//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
75//! everything a line-based format cannot carry) and survives round-trip
76//! exactly. Paths under the project file's own directory are written relative
77//! to it, so a folder holding the media and the `.edith` can be moved or
78//! copied anywhere and still open; anything else is absolute.
79//!
80//! The parser is strict and every refusal names its 1-based line: a project
81//! file is generated, so a line it did not generate is a corrupt file, not a
82//! dialect. Structure is checked here (fields, ordering, empty clips,
83//! out-of-range source indexes); whether the files on disk still match the
84//! timeline is [`crate::PlaybackSession::open_project`]'s business.
85//!
86//! Writing goes through `<path>.part` and a rename, as an export does, so an
87//! interrupted save cannot destroy the previous version of the project. The
88//! bytes are fsynced before the rename and the directory after it, so what a
89//! power loss can lose is a whole save, never half of one under the real name.
90
91use std::ffi::OsString;
92use std::io::Write;
93use std::os::unix::ffi::{OsStrExt, OsStringExt};
94use std::path::{Path, PathBuf};
95
96use crate::color::ColorParams;
97use crate::eq::{Band, BandKind, EqParams};
98use crate::project::{Clip, Lane, LaneKind, Source};
99use crate::scale::FitPolicy;
100
101/// What [`save`] writes. Read support goes back to `edith 1`; see the module
102/// docs for what those dialects looked like.
103const MAGIC: &[u8] = b"edith 7";
104const MAGIC_V6: &[u8] = b"edith 6";
105const MAGIC_V5: &[u8] = b"edith 5";
106const MAGIC_V4: &[u8] = b"edith 4";
107const MAGIC_V3: &[u8] = b"edith 3";
108const MAGIC_V2: &[u8] = b"edith 2";
109const MAGIC_V1: &[u8] = b"edith 1";
110
111/// What a project file says: an edit list plus where the playhead stood.
112/// Structurally valid by construction -- see [`parse`].
113#[derive(Debug)]
114pub struct Document {
115 /// Paths absolute, relative entries already joined to the file's own
116 /// directory.
117 pub sources: Vec<Source>,
118 /// Every lane, in display order, which is the order
119 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
120 /// `A1` -- for every dialect before v4.
121 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
122 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
123 /// every dialect before v5.
124 pub eq: Vec<EqParams>,
125 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
126 /// every dialect before v6.
127 pub color: Vec<ColorParams>,
128 /// The project's own picture size. `None` for every dialect before v7 and
129 /// for a v7 file that leaves it out, which both mean "source 0's picture".
130 pub resolution: Option<(u32, u32)>,
131 pub playhead: u32,
132}
133
134/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
135/// already be orphan-free ([`crate::Project::without_orphan_sources`]).
136pub fn save(
137 path: &Path,
138 sources: &[Source],
139 lanes: &[(LaneKind, Vec<Clip>)],
140 eq: &[EqParams],
141 color: &[ColorParams],
142 resolution: (u32, u32),
143 playhead: u32,
144) -> crate::Result<()> {
145 let dir = project_dir(path);
146 let mut part = path.to_path_buf().into_os_string();
147 part.push(".part");
148 let part = PathBuf::from(part);
149 // The rename publishes the file under the caller's name in one step, on the
150 // same directory; until it happens the old project file is still the whole
151 // truth. `sync_all` puts the bytes on the disk before that name exists, and
152 // the second one puts the name itself there.
153 let result = std::fs::File::create(&part)
154 .and_then(|mut f| {
155 f.write_all(&emit(&dir, sources, lanes, eq, color, resolution, playhead))?;
156 f.sync_all()
157 })
158 .and_then(|()| std::fs::rename(&part, path))
159 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
160 if result.is_err() {
161 let _ = std::fs::remove_file(&part);
162 }
163 result.map_err(Into::into)
164}
165
166pub fn load(path: &Path) -> crate::Result<Document> {
167 let data = std::fs::read(path)?;
168 parse(&data, path.parent().unwrap_or(Path::new("")))
169}
170
171/// The directory a project file's relative source lines are measured from, in
172/// the same canonical form [`crate::Project`] keeps its sources in -- without
173/// that the prefix simply never matches and every line comes out absolute,
174/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
175/// a bare filename is `""`). Canonicalizing fails only if the directory does
176/// not exist, and then the write is about to fail anyway.
177fn project_dir(path: &Path) -> PathBuf {
178 let dir = path
179 .parent()
180 .filter(|p| !p.as_os_str().is_empty())
181 .unwrap_or(Path::new("."));
182 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
183}
184
185fn emit(
186 dir: &Path,
187 sources: &[Source],
188 lanes: &[(LaneKind, Vec<Clip>)],
189 eq: &[EqParams],
190 color: &[ColorParams],
191 resolution: (u32, u32),
192 playhead: u32,
193) -> Vec<u8> {
194 let mut out = Vec::new();
195 out.extend_from_slice(MAGIC);
196 out.push(b'\n');
197 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
198 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
199 for s in sources {
200 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
201 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
202 out.push(b'\n');
203 }
204 // Before the clips, for the reason the sources are: a clip names one by the
205 // position of its line, so the line has to be there first.
206 for params in eq {
207 out.extend_from_slice(b"eq");
208 for b in &params.bands {
209 // `{:?}` rather than `{}`: it is the formatting that promises the
210 // shortest string parsing back to this exact f32, and it never
211 // prints a bare integer, which would read as another field's shape.
212 let kind = match b.kind {
213 BandKind::LowShelf => "ls",
214 BandKind::Peak => "pk",
215 BandKind::HighShelf => "hs",
216 };
217 out.extend_from_slice(
218 format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
219 );
220 }
221 out.push(b'\n');
222 }
223 // ...and the colour table, for the same reason and by the same rules.
224 for p in color {
225 out.extend_from_slice(
226 format!(
227 "color {:?}:{:?}:{:?}:{:?}\n",
228 p.brightness, p.contrast, p.saturation, p.tint
229 )
230 .as_bytes(),
231 );
232 }
233 // Lane by lane rather than interleaved by time: a lane reads as a list, the
234 // parser gets its sortedness check for free from the order it is in, and
235 // the lanes come back out in the order they are displayed in.
236 let (mut video, mut audio) = (0, 0);
237 for (kind, clips) in lanes {
238 let (keyword, ord) = match kind {
239 LaneKind::Video => {
240 video += 1;
241 ("video", video)
242 }
243 LaneKind::Audio => {
244 audio += 1;
245 ("audio", audio)
246 }
247 };
248 // A lane is declared by its clips; one holding nothing has to say so on
249 // a line of its own, or the lane itself would not survive the round trip.
250 if clips.is_empty() {
251 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
252 }
253 for c in clips {
254 let link = c.link.map_or("-".to_string(), |l| l.to_string());
255 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
256 let color = c.color.map_or("-".to_string(), |e| e.to_string());
257 out.extend_from_slice(
258 format!(
259 "{keyword} {ord} {} {} {} {} {link} {eq} {color} {}\n",
260 c.start,
261 c.in_frame,
262 c.out_frame,
263 c.source,
264 fit_name(c.fit)
265 )
266 .as_bytes(),
267 );
268 }
269 }
270 out
271}
272
273fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
274 // One trailing newline is the line terminator of the last line, not an
275 // empty line -- any further one is, and is refused below.
276 let body = data.strip_suffix(b"\n").unwrap_or(data);
277 let mut lines = body.split(|&b| b == b'\n').enumerate();
278 let (_, first) = lines.next().unwrap_or((0, &[]));
279 let v1 = first == MAGIC_V1;
280 // The dialects that wrote a source line without its stream field. Reading
281 // one is the whole of what "an old project still opens" means here.
282 let streamless = v1 || first == MAGIC_V2;
283 // The one that carries a project resolution and per-clip fit policies...
284 let v7 = first == MAGIC;
285 // ...the ones that carry colour grades...
286 let v6 = v7 || first == MAGIC_V6;
287 // ...the ones that carry equalizer settings...
288 let v5 = v6 || first == MAGIC_V5;
289 // ...and the ones that number their lanes. Every older one held two.
290 let numbered = v5 || first == MAGIC_V4;
291 if !numbered && !streamless && first != MAGIC_V3 {
292 return Err(match first.strip_prefix(b"edith ") {
293 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
294 None => "line 1: not a edith file".to_string(),
295 }
296 .into());
297 }
298
299 let mut doc = Document {
300 sources: Vec::new(),
301 // v4 on declares its lanes as they come; every dialect before it held
302 // exactly `V1` and `A1`, either of which could be empty.
303 lanes: if numbered {
304 Vec::new()
305 } else {
306 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
307 },
308 // Nothing before v5 equalizes anything, and nothing before v6 grades.
309 eq: Vec::new(),
310 color: Vec::new(),
311 // Nothing before v7 has a resolution of its own: source 0's picture is
312 // what those projects were, and `None` is how the loader is told so.
313 resolution: None,
314 playhead: 0,
315 };
316 let mut playhead_seen = false;
317 // Where the next v1 clip is placed: that dialect had no `start` field, the
318 // clips simply queued up.
319 let mut queued = 0u32;
320 for (i, line) in lines {
321 let n = i + 1;
322 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
323 Some(at) => (&line[..at], &line[at + 1..]),
324 None => (line, &line[line.len()..]),
325 };
326 match keyword {
327 b"playhead" => {
328 if playhead_seen || !doc.sources.is_empty() {
329 return Err(
330 format!("line {n}: playhead belongs once, before the sources").into(),
331 );
332 }
333 doc.playhead = number(rest, n)?;
334 playhead_seen = true;
335 }
336 b"resolution" if v7 => {
337 if doc.resolution.is_some() || !doc.sources.is_empty() {
338 return Err(
339 format!("line {n}: resolution belongs once, before the sources").into(),
340 );
341 }
342 let f = fields(rest, 2, "resolution", n)?;
343 let (width, height) = (number(f[0], n)?, number(f[1], n)?);
344 // The same bound the keystroke has (`crate::is_resolution`):
345 // unbounded here, this line reached `open_black` and panicked
346 // the open with a capacity overflow.
347 if !crate::is_resolution(width, height) {
348 return Err(format!("line {n}: {width}x{height} is not a picture").into());
349 }
350 doc.resolution = Some((width, height));
351 }
352 b"source" => {
353 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
354 return Err(format!("line {n}: source after a clip").into());
355 }
356 // The stream comes first and the path is everything after it,
357 // spaces and all; an older dialect wrote no stream and meant 0.
358 let (audio_stream, rest) = if streamless {
359 (0, rest)
360 } else {
361 // No space at all still has to reach `number`, so a v2 line
362 // in a v3 file is refused as the missing field it is rather
363 // than as a missing path.
364 let at = rest.iter().position(|&b| b == b' ');
365 (
366 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
367 &rest[at.map_or(rest.len(), |at| at + 1)..],
368 )
369 };
370 if rest.is_empty() {
371 return Err(format!("line {n}: source without a path").into());
372 }
373 let path = unescape(rest, n)?;
374 // Relative means "next to the project file", which is what
375 // makes a whole folder relocatable.
376 doc.sources.push(Source {
377 path: if path.is_absolute() {
378 path
379 } else {
380 dir.join(path)
381 },
382 audio_stream,
383 });
384 }
385 b"eq" if v5 => {
386 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
387 return Err(format!("line {n}: eq after a clip").into());
388 }
389 // A bare `eq` is the empty cascade -- a setting that moves
390 // nothing, which is not the same thing as no setting at all.
391 let bands = match rest.is_empty() {
392 true => Vec::new(),
393 false => rest
394 .split(|&b| b == b' ')
395 .map(|field| band(field, n))
396 .collect::<crate::Result<Vec<Band>>>()?,
397 };
398 doc.eq.push(EqParams { bands });
399 }
400 b"color" if v6 => {
401 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
402 return Err(format!("line {n}: color after a clip").into());
403 }
404 let f = fields(rest, 1, "color", n)?;
405 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
406 if parts.len() != 4 {
407 return Err(
408 format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
409 );
410 }
411 doc.color.push(ColorParams {
412 brightness: float(parts[0], n)?,
413 contrast: float(parts[1], n)?,
414 saturation: float(parts[2], n)?,
415 tint: float(parts[3], n)?,
416 });
417 }
418 // v1: one lane, no placement, no groups. Every clip becomes one
419 // grouped video+audio pair laid where the queue reached, which is
420 // what the file always meant.
421 b"clip" if v1 => {
422 let f = fields(rest, 3, "clip", n)?;
423 let clip = check(
424 Clip {
425 start: queued,
426 in_frame: number(f[0], n)?,
427 out_frame: number(f[1], n)?,
428 source: number(f[2], n)? as usize,
429 link: Some(doc.lanes[0].1.len() as u32),
430 eq: None,
431 color: None,
432 fit: FitPolicy::default(),
433 },
434 &doc,
435 n,
436 )?;
437 queued = clip.end();
438 doc.lanes[0].1.push(clip);
439 doc.lanes[1].1.push(clip);
440 }
441 b"video" | b"audio" if !v1 => {
442 let kind = match keyword {
443 b"video" => LaneKind::Video,
444 _ => LaneKind::Audio,
445 };
446 // v4 on names the lane, and a line naming nothing else is an
447 // empty lane's whole existence. Older dialects had one lane per
448 // kind.
449 let (ord, rest) = if numbered {
450 let at = rest.iter().position(|&b| b == b' ');
451 (
452 number(&rest[..at.unwrap_or(rest.len())], n)?,
453 &rest[at.map_or(rest.len(), |at| at + 1)..],
454 )
455 } else {
456 (1, rest)
457 };
458 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
459 if numbered && rest.is_empty() {
460 continue;
461 }
462 // v7 grew the fit field, v6 the colour one and v5 the eq one;
463 // every older dialect ends at the link.
464 let want = 5 + usize::from(v5) + usize::from(v6) + usize::from(v7);
465 let f = fields(rest, want, "clip", n)?;
466 let clip = check(
467 Clip {
468 start: number(f[0], n)?,
469 in_frame: number(f[1], n)?,
470 out_frame: number(f[2], n)?,
471 source: number(f[3], n)? as usize,
472 link: match f[4] {
473 b"-" => None,
474 field => Some(number(field, n)?),
475 },
476 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
477 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
478 fit: fit_policy(f.get(7).copied(), n)?,
479 },
480 &doc,
481 n,
482 )?;
483 let lane = &mut doc.lanes[at].1;
484 // The sorted, non-overlapping placement invariant, checked at
485 // the only door untrusted clips come in through.
486 if lane.last().is_some_and(|prev| prev.end() > clip.start) {
487 return Err(format!(
488 "line {n}: clip at {} overlaps the one before it, or comes before it",
489 clip.start
490 )
491 .into());
492 }
493 lane.push(clip);
494 }
495 // Empty lines land here too: nothing in this format is optional
496 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
497 // is a file mixing dialects, and is refused the same way.
498 _ => {
499 return Err(format!(
500 "line {n}: unknown keyword {:?}",
501 String::from_utf8_lossy(keyword)
502 )
503 .into());
504 }
505 }
506 }
507 // A file whose lanes are all empty *is* a project -- the emptied timeline,
508 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
509 // refuses that one, by the name it has there.
510 Ok(doc)
511}
512
513/// Where the lane a v4 line names sits, appending it if this is its first line.
514/// Lanes arrive in display order, so a number that skips one of its kind is a
515/// lane that was never declared, and is refused by the name it would have had.
516fn lane_of(
517 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
518 kind: LaneKind,
519 ord: u32,
520 line: usize,
521) -> crate::Result<usize> {
522 let mut seen = 0;
523 for (at, (k, _)) in lanes.iter().enumerate() {
524 if *k == kind {
525 seen += 1;
526 if seen == ord {
527 return Ok(at);
528 }
529 }
530 }
531 if ord != seen + 1 {
532 return Err(match ord.checked_sub(1) {
533 Some(prev) => format!(
534 "line {line}: lane {} comes before {}",
535 Lane::new(kind, prev as usize).label(),
536 Lane::new(kind, seen as usize).label()
537 ),
538 None => format!("line {line}: lane numbers start at 1"),
539 }
540 .into());
541 }
542 lanes.push((kind, Vec::new()));
543 Ok(lanes.len() - 1)
544}
545
546/// Splits a line's fields, refusing the wrong count by name.
547fn fields<'a>(
548 rest: &'a [u8],
549 want: usize,
550 what: &str,
551 line: usize,
552) -> crate::Result<Vec<&'a [u8]>> {
553 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
554 if fields.len() != want {
555 return Err(format!(
556 "line {line}: {what} wants {want} fields, found {}",
557 fields.len()
558 )
559 .into());
560 }
561 Ok(fields)
562}
563
564/// The per-clip structure checks both dialects share.
565fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
566 if clip.out_frame <= clip.in_frame {
567 return Err(format!(
568 "line {line}: clip [{}, {}) is empty",
569 clip.in_frame, clip.out_frame
570 )
571 .into());
572 }
573 if clip.source >= doc.sources.len() {
574 return Err(format!(
575 "line {line}: clip names source {} of {}",
576 clip.source,
577 doc.sources.len()
578 )
579 .into());
580 }
581 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
582 // adds `start + len` as plain `u32`, which panics in debug and wraps in
583 // release on a crafted file. Bound it here, at the door.
584 if clip.start.checked_add(clip.len()).is_none() {
585 return Err(format!(
586 "line {line}: clip at {} runs past the last frame there is",
587 clip.start
588 )
589 .into());
590 }
591 Ok(clip)
592}
593
594/// How a fit policy is spelled in the file. One word each, so a clip line stays
595/// readable, and the same word the parser takes back.
596fn fit_name(fit: FitPolicy) -> &'static str {
597 match fit {
598 FitPolicy::Fit => "fit",
599 FitPolicy::Fill => "fill",
600 FitPolicy::Stretch => "stretch",
601 FitPolicy::Center => "center",
602 }
603}
604
605/// A clip's `<fit>` field. A dialect that has no such field at all means the
606/// default -- those projects held one resolution, so no clip of theirs was ever
607/// placed on anything.
608fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
609 let Some(field) = field else {
610 return Ok(FitPolicy::default());
611 };
612 match field {
613 b"fit" => Ok(FitPolicy::Fit),
614 b"fill" => Ok(FitPolicy::Fill),
615 b"stretch" => Ok(FitPolicy::Stretch),
616 b"center" => Ok(FitPolicy::Center),
617 other => Err(format!(
618 "line {line}: {:?} is not a fit policy",
619 String::from_utf8_lossy(other)
620 )
621 .into()),
622 }
623}
624
625/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
626/// at all), or a line of a table that is already declared. Refused by the name
627/// of what it points at, so the message reads as the file does.
628fn table_index(
629 field: Option<&[u8]>,
630 len: usize,
631 what: &str,
632 line: usize,
633) -> crate::Result<Option<u16>> {
634 let field = match field {
635 None | Some(b"-") => return Ok(None),
636 Some(field) => field,
637 };
638 let i = number(field, line)?;
639 if i as usize >= len || i > u32::from(u16::MAX) {
640 return Err(format!("line {line}: clip names {what} {i} of {len}").into());
641 }
642 Ok(Some(i as u16))
643}
644
645/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
646fn band(field: &[u8], line: usize) -> crate::Result<Band> {
647 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
648 if parts.len() != 4 {
649 return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
650 }
651 Ok(Band {
652 freq_hz: float(parts[0], line)?,
653 gain_db: float(parts[1], line)?,
654 q: float(parts[2], line)?,
655 kind: match parts[3] {
656 b"ls" => BandKind::LowShelf,
657 b"pk" => BandKind::Peak,
658 b"hs" => BandKind::HighShelf,
659 other => {
660 return Err(format!(
661 "line {line}: {:?} is not a band shape",
662 String::from_utf8_lossy(other)
663 )
664 .into());
665 }
666 },
667 })
668}
669
670/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
671/// and NaN are refused rather than carried -- they are the values a coefficient
672/// cannot be built from, and the ones that would not compare equal to
673/// themselves on the way back.
674fn float(field: &[u8], line: usize) -> crate::Result<f32> {
675 match std::str::from_utf8(field)
676 .ok()
677 .and_then(|s| s.parse::<f32>().ok())
678 .filter(|f| f.is_finite())
679 {
680 Some(f) => Ok(f),
681 None => Err(format!(
682 "line {line}: {:?} is not a number",
683 String::from_utf8_lossy(field)
684 )
685 .into()),
686 }
687}
688
689fn number(field: &[u8], line: usize) -> crate::Result<u32> {
690 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
691 Some(n) => Ok(n),
692 None => Err(format!(
693 "line {line}: {:?} is not a number",
694 String::from_utf8_lossy(field)
695 )
696 .into()),
697 }
698}
699
700/// The two bytes a line-based format cannot hold, and the escape byte itself.
701fn escape(path: &Path, out: &mut Vec<u8>) {
702 for &b in path.as_os_str().as_bytes() {
703 match b {
704 b'%' => out.extend_from_slice(b"%25"),
705 b'\n' => out.extend_from_slice(b"%0A"),
706 _ => out.push(b),
707 }
708 }
709}
710
711/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
712/// may spell a space or a quote that way, and there is no reason to refuse it.
713fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
714 let mut out = Vec::with_capacity(field.len());
715 let mut i = 0;
716 while i < field.len() {
717 if field[i] != b'%' {
718 out.push(field[i]);
719 i += 1;
720 continue;
721 }
722 let byte = field
723 .get(i + 1..i + 3)
724 .and_then(|h| std::str::from_utf8(h).ok())
725 .and_then(|h| u8::from_str_radix(h, 16).ok())
726 .ok_or_else(|| -> crate::Error {
727 format!("line {line}: truncated % escape in the path").into()
728 })?;
729 out.push(byte);
730 i += 3;
731 }
732 Ok(PathBuf::from(OsString::from_vec(out)))
733}
734
735#[cfg(test)]
736mod tests {
737 use super::*;
738
739 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
740 Clip {
741 start,
742 in_frame,
743 out_frame,
744 source,
745 link,
746 eq: None,
747 color: None,
748 fit: FitPolicy::default(),
749 }
750 }
751
752 /// [`emit`] for a timeline that equalizes nothing, which is every case that
753 /// predates the eq lines.
754 fn flat(
755 dir: &Path,
756 sources: &[Source],
757 lanes: &[(LaneKind, Vec<Clip>)],
758 playhead: u32,
759 ) -> Vec<u8> {
760 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
761 }
762
763 /// Two sources, one under the project's own directory and one not, a clip
764 /// from each on the video lane, and an audio lane with a gap in the middle
765 /// -- the shape every case below starts from.
766 fn source(path: &str, audio_stream: usize) -> Source {
767 Source {
768 path: PathBuf::from(path),
769 audio_stream,
770 }
771 }
772
773 /// Lanes in display order, as [`Document::lanes`] holds them.
774 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
775
776 /// `V1` then `A1`, the shape every dialect before v4 held.
777 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
778 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
779 }
780
781 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
782 (
783 PathBuf::from("/proj"),
784 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
785 two(
786 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
787 vec![clip(0, 0, 30, 0, Some(0))],
788 ),
789 )
790 }
791
792 #[test]
793 fn relative_and_absolute_paths_round_trip() {
794 let (dir, sources, lanes) = doc();
795 let bytes = flat(&dir, &sources, &lanes, 12);
796 assert_eq!(
797 String::from_utf8_lossy(&bytes),
798 "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
799 source 2 /elsewhere/b.mp4\n\
800 video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
801 audio 1 0 0 30 0 0 - - fit\n",
802 "the file under the project directory is written relative to it, \
803 each with the audio stream it plays"
804 );
805 let back = parse(&bytes, &dir).expect("parse");
806 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
807 assert_eq!(
808 back.lanes, lanes,
809 "both lanes, in display order; the trailing gap needs no line"
810 );
811 assert_eq!(back.playhead, 12);
812 // ...and emitting the parsed document reproduces the same bytes.
813 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
814 }
815
816 /// The whole of the bump: a project of any number of lanes writes and reads
817 /// back, in display order, empty lanes and cross-lane groups included.
818 #[test]
819 fn any_number_of_lanes_round_trips() {
820 let dir = PathBuf::from("/proj");
821 let sources = vec![source("/proj/a.mp4", 0)];
822 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
823 // shows, not video-then-audio -- with one take grouped across V1 and A2
824 // (no paired ord, the lanes between them empty of it) and an A1 holding
825 // nothing at all.
826 let lanes = vec![
827 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
828 (LaneKind::Audio, Vec::new()),
829 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
830 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
831 ];
832 let bytes = flat(&dir, &sources, &lanes, 7);
833 assert_eq!(
834 String::from_utf8_lossy(&bytes),
835 "edith 7\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
836 video 1 0 0 30 0 4 - - fit\naudio 1\n\
837 video 2 40 0 10 0 - - - fit\naudio 2 0 0 30 0 4 - - fit\n",
838 "an empty lane is a line of its own; everything else is its clips"
839 );
840 let back = parse(&bytes, &dir).expect("parse");
841 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
842 assert_eq!(back.playhead, 7);
843 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
844
845 // A lane number may not skip one of its kind: that lane was declared by
846 // nothing, and the refusal names it.
847 for (file, want) in [
848 (
849 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
850 "line 3: lane V2 comes before V1",
851 ),
852 (
853 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
854 "line 4: lane A3 comes before A1",
855 ),
856 (
857 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
858 "line 3: lane numbers start at 1",
859 ),
860 // The clip fields are still the clip fields, one lane number on.
861 (
862 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
863 "line 3: clip wants 5 fields, found 4",
864 ),
865 // ...and a v4 line in a v3 file reads as the garbled clip it is.
866 (
867 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
868 "line 3: clip wants 5 fields, found 6",
869 ),
870 ] {
871 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
872 }
873 // Lanes and nothing on them is the emptied timeline, saved: a project.
874 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
875 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
876 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
877 }
878
879 /// One band, spelled the way an eq line spells it.
880 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
881 Band {
882 freq_hz,
883 gain_db,
884 q,
885 kind,
886 }
887 }
888
889 /// The whole of the v5 bump: the clips name a shared equalizer table, the
890 /// bytes are the ones documented at the top of this file, and every f32 in
891 /// them comes back *bit* for bit -- which is what makes a re-save of a
892 /// loaded project produce the same file rather than a drifting one.
893 #[test]
894 fn equalizers_round_trip_bit_exactly_and_are_shared() {
895 let dir = PathBuf::from("/proj");
896 let sources = vec![source("/proj/a.mp4", 0)];
897 let eq = vec![
898 EqParams {
899 bands: vec![
900 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
901 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
902 ],
903 },
904 // The awkward ones: a value needing all 24 mantissa bits, one whose
905 // shortest spelling is exponential, a subnormal, and a negative
906 // zero -- plus the empty cascade, which is a setting like any other.
907 EqParams {
908 bands: vec![band_of(
909 16_777_215.0,
910 -0.1,
911 f32::MIN_POSITIVE / 3.0,
912 BandKind::HighShelf,
913 )],
914 },
915 EqParams { bands: Vec::new() },
916 ];
917 // Two clips share entry 0, so it is written once; one clip plays flat.
918 let lanes = two(
919 vec![
920 Clip {
921 eq: Some(0),
922 ..clip(0, 0, 30, 0, Some(0))
923 },
924 Clip {
925 eq: Some(1),
926 ..clip(30, 10, 20, 0, None)
927 },
928 ],
929 vec![
930 Clip {
931 eq: Some(0),
932 ..clip(0, 0, 30, 0, Some(0))
933 },
934 Clip {
935 eq: Some(2),
936 ..clip(30, 0, 10, 0, None)
937 },
938 ],
939 );
940 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
941 assert_eq!(
942 String::from_utf8_lossy(&bytes),
943 "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
944 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
945 eq 16777215.0:-0.1:3.918315e-39:hs\n\
946 eq\n\
947 video 1 0 0 30 0 0 0 - fit\nvideo 1 30 10 20 0 - 1 - fit\n\
948 audio 1 0 0 30 0 0 0 - fit\naudio 1 30 0 10 0 - 2 - fit\n",
949 "the table comes before the clips, and a clip names a line of it"
950 );
951
952 let back = parse(&bytes, &dir).expect("parse");
953 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
954 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
955 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
956 assert_eq!(
957 (
958 got.freq_hz.to_bits(),
959 got.gain_db.to_bits(),
960 got.q.to_bits(),
961 got.kind
962 ),
963 (
964 want.freq_hz.to_bits(),
965 want.gain_db.to_bits(),
966 want.q.to_bits(),
967 want.kind
968 ),
969 "eq {i} band {b} came back as other bits"
970 );
971 }
972 }
973 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
974 assert_eq!(
975 emit(
976 &dir,
977 &back.sources,
978 &back.lanes,
979 &back.eq,
980 &back.color,
981 (1280, 720),
982 0
983 ),
984 bytes
985 );
986 }
987
988 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
989 /// colour table, the bytes are the ones documented at the top of this file,
990 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
991 #[test]
992 fn colours_round_trip_bit_exactly_and_are_shared() {
993 let dir = PathBuf::from("/proj");
994 let sources = vec![source("/proj/a.mp4", 0)];
995 let color = vec![
996 ColorParams {
997 brightness: 0.1,
998 contrast: 1.2,
999 saturation: 0.9,
1000 tint: -0.3,
1001 },
1002 // The awkward ones again: all 24 mantissa bits, an exponential
1003 // spelling, a subnormal and a negative zero -- and the identity,
1004 // which is a setting like any other.
1005 ColorParams {
1006 brightness: -0.000_000_1,
1007 contrast: 16_777_215.0,
1008 saturation: f32::MIN_POSITIVE / 3.0,
1009 tint: -0.0,
1010 },
1011 ColorParams::default(),
1012 ];
1013 // Two clips share entry 0, so it is written once; one clip is ungraded.
1014 let lanes = two(
1015 vec![
1016 Clip {
1017 color: Some(0),
1018 fit: FitPolicy::default(),
1019 ..clip(0, 0, 30, 0, Some(0))
1020 },
1021 Clip {
1022 color: Some(1),
1023 fit: FitPolicy::default(),
1024 ..clip(30, 10, 20, 0, None)
1025 },
1026 ],
1027 vec![
1028 Clip {
1029 color: Some(0),
1030 fit: FitPolicy::default(),
1031 ..clip(0, 0, 30, 0, Some(0))
1032 },
1033 Clip {
1034 color: Some(2),
1035 fit: FitPolicy::default(),
1036 ..clip(30, 0, 10, 0, None)
1037 },
1038 ],
1039 );
1040 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1041 assert_eq!(
1042 String::from_utf8_lossy(&bytes),
1043 "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1044 color 0.1:1.2:0.9:-0.3\n\
1045 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1046 color 0.0:1.0:1.0:0.0\n\
1047 video 1 0 0 30 0 0 - 0 fit\nvideo 1 30 10 20 0 - - 1 fit\n\
1048 audio 1 0 0 30 0 0 - 0 fit\naudio 1 30 0 10 0 - - 2 fit\n",
1049 "the table comes before the clips, and a clip names a line of it"
1050 );
1051
1052 let back = parse(&bytes, &dir).expect("parse");
1053 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
1054 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
1055 assert_eq!(
1056 (
1057 got.brightness.to_bits(),
1058 got.contrast.to_bits(),
1059 got.saturation.to_bits(),
1060 got.tint.to_bits()
1061 ),
1062 (
1063 want.brightness.to_bits(),
1064 want.contrast.to_bits(),
1065 want.saturation.to_bits(),
1066 want.tint.to_bits()
1067 ),
1068 "color {i} came back as other bits"
1069 );
1070 }
1071 assert_eq!(back.color.len(), 3);
1072 assert_eq!(
1073 emit(
1074 &dir,
1075 &back.sources,
1076 &back.lanes,
1077 &back.eq,
1078 &back.color,
1079 (1280, 720),
1080 0
1081 ),
1082 bytes
1083 );
1084 }
1085
1086 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
1087 /// intact, and re-saving it writes the new magic and a `-` colour field.
1088 #[test]
1089 fn a_v5_file_grades_nothing() {
1090 let dir = PathBuf::from("/proj");
1091 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
1092 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
1093 let old = parse(v5, &dir).expect("v5 parses");
1094 assert!(old.color.is_empty(), "nothing before v6 grades anything");
1095 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
1096 assert_eq!(old.lanes[0].1[0].eq, Some(0));
1097 assert!(old.lanes[0].1[0].color.is_none());
1098 assert_eq!(
1099 String::from_utf8_lossy(&emit(
1100 &dir,
1101 &old.sources,
1102 &old.lanes,
1103 &old.eq,
1104 &old.color,
1105 (1280, 720),
1106 old.playhead
1107 )),
1108 "edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1109 eq 80.0:-3.0:0.707:ls\n\
1110 video 1 0 0 30 0 0 0 - fit\naudio 1 0 0 30 0 0 - - fit\n"
1111 );
1112 }
1113
1114 /// The refusals the colour grammar adds, each naming its line.
1115 #[test]
1116 fn a_malformed_colour_names_its_line() {
1117 let dir = PathBuf::from("/proj");
1118 let head = "edith 6\nsource 0 a.mp4\n";
1119 // v6, deliberately: the colour grammar is the same one v7 inherits, and
1120 // a v6 clip line is one field shorter.
1121 for (file, want) in [
1122 (
1123 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
1124 "line 3: color wants 4 fields, found 3",
1125 ),
1126 (
1127 format!("{head}color 0.0:1.0:1.0:0.0 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1128 "line 3: color wants 1 fields, found 2",
1129 ),
1130 (
1131 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1132 "line 3: \"warm\" is not a number",
1133 ),
1134 // The two values the format cannot write and read back as itself.
1135 (
1136 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1137 "line 3: \"inf\" is not a number",
1138 ),
1139 (
1140 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
1141 "line 3: \"NaN\" is not a number",
1142 ),
1143 (
1144 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
1145 "line 4: clip names color 1 of 1",
1146 ),
1147 (
1148 format!("{head}video 1 0 0 5 0 - - 0\n"),
1149 "line 3: clip names color 0 of 0",
1150 ),
1151 // A clip's colour field is not optional in v6, and the table has to
1152 // be declared before the clip that names it.
1153 (
1154 format!("{head}video 1 0 0 5 0 - -\n"),
1155 "line 3: clip wants 7 fields, found 6",
1156 ),
1157 (
1158 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
1159 "line 4: color after a clip",
1160 ),
1161 // ...and a colour line in a file that predates them is a corrupt one.
1162 (
1163 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
1164 "line 3: unknown keyword \"color\"",
1165 ),
1166 ] {
1167 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1168 }
1169 }
1170
1171 /// The refusals the eq grammar adds, each naming its line.
1172 #[test]
1173 fn a_malformed_equalizer_names_its_line() {
1174 let dir = PathBuf::from("/proj");
1175 let head = "edith 5\nsource 0 a.mp4\n";
1176 for (file, want) in [
1177 (
1178 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
1179 "line 3: band wants 4 fields, found 3",
1180 ),
1181 (
1182 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
1183 "line 3: \"notch\" is not a band shape",
1184 ),
1185 (
1186 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
1187 "line 3: \"wide\" is not a number",
1188 ),
1189 // Neither of the two values a coefficient cannot be built from, and
1190 // NaN would not even compare equal to itself on the way back.
1191 (
1192 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1193 "line 3: \"inf\" is not a number",
1194 ),
1195 (
1196 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1197 "line 3: \"NaN\" is not a number",
1198 ),
1199 (
1200 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
1201 "line 4: clip names eq 1 of 1",
1202 ),
1203 (
1204 format!("{head}video 1 0 0 5 0 - 0\n"),
1205 "line 3: clip names eq 0 of 0",
1206 ),
1207 // A clip's eq field is not optional in v5, and the table has to be
1208 // declared before the clip that names it.
1209 (
1210 format!("{head}video 1 0 0 5 0 -\n"),
1211 "line 3: clip wants 6 fields, found 5",
1212 ),
1213 (
1214 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
1215 "line 4: eq after a clip",
1216 ),
1217 // ...and an eq line in a file that predates them is a corrupt file.
1218 (
1219 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
1220 "line 3: unknown keyword \"eq\"",
1221 ),
1222 ] {
1223 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1224 }
1225 }
1226
1227 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
1228 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
1229 /// and not one byte else.
1230 #[test]
1231 fn a_v4_file_equalizes_nothing() {
1232 let dir = PathBuf::from("/proj");
1233 let (_, sources, lanes) = doc();
1234 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1235 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
1236 let old = parse(v4, &dir).expect("v4 parses");
1237 assert_eq!(
1238 (&old.sources, &old.lanes, old.playhead),
1239 (&sources, &lanes, 12)
1240 );
1241 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1242 assert_eq!(
1243 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1244 "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1245 source 2 /elsewhere/b.mp4\n\
1246 video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1247 audio 1 0 0 30 0 0 - - fit\n"
1248 );
1249 // An empty lane's line is still the whole of that lane, eq or no eq.
1250 let empty = parse(
1251 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
1252 &dir,
1253 )
1254 .expect("parse");
1255 assert!(empty.lanes[1].1.is_empty());
1256 }
1257
1258 /// The other half of the compatibility promise: a v3 file is a v4 one
1259 /// without the lane numbers, and a v2 file names no audio stream and means
1260 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
1261 /// they always were, and saving either writes v5 with nothing else changed.
1262 #[test]
1263 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
1264 let dir = PathBuf::from("/proj");
1265 let (_, _, lanes) = doc();
1266 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1267 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1268 let old = parse(v3, &dir).expect("v3 parses");
1269 assert_eq!(
1270 (&old.sources, &old.lanes, old.playhead),
1271 (
1272 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
1273 &lanes,
1274 12
1275 ),
1276 "a v3 file loads as exactly the state its v5 twin does"
1277 );
1278 // ...and re-saved it *is* that twin: the magic and a lane number per
1279 // clip line, and not one byte else.
1280 assert_eq!(
1281 flat(&dir, &old.sources, &old.lanes, old.playhead),
1282 flat(&dir, &old.sources, &lanes, 12),
1283 );
1284
1285 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
1286 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1287 let back = parse(v2, &dir).expect("v2 parses");
1288 assert_eq!(
1289 back.sources,
1290 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
1291 );
1292 assert_eq!(back.lanes, lanes);
1293
1294 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1295 assert_eq!(
1296 String::from_utf8_lossy(&v5),
1297 "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1298 source 0 /elsewhere/b.mp4\n\
1299 video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1300 audio 1 0 0 30 0 0 - - fit\n",
1301 "a re-saved v2 project differs only by its version, the lane \
1302 numbers, the streams it always meant and an equalizer it has none of"
1303 );
1304 let again = parse(&v5, &dir).expect("v5 parses");
1305 assert_eq!(again.sources, back.sources);
1306 }
1307
1308 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
1309 /// lanes, and saving it again writes v5.
1310 #[test]
1311 fn a_v1_file_loads_as_two_grouped_lanes() {
1312 let dir = PathBuf::from("/proj");
1313 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
1314 let back = parse(v1, &dir).expect("v1 parses");
1315 assert_eq!(
1316 back.lanes[0].1,
1317 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
1318 "v1 clips queue up: the second starts where the first ended"
1319 );
1320 assert_eq!(
1321 back.lanes,
1322 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
1323 "one take per clip, on both lanes"
1324 );
1325 assert_eq!(back.playhead, 5);
1326 // Saved again it is the current version, which round-trips to the
1327 // same document.
1328 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1329 assert!(v5.starts_with(b"edith 7\n"));
1330 let again = parse(&v5, &dir).expect("v5 parses");
1331 assert_eq!(again.lanes, back.lanes);
1332 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
1333 for (bytes, want) in [
1334 (
1335 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
1336 "line 3: unknown keyword \"video\"",
1337 ),
1338 (
1339 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
1340 "line 3: unknown keyword \"clip\"",
1341 ),
1342 ] {
1343 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
1344 }
1345 }
1346
1347 /// A gap is the absence of a line, so a lane's placements must arrive in
1348 /// order and never overlap -- the invariant the whole model rests on.
1349 #[test]
1350 fn a_lane_out_of_order_or_overlapping_is_refused() {
1351 let dir = PathBuf::from("/proj");
1352 for bytes in [
1353 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
1354 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
1355 ] {
1356 let err = parse(bytes, &dir).unwrap_err().to_string();
1357 assert!(err.starts_with("line 4: clip at "), "{err}");
1358 }
1359 // The lanes are independent, so a video line never crowds an audio one.
1360 assert!(
1361 parse(
1362 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
1363 &dir
1364 )
1365 .is_ok()
1366 );
1367 // ...and a lane may be empty as long as the other one is not.
1368 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
1369 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
1370 }
1371
1372 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
1373 /// and wrap in release, and a wrapped end passes the overlap check --
1374 /// crafted numbers must be refused by name, in both dialects.
1375 #[test]
1376 fn a_clip_whose_end_overflows_is_refused() {
1377 let dir = PathBuf::from("/proj");
1378 for bytes in [
1379 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
1380 // Two of them: the second would land *before* the first once wrapped.
1381 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
1382 // v1 has no `start` field, but its queue reaches the same ceiling.
1383 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
1384 ] {
1385 let err = parse(bytes, &dir).unwrap_err().to_string();
1386 assert!(
1387 err.contains("runs past the last frame there is"),
1388 "not refused by name: {err}"
1389 );
1390 }
1391 }
1392
1393 /// The relocatability promise, from the two directions a project path
1394 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
1395 /// clip.mp4`, whose parent is `""`) and a directory reached through a
1396 /// symlink. Both used to emit absolute source lines.
1397 #[test]
1398 fn a_non_canonical_project_path_still_writes_relative_sources() {
1399 assert_eq!(
1400 project_dir(Path::new("a.edith")),
1401 std::env::current_dir().expect("cwd"),
1402 "a bare filename is saved into the working directory"
1403 );
1404
1405 let dir = std::env::temp_dir().join(format!("ve_edith_link_{}", std::process::id()));
1406 let _ = std::fs::remove_dir_all(&dir);
1407 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
1408 let dir = std::fs::canonicalize(&dir).expect("canonical scratch dir");
1409 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
1410 let source = dir.join("real/a.mp4");
1411 let path = dir.join("link/p.edith");
1412
1413 let one = [clip(0, 0, 30, 0, None)];
1414 let entry = Source {
1415 path: source,
1416 audio_stream: 1,
1417 };
1418 save(
1419 &path,
1420 &[entry],
1421 &two(one.to_vec(), one.to_vec()),
1422 &[],
1423 &[],
1424 (1280, 720),
1425 0,
1426 )
1427 .expect("save");
1428 let bytes = std::fs::read(&path).expect("read back");
1429 assert_eq!(
1430 String::from_utf8_lossy(&bytes),
1431 "edith 7\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1432 video 1 0 0 30 0 - - - fit\naudio 1 0 0 30 0 - - - fit\n"
1433 );
1434 // Loading rejoins the *given* directory, so the file is reached by the
1435 // way the project was opened -- the same file, through the link, still
1436 // playing the stream it was saved on.
1437 assert_eq!(
1438 load(&path).expect("load").sources,
1439 vec![Source {
1440 path: dir.join("link/a.mp4"),
1441 audio_stream: 1,
1442 }]
1443 );
1444 std::fs::remove_dir_all(&dir).expect("cleanup");
1445 }
1446
1447 #[test]
1448 fn escapes_survive_the_bytes_json_would_not() {
1449 let dir = PathBuf::from("/proj");
1450 // A newline and a percent in a filename, plus a non-UTF-8 byte.
1451 let nasty = Source {
1452 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
1453 audio_stream: 0,
1454 };
1455 let bytes = flat(
1456 &dir,
1457 &[nasty.clone()],
1458 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
1459 0,
1460 );
1461 assert_eq!(
1462 bytes.iter().filter(|&&b| b == b'\n').count(),
1463 6,
1464 "the escaped newline must not become a line break: magic, playhead, \
1465 resolution, source, the clip, and the empty audio lane's own line"
1466 );
1467 let back = parse(&bytes, &dir).expect("parse");
1468 // The spaces in it are the reason the stream field leads rather than
1469 // trails: everything after the first one is path.
1470 assert_eq!(back.sources, vec![nasty]);
1471 }
1472
1473 #[test]
1474 fn a_wrong_first_line_is_refused_by_name() {
1475 let dir = PathBuf::from("/proj");
1476 let err = parse(b"edith 8\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
1477 .unwrap_err()
1478 .to_string();
1479 assert_eq!(err, "line 1: unsupported version 8");
1480 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
1481 assert_eq!(
1482 parse(junk, &dir).unwrap_err().to_string(),
1483 "line 1: not a edith file"
1484 );
1485 }
1486 }
1487
1488 #[test]
1489 fn malformed_lines_name_their_line_number() {
1490 let dir = PathBuf::from("/proj");
1491 let cases: [(&[u8], &str); 10] = [
1492 // v3 wants the stream before the path, and a path after it.
1493 (
1494 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
1495 "line 2: \"a.mp4\" is not a number",
1496 ),
1497 (
1498 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
1499 "line 2: source without a path",
1500 ),
1501 (
1502 b"edith 1\nsource a.mp4\nclip 0 5\n",
1503 "line 3: clip wants 3 fields, found 2",
1504 ),
1505 (
1506 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
1507 "line 3: \"five\" is not a number",
1508 ),
1509 (
1510 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
1511 "line 3: clip [5, 5) is empty",
1512 ),
1513 (
1514 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
1515 "line 3: clip [7, 5) is empty",
1516 ),
1517 (
1518 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
1519 "line 3: clip names source 1 of 1",
1520 ),
1521 (
1522 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
1523 "line 4: source after a clip",
1524 ),
1525 (
1526 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
1527 "line 3: unknown keyword \"\"",
1528 ),
1529 (
1530 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
1531 "line 3: playhead belongs once, before the sources",
1532 ),
1533 ];
1534 for (bytes, want) in cases {
1535 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
1536 }
1537 }
1538
1539 /// The emptied timeline writes and reads back: every lane declared, no clip
1540 /// on any of them, and the source that gave the project its frame rate still
1541 /// named. Nothing about the format changes for it -- an empty lane already
1542 /// had a line of its own.
1543 #[test]
1544 fn a_project_without_clips_round_trips() {
1545 let dir = PathBuf::from("/proj");
1546 let source = Source {
1547 path: PathBuf::from("/proj/a.mp4"),
1548 audio_stream: 0,
1549 };
1550 let bytes = flat(&dir, &[source.clone()], &two(Vec::new(), Vec::new()), 0);
1551 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
1552 assert_eq!(back.sources, vec![source]);
1553 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
1554 assert_eq!(back.playhead, 0);
1555 // Older dialects, where the two lanes are implied rather than declared.
1556 assert_eq!(
1557 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
1558 two(Vec::new(), Vec::new())
1559 );
1560 assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty());
1561 }
1562
1563 /// Every truncation of a good file either parses or refuses; none panics.
1564 #[test]
1565 fn truncations_never_panic() {
1566 let (dir, sources, lanes) = doc();
1567 let bytes = flat(&dir, &sources, &lanes, 12);
1568 for cut in 0..bytes.len() {
1569 let _ = parse(&bytes[..cut], &dir);
1570 // ...and the same file with a byte lopped off the front, which
1571 // shifts every field into the wrong place.
1572 let _ = parse(&bytes[cut..], &dir);
1573 }
1574 // A % escape at the very end of a line has nothing to consume.
1575 assert_eq!(
1576 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
1577 .unwrap_err()
1578 .to_string(),
1579 "line 2: truncated % escape in the path"
1580 );
1581 }
1582}