forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

edith.rs1576 lines, 62.0 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 if doc.lanes.iter().all(|(_, clips)| clips.is_empty()) {
508 return Err("no clips: an empty timeline is not a project".into());
509 }
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 not a project.
874 assert_eq!(
875 parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir)
876 .unwrap_err()
877 .to_string(),
878 "no clips: an empty timeline is not a project"
879 );
880 }
881
882 /// One band, spelled the way an eq line spells it.
883 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
884 Band {
885 freq_hz,
886 gain_db,
887 q,
888 kind,
889 }
890 }
891
892 /// The whole of the v5 bump: the clips name a shared equalizer table, the
893 /// bytes are the ones documented at the top of this file, and every f32 in
894 /// them comes back *bit* for bit -- which is what makes a re-save of a
895 /// loaded project produce the same file rather than a drifting one.
896 #[test]
897 fn equalizers_round_trip_bit_exactly_and_are_shared() {
898 let dir = PathBuf::from("/proj");
899 let sources = vec![source("/proj/a.mp4", 0)];
900 let eq = vec![
901 EqParams {
902 bands: vec![
903 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
904 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
905 ],
906 },
907 // The awkward ones: a value needing all 24 mantissa bits, one whose
908 // shortest spelling is exponential, a subnormal, and a negative
909 // zero -- plus the empty cascade, which is a setting like any other.
910 EqParams {
911 bands: vec![band_of(
912 16_777_215.0,
913 -0.1,
914 f32::MIN_POSITIVE / 3.0,
915 BandKind::HighShelf,
916 )],
917 },
918 EqParams { bands: Vec::new() },
919 ];
920 // Two clips share entry 0, so it is written once; one clip plays flat.
921 let lanes = two(
922 vec![
923 Clip {
924 eq: Some(0),
925 ..clip(0, 0, 30, 0, Some(0))
926 },
927 Clip {
928 eq: Some(1),
929 ..clip(30, 10, 20, 0, None)
930 },
931 ],
932 vec![
933 Clip {
934 eq: Some(0),
935 ..clip(0, 0, 30, 0, Some(0))
936 },
937 Clip {
938 eq: Some(2),
939 ..clip(30, 0, 10, 0, None)
940 },
941 ],
942 );
943 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
944 assert_eq!(
945 String::from_utf8_lossy(&bytes),
946 "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
947 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
948 eq 16777215.0:-0.1:3.918315e-39:hs\n\
949 eq\n\
950 video 1 0 0 30 0 0 0 - fit\nvideo 1 30 10 20 0 - 1 - fit\n\
951 audio 1 0 0 30 0 0 0 - fit\naudio 1 30 0 10 0 - 2 - fit\n",
952 "the table comes before the clips, and a clip names a line of it"
953 );
954
955 let back = parse(&bytes, &dir).expect("parse");
956 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
957 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
958 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
959 assert_eq!(
960 (
961 got.freq_hz.to_bits(),
962 got.gain_db.to_bits(),
963 got.q.to_bits(),
964 got.kind
965 ),
966 (
967 want.freq_hz.to_bits(),
968 want.gain_db.to_bits(),
969 want.q.to_bits(),
970 want.kind
971 ),
972 "eq {i} band {b} came back as other bits"
973 );
974 }
975 }
976 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
977 assert_eq!(
978 emit(
979 &dir,
980 &back.sources,
981 &back.lanes,
982 &back.eq,
983 &back.color,
984 (1280, 720),
985 0
986 ),
987 bytes
988 );
989 }
990
991 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
992 /// colour table, the bytes are the ones documented at the top of this file,
993 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
994 #[test]
995 fn colours_round_trip_bit_exactly_and_are_shared() {
996 let dir = PathBuf::from("/proj");
997 let sources = vec![source("/proj/a.mp4", 0)];
998 let color = vec![
999 ColorParams {
1000 brightness: 0.1,
1001 contrast: 1.2,
1002 saturation: 0.9,
1003 tint: -0.3,
1004 },
1005 // The awkward ones again: all 24 mantissa bits, an exponential
1006 // spelling, a subnormal and a negative zero -- and the identity,
1007 // which is a setting like any other.
1008 ColorParams {
1009 brightness: -0.000_000_1,
1010 contrast: 16_777_215.0,
1011 saturation: f32::MIN_POSITIVE / 3.0,
1012 tint: -0.0,
1013 },
1014 ColorParams::default(),
1015 ];
1016 // Two clips share entry 0, so it is written once; one clip is ungraded.
1017 let lanes = two(
1018 vec![
1019 Clip {
1020 color: Some(0),
1021 fit: FitPolicy::default(),
1022 ..clip(0, 0, 30, 0, Some(0))
1023 },
1024 Clip {
1025 color: Some(1),
1026 fit: FitPolicy::default(),
1027 ..clip(30, 10, 20, 0, None)
1028 },
1029 ],
1030 vec![
1031 Clip {
1032 color: Some(0),
1033 fit: FitPolicy::default(),
1034 ..clip(0, 0, 30, 0, Some(0))
1035 },
1036 Clip {
1037 color: Some(2),
1038 fit: FitPolicy::default(),
1039 ..clip(30, 0, 10, 0, None)
1040 },
1041 ],
1042 );
1043 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1044 assert_eq!(
1045 String::from_utf8_lossy(&bytes),
1046 "edith 7\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1047 color 0.1:1.2:0.9:-0.3\n\
1048 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1049 color 0.0:1.0:1.0:0.0\n\
1050 video 1 0 0 30 0 0 - 0 fit\nvideo 1 30 10 20 0 - - 1 fit\n\
1051 audio 1 0 0 30 0 0 - 0 fit\naudio 1 30 0 10 0 - - 2 fit\n",
1052 "the table comes before the clips, and a clip names a line of it"
1053 );
1054
1055 let back = parse(&bytes, &dir).expect("parse");
1056 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
1057 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
1058 assert_eq!(
1059 (
1060 got.brightness.to_bits(),
1061 got.contrast.to_bits(),
1062 got.saturation.to_bits(),
1063 got.tint.to_bits()
1064 ),
1065 (
1066 want.brightness.to_bits(),
1067 want.contrast.to_bits(),
1068 want.saturation.to_bits(),
1069 want.tint.to_bits()
1070 ),
1071 "color {i} came back as other bits"
1072 );
1073 }
1074 assert_eq!(back.color.len(), 3);
1075 assert_eq!(
1076 emit(
1077 &dir,
1078 &back.sources,
1079 &back.lanes,
1080 &back.eq,
1081 &back.color,
1082 (1280, 720),
1083 0
1084 ),
1085 bytes
1086 );
1087 }
1088
1089 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
1090 /// intact, and re-saving it writes the new magic and a `-` colour field.
1091 #[test]
1092 fn a_v5_file_grades_nothing() {
1093 let dir = PathBuf::from("/proj");
1094 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
1095 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
1096 let old = parse(v5, &dir).expect("v5 parses");
1097 assert!(old.color.is_empty(), "nothing before v6 grades anything");
1098 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
1099 assert_eq!(old.lanes[0].1[0].eq, Some(0));
1100 assert!(old.lanes[0].1[0].color.is_none());
1101 assert_eq!(
1102 String::from_utf8_lossy(&emit(
1103 &dir,
1104 &old.sources,
1105 &old.lanes,
1106 &old.eq,
1107 &old.color,
1108 (1280, 720),
1109 old.playhead
1110 )),
1111 "edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1112 eq 80.0:-3.0:0.707:ls\n\
1113 video 1 0 0 30 0 0 0 - fit\naudio 1 0 0 30 0 0 - - fit\n"
1114 );
1115 }
1116
1117 /// The refusals the colour grammar adds, each naming its line.
1118 #[test]
1119 fn a_malformed_colour_names_its_line() {
1120 let dir = PathBuf::from("/proj");
1121 let head = "edith 6\nsource 0 a.mp4\n";
1122 // v6, deliberately: the colour grammar is the same one v7 inherits, and
1123 // a v6 clip line is one field shorter.
1124 for (file, want) in [
1125 (
1126 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
1127 "line 3: color wants 4 fields, found 3",
1128 ),
1129 (
1130 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"),
1131 "line 3: color wants 1 fields, found 2",
1132 ),
1133 (
1134 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1135 "line 3: \"warm\" is not a number",
1136 ),
1137 // The two values the format cannot write and read back as itself.
1138 (
1139 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1140 "line 3: \"inf\" is not a number",
1141 ),
1142 (
1143 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
1144 "line 3: \"NaN\" is not a number",
1145 ),
1146 (
1147 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
1148 "line 4: clip names color 1 of 1",
1149 ),
1150 (
1151 format!("{head}video 1 0 0 5 0 - - 0\n"),
1152 "line 3: clip names color 0 of 0",
1153 ),
1154 // A clip's colour field is not optional in v6, and the table has to
1155 // be declared before the clip that names it.
1156 (
1157 format!("{head}video 1 0 0 5 0 - -\n"),
1158 "line 3: clip wants 7 fields, found 6",
1159 ),
1160 (
1161 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
1162 "line 4: color after a clip",
1163 ),
1164 // ...and a colour line in a file that predates them is a corrupt one.
1165 (
1166 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
1167 "line 3: unknown keyword \"color\"",
1168 ),
1169 ] {
1170 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1171 }
1172 }
1173
1174 /// The refusals the eq grammar adds, each naming its line.
1175 #[test]
1176 fn a_malformed_equalizer_names_its_line() {
1177 let dir = PathBuf::from("/proj");
1178 let head = "edith 5\nsource 0 a.mp4\n";
1179 for (file, want) in [
1180 (
1181 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
1182 "line 3: band wants 4 fields, found 3",
1183 ),
1184 (
1185 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
1186 "line 3: \"notch\" is not a band shape",
1187 ),
1188 (
1189 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
1190 "line 3: \"wide\" is not a number",
1191 ),
1192 // Neither of the two values a coefficient cannot be built from, and
1193 // NaN would not even compare equal to itself on the way back.
1194 (
1195 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1196 "line 3: \"inf\" is not a number",
1197 ),
1198 (
1199 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1200 "line 3: \"NaN\" is not a number",
1201 ),
1202 (
1203 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
1204 "line 4: clip names eq 1 of 1",
1205 ),
1206 (
1207 format!("{head}video 1 0 0 5 0 - 0\n"),
1208 "line 3: clip names eq 0 of 0",
1209 ),
1210 // A clip's eq field is not optional in v5, and the table has to be
1211 // declared before the clip that names it.
1212 (
1213 format!("{head}video 1 0 0 5 0 -\n"),
1214 "line 3: clip wants 6 fields, found 5",
1215 ),
1216 (
1217 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
1218 "line 4: eq after a clip",
1219 ),
1220 // ...and an eq line in a file that predates them is a corrupt file.
1221 (
1222 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
1223 "line 3: unknown keyword \"eq\"",
1224 ),
1225 ] {
1226 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1227 }
1228 }
1229
1230 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
1231 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
1232 /// and not one byte else.
1233 #[test]
1234 fn a_v4_file_equalizes_nothing() {
1235 let dir = PathBuf::from("/proj");
1236 let (_, sources, lanes) = doc();
1237 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1238 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
1239 let old = parse(v4, &dir).expect("v4 parses");
1240 assert_eq!(
1241 (&old.sources, &old.lanes, old.playhead),
1242 (&sources, &lanes, 12)
1243 );
1244 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1245 assert_eq!(
1246 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1247 "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1248 source 2 /elsewhere/b.mp4\n\
1249 video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1250 audio 1 0 0 30 0 0 - - fit\n"
1251 );
1252 // An empty lane's line is still the whole of that lane, eq or no eq.
1253 let empty = parse(
1254 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
1255 &dir,
1256 )
1257 .expect("parse");
1258 assert!(empty.lanes[1].1.is_empty());
1259 }
1260
1261 /// The other half of the compatibility promise: a v3 file is a v4 one
1262 /// without the lane numbers, and a v2 file names no audio stream and means
1263 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
1264 /// they always were, and saving either writes v5 with nothing else changed.
1265 #[test]
1266 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
1267 let dir = PathBuf::from("/proj");
1268 let (_, _, lanes) = doc();
1269 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1270 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1271 let old = parse(v3, &dir).expect("v3 parses");
1272 assert_eq!(
1273 (&old.sources, &old.lanes, old.playhead),
1274 (
1275 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
1276 &lanes,
1277 12
1278 ),
1279 "a v3 file loads as exactly the state its v5 twin does"
1280 );
1281 // ...and re-saved it *is* that twin: the magic and a lane number per
1282 // clip line, and not one byte else.
1283 assert_eq!(
1284 flat(&dir, &old.sources, &old.lanes, old.playhead),
1285 flat(&dir, &old.sources, &lanes, 12),
1286 );
1287
1288 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
1289 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1290 let back = parse(v2, &dir).expect("v2 parses");
1291 assert_eq!(
1292 back.sources,
1293 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
1294 );
1295 assert_eq!(back.lanes, lanes);
1296
1297 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1298 assert_eq!(
1299 String::from_utf8_lossy(&v5),
1300 "edith 7\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1301 source 0 /elsewhere/b.mp4\n\
1302 video 1 0 0 30 0 0 - - fit\nvideo 1 30 10 20 1 1 - - fit\n\
1303 audio 1 0 0 30 0 0 - - fit\n",
1304 "a re-saved v2 project differs only by its version, the lane \
1305 numbers, the streams it always meant and an equalizer it has none of"
1306 );
1307 let again = parse(&v5, &dir).expect("v5 parses");
1308 assert_eq!(again.sources, back.sources);
1309 }
1310
1311 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
1312 /// lanes, and saving it again writes v5.
1313 #[test]
1314 fn a_v1_file_loads_as_two_grouped_lanes() {
1315 let dir = PathBuf::from("/proj");
1316 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
1317 let back = parse(v1, &dir).expect("v1 parses");
1318 assert_eq!(
1319 back.lanes[0].1,
1320 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
1321 "v1 clips queue up: the second starts where the first ended"
1322 );
1323 assert_eq!(
1324 back.lanes,
1325 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
1326 "one take per clip, on both lanes"
1327 );
1328 assert_eq!(back.playhead, 5);
1329 // Saved again it is the current version, which round-trips to the
1330 // same document.
1331 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1332 assert!(v5.starts_with(b"edith 7\n"));
1333 let again = parse(&v5, &dir).expect("v5 parses");
1334 assert_eq!(again.lanes, back.lanes);
1335 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
1336 for (bytes, want) in [
1337 (
1338 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
1339 "line 3: unknown keyword \"video\"",
1340 ),
1341 (
1342 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
1343 "line 3: unknown keyword \"clip\"",
1344 ),
1345 ] {
1346 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
1347 }
1348 }
1349
1350 /// A gap is the absence of a line, so a lane's placements must arrive in
1351 /// order and never overlap -- the invariant the whole model rests on.
1352 #[test]
1353 fn a_lane_out_of_order_or_overlapping_is_refused() {
1354 let dir = PathBuf::from("/proj");
1355 for bytes in [
1356 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
1357 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
1358 ] {
1359 let err = parse(bytes, &dir).unwrap_err().to_string();
1360 assert!(err.starts_with("line 4: clip at "), "{err}");
1361 }
1362 // The lanes are independent, so a video line never crowds an audio one.
1363 assert!(
1364 parse(
1365 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
1366 &dir
1367 )
1368 .is_ok()
1369 );
1370 // ...and a lane may be empty as long as the other one is not.
1371 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
1372 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
1373 }
1374
1375 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
1376 /// and wrap in release, and a wrapped end passes the overlap check --
1377 /// crafted numbers must be refused by name, in both dialects.
1378 #[test]
1379 fn a_clip_whose_end_overflows_is_refused() {
1380 let dir = PathBuf::from("/proj");
1381 for bytes in [
1382 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
1383 // Two of them: the second would land *before* the first once wrapped.
1384 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
1385 // v1 has no `start` field, but its queue reaches the same ceiling.
1386 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
1387 ] {
1388 let err = parse(bytes, &dir).unwrap_err().to_string();
1389 assert!(
1390 err.contains("runs past the last frame there is"),
1391 "not refused by name: {err}"
1392 );
1393 }
1394 }
1395
1396 /// The relocatability promise, from the two directions a project path
1397 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
1398 /// clip.mp4`, whose parent is `""`) and a directory reached through a
1399 /// symlink. Both used to emit absolute source lines.
1400 #[test]
1401 fn a_non_canonical_project_path_still_writes_relative_sources() {
1402 assert_eq!(
1403 project_dir(Path::new("a.edith")),
1404 std::env::current_dir().expect("cwd"),
1405 "a bare filename is saved into the working directory"
1406 );
1407
1408 let dir = std::env::temp_dir().join(format!("ve_edith_link_{}", std::process::id()));
1409 let _ = std::fs::remove_dir_all(&dir);
1410 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
1411 let dir = std::fs::canonicalize(&dir).expect("canonical scratch dir");
1412 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
1413 let source = dir.join("real/a.mp4");
1414 let path = dir.join("link/p.edith");
1415
1416 let one = [clip(0, 0, 30, 0, None)];
1417 let entry = Source {
1418 path: source,
1419 audio_stream: 1,
1420 };
1421 save(
1422 &path,
1423 &[entry],
1424 &two(one.to_vec(), one.to_vec()),
1425 &[],
1426 &[],
1427 (1280, 720),
1428 0,
1429 )
1430 .expect("save");
1431 let bytes = std::fs::read(&path).expect("read back");
1432 assert_eq!(
1433 String::from_utf8_lossy(&bytes),
1434 "edith 7\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1435 video 1 0 0 30 0 - - - fit\naudio 1 0 0 30 0 - - - fit\n"
1436 );
1437 // Loading rejoins the *given* directory, so the file is reached by the
1438 // way the project was opened -- the same file, through the link, still
1439 // playing the stream it was saved on.
1440 assert_eq!(
1441 load(&path).expect("load").sources,
1442 vec![Source {
1443 path: dir.join("link/a.mp4"),
1444 audio_stream: 1,
1445 }]
1446 );
1447 std::fs::remove_dir_all(&dir).expect("cleanup");
1448 }
1449
1450 #[test]
1451 fn escapes_survive_the_bytes_json_would_not() {
1452 let dir = PathBuf::from("/proj");
1453 // A newline and a percent in a filename, plus a non-UTF-8 byte.
1454 let nasty = Source {
1455 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
1456 audio_stream: 0,
1457 };
1458 let bytes = flat(
1459 &dir,
1460 &[nasty.clone()],
1461 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
1462 0,
1463 );
1464 assert_eq!(
1465 bytes.iter().filter(|&&b| b == b'\n').count(),
1466 6,
1467 "the escaped newline must not become a line break: magic, playhead, \
1468 resolution, source, the clip, and the empty audio lane's own line"
1469 );
1470 let back = parse(&bytes, &dir).expect("parse");
1471 // The spaces in it are the reason the stream field leads rather than
1472 // trails: everything after the first one is path.
1473 assert_eq!(back.sources, vec![nasty]);
1474 }
1475
1476 #[test]
1477 fn a_wrong_first_line_is_refused_by_name() {
1478 let dir = PathBuf::from("/proj");
1479 let err = parse(b"edith 8\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
1480 .unwrap_err()
1481 .to_string();
1482 assert_eq!(err, "line 1: unsupported version 8");
1483 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
1484 assert_eq!(
1485 parse(junk, &dir).unwrap_err().to_string(),
1486 "line 1: not a edith file"
1487 );
1488 }
1489 }
1490
1491 #[test]
1492 fn malformed_lines_name_their_line_number() {
1493 let dir = PathBuf::from("/proj");
1494 let cases: [(&[u8], &str); 10] = [
1495 // v3 wants the stream before the path, and a path after it.
1496 (
1497 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
1498 "line 2: \"a.mp4\" is not a number",
1499 ),
1500 (
1501 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
1502 "line 2: source without a path",
1503 ),
1504 (
1505 b"edith 1\nsource a.mp4\nclip 0 5\n",
1506 "line 3: clip wants 3 fields, found 2",
1507 ),
1508 (
1509 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
1510 "line 3: \"five\" is not a number",
1511 ),
1512 (
1513 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
1514 "line 3: clip [5, 5) is empty",
1515 ),
1516 (
1517 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
1518 "line 3: clip [7, 5) is empty",
1519 ),
1520 (
1521 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
1522 "line 3: clip names source 1 of 1",
1523 ),
1524 (
1525 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
1526 "line 4: source after a clip",
1527 ),
1528 (
1529 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
1530 "line 3: unknown keyword \"\"",
1531 ),
1532 (
1533 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
1534 "line 3: playhead belongs once, before the sources",
1535 ),
1536 ];
1537 for (bytes, want) in cases {
1538 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
1539 }
1540 }
1541
1542 #[test]
1543 fn a_project_without_clips_is_not_a_project() {
1544 let dir = PathBuf::from("/proj");
1545 assert_eq!(
1546 parse(b"edith 1\nsource a.mp4\n", &dir)
1547 .unwrap_err()
1548 .to_string(),
1549 "no clips: an empty timeline is not a project"
1550 );
1551 assert_eq!(
1552 parse(b"edith 1\n", &dir).unwrap_err().to_string(),
1553 "no clips: an empty timeline is not a project"
1554 );
1555 }
1556
1557 /// Every truncation of a good file either parses or refuses; none panics.
1558 #[test]
1559 fn truncations_never_panic() {
1560 let (dir, sources, lanes) = doc();
1561 let bytes = flat(&dir, &sources, &lanes, 12);
1562 for cut in 0..bytes.len() {
1563 let _ = parse(&bytes[..cut], &dir);
1564 // ...and the same file with a byte lopped off the front, which
1565 // shifts every field into the wrong place.
1566 let _ = parse(&bytes[cut..], &dir);
1567 }
1568 // A % escape at the very end of a line has nothing to consume.
1569 assert_eq!(
1570 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
1571 .unwrap_err()
1572 .to_string(),
1573 "line 2: truncated % escape in the path"
1574 );
1575 }
1576}