forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB65ea910Tahinli3 months ago308 commits

edith.rs2241 lines, 90.9 KiBHistoryRawDownload
1//! The project file: a line of text per thing, and nothing else.
2//!
3//! ```text
4//! edith 11
5//! playhead 90
6//! resolution 1920 1080
7//! fps 30.0
8//! tonemap vivid
9//! limiter -1.0 on
10//! source 0 test_av.mp4
11//! source 1 /elsewhere/test_av2.mp4
12//! subtitle - subs.srt
13//! subtitle 3 test_av.mp4
14//! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
15//! color 0.1:1.2:0.9:-0.3
16//! video 1 0 0 120 0 0 0 0 fit 1000
17//! audio 1 0 0 120 0 0 0 - fit 1000
18//! video 2 120 0 120 1 - - - fill 2000
19//! audio 2
20//! gain audio 1 -3.0
21//! ```
22//!
23//! The `fps` line is the rate the timeline was cut at -- the scaffolding
24//! source's own unless a rate was picked
25//! ([`crate::PlaybackSession::set_frame_rate`]), and the *only* thing that says
26//! so once one was, since every clip number in the file is counted in it.
27//! Printed so it reads back bit-exactly. A file without one (every dialect
28//! before v9) means "whatever the scaffolding source runs at", which is what
29//! such a project always was and is an answer only a project holding a video has
30//! ([`crate::PlaybackSession::open_project`]).
31//!
32//! A `subtitle` line is `subtitle <track> <path>`: which track of that file the
33//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle
34//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the
35//! reason a source's is. Only the reference is written: the cues themselves are
36//! read back out of the file on the way in, exactly as a clip's pictures are, so
37//! a project file stays an edit list. A subtitle file that has gone missing
38//! since the save comes back listed and refused by name rather than dropped,
39//! which is what keeps a re-save from losing it.
40//!
41//! The `tonemap` line is which HDR-to-SDR rendition the project is watched and
42//! exported in ([`crate::tonemap::Preset`]), spelled `reference`, `standard` or
43//! `vivid`. Left out when it is the default, which is `reference` -- so a
44//! project holding no HDR media, and one whose owner never picked, are the bytes
45//! they were.
46//!
47//! The `limiter` line is the master limiter over the whole mix
48//! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,
49//! spelled `on` or `off`. Left out when it is the default, which is off.
50//!
51//! A `gain` line is `gain <kind> <lane> <dB>`: how loud that whole lane plays,
52//! everything on it and every frequency of it -- a different thing from a
53//! clip's `eq` line, which is one take and one band. It names its lane the way
54//! a clip line does and comes *after* the lanes, because a lane is declared by
55//! its clips and a gain declares nothing. Only a lane somebody has turned gets
56//! one; the rest are at 0 dB, which is where every lane of every dialect before
57//! v9 is.
58//!
59//! The `resolution` line is the **project's** picture size, which is a
60//! different thing from any source's: media of other sizes are placed on it.
61//! It belongs once, beside the playhead, and a file without one (every dialect
62//! before v7) means "source 0's own picture", which is what such a project
63//! always was.
64//!
65//! A source line is `source <audio stream> <path>`: which of the file's audio
66//! tracks that source plays, in the file order
67//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
68//! stream first because a path runs to the end of the line (it may hold
69//! spaces) and an optional *trailing* field could not be told from one.
70//!
71//! An eq line is `eq <band>...`, one band per field, each
72//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk` or
73//! `hs` ([`crate::eq::BandKind`]). Like a source it is named by *position* --
74//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
75//! curve write it once. `eq` on its own is the empty cascade, which is a
76//! setting like any other. The numbers are printed to round trip bit-exactly;
77//! anything not finite is refused, here and at [`crate::Project::set_eq`].
78//!
79//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
80//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
81//! -- the first colour line is color 0 -- printed and refused by the same rules.
82//!
83//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
84//! <color> <fit> <speed>`: which lane the clip is on -- its kind and its 1-based number
85//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
86//! column shows -- then where the clip sits on the timeline, the half-open
87//! source range it plays, the file it plays from, its group id, the eq line it
88//! plays through, the colour line it is graded by (`-` for none of those three)
89//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
90//! `stretch` or `center` ([`crate::scale::FitPolicy`]), and how fast it plays,
91//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip
92//! nobody has speeded). Timeline placement is
93//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
94//! to write for one, and nothing that can disagree about its length. The `<in>`
95//! and `<out>` are *source* frames whatever the speed says: how long the clip is
96//! on the timeline is that range divided by the rate, and is written nowhere.
97//!
98//! A lane is declared by the clips on it, in the order the lanes are displayed
99//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
100//! is the only way an empty lane could still be there on the way back. A lane
101//! number may not skip one of its kind.
102//!
103//! **Version 10** was this without the `tonemap` line: such a project is shown
104//! in the reference rendition, which is the only one there was.
105//! **Version 9** was that without the `subtitle` lines: such a project shows no
106//! subtitles, which is all any project could do.
107//! **Version 8** was that without the `fps` and `limiter` lines and without
108//! the `gain` ones: such a project mixes every lane at unity, limits nothing,
109//! and comes back at the rate its scaffolding source runs at.
110//! **Version 7** was that without the clip's speed field -- every clip of such
111//! a project plays at real time, which is the only rate there was.
112//! **Version 6** was that without the `resolution` line and without the clip's
113//! fit field -- such a project is the size of its first source and letterboxes
114//! nothing, because nothing on it could differ in size. **Version 5** was that
115//! without the colour lines and without the clip's colour
116//! field. **Version 4** was that without the eq lines and without the clip's eq
117//! field. **Version 3** was that without the lane number, and held one video
118//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
119//! well, which is this file's stream 0 -- one per file, whichever audio track
120//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
121//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
122//! cumulatively and copied onto both lanes as one group each, which is exactly
123//! what a v1 timeline meant, and an older file simply equalizes and grades
124//! nothing, and an older one plays everything at real time, and an older one
125//! mixes flat, and an older one shows no subtitles, and an older one is shown
126//! in the reference rendition -- and saving any of them writes v11. An older
127//! reader refuses a newer file by name.
128//!
129//! Text because an edit list is a few integers and a path, and a path is
130//! *bytes* on this platform -- a JSON string would have to lossily decode one.
131//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
132//! everything a line-based format cannot carry) and survives round-trip
133//! exactly. Paths under the project file's own directory are written relative
134//! to it, so a folder holding the media and the `.edith` can be moved or
135//! copied anywhere and still open; anything else is absolute.
136//!
137//! The parser is strict and every refusal names its 1-based line: a project
138//! file is generated, so a line it did not generate is a corrupt file, not a
139//! dialect. Structure is checked here (fields, ordering, empty clips,
140//! out-of-range source indexes); whether the files on disk still match the
141//! timeline is [`crate::PlaybackSession::open_project`]'s business.
142//!
143//! Writing goes through `<path>.part` and a rename, as an export does, so an
144//! interrupted save cannot destroy the previous version of the project. The
145//! bytes are fsynced before the rename and the directory after it, so what a
146//! power loss can lose is a whole save, never half of one under the real name.
147
148use std::ffi::OsString;
149use std::io::Write;
150use std::os::unix::ffi::{OsStrExt, OsStringExt};
151use std::path::{Path, PathBuf};
152
153use crate::color::ColorParams;
154use crate::eq::{Band, BandKind, EqParams};
155use crate::limiter::Limiter;
156use crate::project::{Clip, Lane, LaneKind, Source, Speed};
157use crate::scale::FitPolicy;
158use crate::subtitle::SubtitleTrack;
159
160/// What [`save`] writes. Read support goes back to `edith 1`; see the module
161/// docs for what those dialects looked like.
162const MAGIC: &[u8] = b"edith 11";
163const MAGIC_V10: &[u8] = b"edith 10";
164const MAGIC_V9: &[u8] = b"edith 9";
165const MAGIC_V8: &[u8] = b"edith 8";
166const MAGIC_V7: &[u8] = b"edith 7";
167const MAGIC_V6: &[u8] = b"edith 6";
168const MAGIC_V5: &[u8] = b"edith 5";
169const MAGIC_V4: &[u8] = b"edith 4";
170const MAGIC_V3: &[u8] = b"edith 3";
171const MAGIC_V2: &[u8] = b"edith 2";
172const MAGIC_V1: &[u8] = b"edith 1";
173
174/// What a project file says: an edit list plus where the playhead stood.
175/// Structurally valid by construction -- see [`parse`].
176#[derive(Debug)]
177pub struct Document {
178 /// Paths absolute, relative entries already joined to the file's own
179 /// directory.
180 pub sources: Vec<Source>,
181 /// Every lane, in display order, which is the order
182 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
183 /// `A1` -- for every dialect before v4.
184 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
185 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
186 /// every dialect before v5.
187 pub eq: Vec<EqParams>,
188 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
189 /// every dialect before v6.
190 pub color: Vec<ColorParams>,
191 /// The project's own picture size. `None` for every dialect before v7 and
192 /// for a v7 file that leaves it out, which both mean "source 0's picture".
193 pub resolution: Option<(u32, u32)>,
194 /// Every lane's own volume in dB, in the order `lanes` is in and as long as
195 /// it; `0.0` for a lane nobody has turned, which is every lane of every
196 /// dialect before v9.
197 pub gains: Vec<f32>,
198 /// The master limiter. Off for every dialect before v9, and for a v9 file
199 /// that leaves the line out.
200 pub limiter: Limiter,
201 /// The subtitle tracks, as the file names them: the path the cues are in
202 /// and which track of it, which is what [`crate::subtitle::open`] takes.
203 /// Reading them is the loader's business, not this module's -- a `.edith`
204 /// holds no cues. Empty for every dialect before v10.
205 pub subtitles: Vec<(PathBuf, Option<u64>)>,
206 /// The timeline's frame rate. `None` for every dialect before v9 and for a
207 /// v9 file that leaves it out, which both mean "whatever the scaffolding
208 /// source runs at" -- the inference a project of nothing but stills and
209 /// songs has no answer for (see
210 /// [`crate::PlaybackSession::open_project`]).
211 pub fps: Option<f64>,
212 /// The HDR-to-SDR rendition every clip on an HDR curve is shown in.
213 /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and
214 /// for a v11 file that leaves the line out, which both mean the published
215 /// conversion -- the only one those projects had.
216 pub tone: crate::tonemap::Preset,
217 pub playhead: u32,
218}
219
220/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
221/// already be orphan-free ([`crate::Project::without_orphan_sources`]);
222/// `gains` is one dB per lane in the same order the lanes are in
223/// ([`crate::Project::lane_gains`]).
224#[allow(clippy::too_many_arguments)]
225pub fn save(
226 path: &Path,
227 sources: &[Source],
228 lanes: &[(LaneKind, Vec<Clip>)],
229 gains: &[f32],
230 subtitles: &[SubtitleTrack],
231 eq: &[EqParams],
232 color: &[ColorParams],
233 resolution: (u32, u32),
234 fps: Option<f64>,
235 tone: crate::tonemap::Preset,
236 limiter: Limiter,
237 playhead: u32,
238) -> crate::Result<()> {
239 let dir = project_dir(path);
240 let mut part = path.to_path_buf().into_os_string();
241 part.push(".part");
242 let part = PathBuf::from(part);
243 // The rename publishes the file under the caller's name in one step, on the
244 // same directory; until it happens the old project file is still the whole
245 // truth. `sync_all` puts the bytes on the disk before that name exists, and
246 // the second one puts the name itself there.
247 let result = std::fs::File::create(&part)
248 .and_then(|mut f| {
249 f.write_all(&emit(
250 &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, tone,
251 limiter, playhead,
252 ))?;
253 f.sync_all()
254 })
255 .and_then(|()| std::fs::rename(&part, path))
256 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
257 if result.is_err() {
258 let _ = std::fs::remove_file(&part);
259 }
260 result.map_err(Into::into)
261}
262
263pub fn load(path: &Path) -> crate::Result<Document> {
264 let data = std::fs::read(path)?;
265 parse(&data, path.parent().unwrap_or(Path::new("")))
266}
267
268/// The directory a project file's relative source lines are measured from, in
269/// the same canonical form [`crate::Project`] keeps its sources in -- without
270/// that the prefix simply never matches and every line comes out absolute,
271/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
272/// a bare filename is `""`). Canonicalizing fails only if the directory does
273/// not exist, and then the write is about to fail anyway.
274fn project_dir(path: &Path) -> PathBuf {
275 let dir = path
276 .parent()
277 .filter(|p| !p.as_os_str().is_empty())
278 .unwrap_or(Path::new("."));
279 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
280}
281
282#[allow(clippy::too_many_arguments)]
283fn emit(
284 dir: &Path,
285 sources: &[Source],
286 lanes: &[(LaneKind, Vec<Clip>)],
287 gains: &[f32],
288 subtitles: &[SubtitleTrack],
289 eq: &[EqParams],
290 color: &[ColorParams],
291 resolution: (u32, u32),
292 fps: Option<f64>,
293 tone: crate::tonemap::Preset,
294 limiter: Limiter,
295 playhead: u32,
296) -> Vec<u8> {
297 let mut out = Vec::new();
298 out.extend_from_slice(MAGIC);
299 out.push(b'\n');
300 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
301 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
302 // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read
303 // back as the very number, or every clip on it lands on another frame.
304 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
305 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
306 }
307 // Beside the rate, and written only when it is not the default: a project
308 // holding no HDR media has nothing to say here, and saying nothing is what
309 // a v10 file already said.
310 if tone != crate::tonemap::Preset::default() {
311 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
312 }
313 // Written only when it is not the default, so a project nobody has limited
314 // is the same bytes it was in v8 bar the version line.
315 if limiter != Limiter::default() {
316 out.extend_from_slice(
317 format!(
318 "limiter {:?} {}\n",
319 limiter.ceiling_db,
320 match limiter.on {
321 true => "on",
322 false => "off",
323 }
324 )
325 .as_bytes(),
326 );
327 }
328 for s in sources {
329 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
330 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
331 out.push(b'\n');
332 }
333 // The subtitle tracks, by reference: which track of which file, and never
334 // the cues (see the module docs). Beside the sources because that is what
335 // they are -- a file this project reads from -- although nothing indexes
336 // them and their order is only the order they were added in.
337 for t in subtitles {
338 let track = t.track.map_or("-".to_string(), |n| n.to_string());
339 out.extend_from_slice(format!("subtitle {track} ").as_bytes());
340 escape(t.path.strip_prefix(dir).unwrap_or(&t.path), &mut out);
341 out.push(b'\n');
342 }
343 // Before the clips, for the reason the sources are: a clip names one by the
344 // position of its line, so the line has to be there first.
345 for params in eq {
346 out.extend_from_slice(b"eq");
347 for b in &params.bands {
348 // `{:?}` rather than `{}`: it is the formatting that promises the
349 // shortest string parsing back to this exact f32, and it never
350 // prints a bare integer, which would read as another field's shape.
351 let kind = match b.kind {
352 BandKind::LowShelf => "ls",
353 BandKind::Peak => "pk",
354 BandKind::HighShelf => "hs",
355 };
356 out.extend_from_slice(
357 format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
358 );
359 }
360 out.push(b'\n');
361 }
362 // ...and the colour table, for the same reason and by the same rules.
363 for p in color {
364 out.extend_from_slice(
365 format!(
366 "color {:?}:{:?}:{:?}:{:?}\n",
367 p.brightness, p.contrast, p.saturation, p.tint
368 )
369 .as_bytes(),
370 );
371 }
372 // Lane by lane rather than interleaved by time: a lane reads as a list, the
373 // parser gets its sortedness check for free from the order it is in, and
374 // the lanes come back out in the order they are displayed in.
375 let (mut video, mut audio) = (0, 0);
376 for (kind, clips) in lanes {
377 let (keyword, ord) = match kind {
378 LaneKind::Video => {
379 video += 1;
380 ("video", video)
381 }
382 LaneKind::Audio => {
383 audio += 1;
384 ("audio", audio)
385 }
386 };
387 // A lane is declared by its clips; one holding nothing has to say so on
388 // a line of its own, or the lane itself would not survive the round trip.
389 if clips.is_empty() {
390 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
391 }
392 for c in clips {
393 let link = c.link.map_or("-".to_string(), |l| l.to_string());
394 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
395 let color = c.color.map_or("-".to_string(), |e| e.to_string());
396 out.extend_from_slice(
397 format!(
398 "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {}\n",
399 c.start,
400 c.in_frame,
401 c.out_frame,
402 c.source,
403 fit_name(c.fit),
404 c.speed.permille()
405 )
406 .as_bytes(),
407 );
408 }
409 }
410 // After the lanes, not before them: a gain line names a lane that has to be
411 // there already, and a lane is declared by its own lines. Only the lanes
412 // somebody has turned get one.
413 let (mut video, mut audio) = (0, 0);
414 for ((kind, _), &db) in lanes.iter().zip(gains) {
415 let (keyword, ord) = match kind {
416 LaneKind::Video => {
417 video += 1;
418 ("video", video)
419 }
420 LaneKind::Audio => {
421 audio += 1;
422 ("audio", audio)
423 }
424 };
425 if db != 0.0 {
426 out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes());
427 }
428 }
429 out
430}
431
432fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
433 // One trailing newline is the line terminator of the last line, not an
434 // empty line -- any further one is, and is refused below.
435 let body = data.strip_suffix(b"\n").unwrap_or(data);
436 let mut lines = body.split(|&b| b == b'\n').enumerate();
437 let (_, first) = lines.next().unwrap_or((0, &[]));
438 let v1 = first == MAGIC_V1;
439 // The dialects that wrote a source line without its stream field. Reading
440 // one is the whole of what "an old project still opens" means here.
441 let streamless = v1 || first == MAGIC_V2;
442 // The one that carries an HDR rendition...
443 let v11 = first == MAGIC;
444 // ...the ones that carry subtitle tracks...
445 let v10 = v11 || first == MAGIC_V10;
446 // ...the ones that carry the mix -- lane volumes, the master limiter and
447 // the rate the timeline was cut at...
448 let v9 = v10 || first == MAGIC_V9;
449 // ...the ones that carry a per-clip speed...
450 let v8 = v9 || first == MAGIC_V8;
451 // ...the ones that carry a project resolution and per-clip fit policies...
452 let v7 = v8 || first == MAGIC_V7;
453 // ...the ones that carry colour grades...
454 let v6 = v7 || first == MAGIC_V6;
455 // ...the ones that carry equalizer settings...
456 let v5 = v6 || first == MAGIC_V5;
457 // ...and the ones that number their lanes. Every older one held two.
458 let numbered = v5 || first == MAGIC_V4;
459 if !numbered && !streamless && first != MAGIC_V3 {
460 return Err(match first.strip_prefix(b"edith ") {
461 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
462 None => "line 1: not a edith file".to_string(),
463 }
464 .into());
465 }
466
467 let mut doc = Document {
468 sources: Vec::new(),
469 // v4 on declares its lanes as they come; every dialect before it held
470 // exactly `V1` and `A1`, either of which could be empty.
471 lanes: if numbered {
472 Vec::new()
473 } else {
474 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
475 },
476 // Nothing before v5 equalizes anything, and nothing before v6 grades.
477 eq: Vec::new(),
478 color: Vec::new(),
479 // Nothing before v7 has a resolution of its own: source 0's picture is
480 // what those projects were, and `None` is how the loader is told so.
481 resolution: None,
482 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
483 // no limiter, and the rate inferred from the scaffold as it always was.
484 gains: Vec::new(),
485 // Nothing before v10 shows a subtitle, and nothing before v11 was shown
486 // in any rendition but the published one.
487 subtitles: Vec::new(),
488 limiter: Limiter::default(),
489 tone: crate::tonemap::Preset::default(),
490 fps: None,
491 playhead: 0,
492 };
493 let mut playhead_seen = false;
494 // Where the next v1 clip is placed: that dialect had no `start` field, the
495 // clips simply queued up.
496 let mut queued = 0u32;
497 for (i, line) in lines {
498 let n = i + 1;
499 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
500 Some(at) => (&line[..at], &line[at + 1..]),
501 None => (line, &line[line.len()..]),
502 };
503 match keyword {
504 b"playhead" => {
505 if playhead_seen || !doc.sources.is_empty() {
506 return Err(
507 format!("line {n}: playhead belongs once, before the sources").into(),
508 );
509 }
510 doc.playhead = number(rest, n)?;
511 playhead_seen = true;
512 }
513 b"resolution" if v7 => {
514 if doc.resolution.is_some() || !doc.sources.is_empty() {
515 return Err(
516 format!("line {n}: resolution belongs once, before the sources").into(),
517 );
518 }
519 let f = fields(rest, 2, "resolution", n)?;
520 let (width, height) = (number(f[0], n)?, number(f[1], n)?);
521 // The same bound the keystroke has (`crate::is_resolution`):
522 // unbounded here, this line reached `open_black` and panicked
523 // the open with a capacity overflow.
524 if !crate::is_resolution(width, height) {
525 return Err(format!("line {n}: {width}x{height} is not a picture").into());
526 }
527 doc.resolution = Some((width, height));
528 }
529 b"fps" if v9 => {
530 if doc.fps.is_some() || !doc.sources.is_empty() {
531 return Err(format!("line {n}: fps belongs once, before the sources").into());
532 }
533 let f = fields(rest, 1, "fps", n)?;
534 let fps = std::str::from_utf8(f[0])
535 .ok()
536 .and_then(|s| s.parse::<f64>().ok())
537 .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0)
538 .ok_or_else(|| {
539 format!(
540 "line {n}: {:?} is not a frame rate",
541 String::from_utf8_lossy(f[0])
542 )
543 })?;
544 doc.fps = Some(fps);
545 }
546 b"tonemap" if v11 => {
547 if !doc.sources.is_empty() {
548 return Err(
549 format!("line {n}: tonemap belongs once, before the sources").into(),
550 );
551 }
552 let f = fields(rest, 1, "tonemap", n)?;
553 doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| {
554 format!(
555 "line {n}: {:?} is not a tone map",
556 String::from_utf8_lossy(f[0])
557 )
558 })?;
559 }
560 b"limiter" if v9 => {
561 if !doc.sources.is_empty() {
562 return Err(
563 format!("line {n}: limiter belongs once, before the sources").into(),
564 );
565 }
566 let f = fields(rest, 2, "limiter", n)?;
567 let on = match f[1] {
568 b"on" => true,
569 b"off" => false,
570 other => {
571 return Err(format!(
572 "line {n}: limiter is on or off, not {:?}",
573 String::from_utf8_lossy(other)
574 )
575 .into());
576 }
577 };
578 // Through the same clamp a nudge goes through: a hand-written
579 // ceiling above full scale is a ceiling that limits nothing.
580 doc.limiter = Limiter {
581 on,
582 ..Limiter::default()
583 }
584 .with_ceiling(float(f[0], n)?);
585 }
586 // After the lanes it names, which is where `emit` writes it: a lane
587 // is declared by its own lines, and a gain declares nothing.
588 b"gain" if v9 => {
589 let f = fields(rest, 3, "gain", n)?;
590 let kind = match f[0] {
591 b"video" => LaneKind::Video,
592 b"audio" => LaneKind::Audio,
593 other => {
594 return Err(format!(
595 "line {n}: gain names {:?}, not a lane kind",
596 String::from_utf8_lossy(other)
597 )
598 .into());
599 }
600 };
601 let ord = number(f[1], n)?;
602 let at = doc
603 .lanes
604 .iter()
605 .enumerate()
606 .filter(|(_, (k, _))| *k == kind)
607 .nth(ord.saturating_sub(1) as usize)
608 .map(|(at, _)| at)
609 .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?;
610 doc.gains.resize(doc.lanes.len(), 0.0);
611 doc.gains[at] = float(f[2], n)?;
612 }
613 // Beside the source lines and read the same way: fields first, the
614 // path last, because a path runs to the end of the line.
615 b"subtitle" if v10 => {
616 let at = rest
617 .iter()
618 .position(|&b| b == b' ')
619 .ok_or_else(|| format!("line {n}: subtitle without a path"))?;
620 let track = match &rest[..at] {
621 b"-" => None,
622 field => Some(u64::from(number(field, n)?)),
623 };
624 let path = unescape(&rest[at + 1..], n)?;
625 if path.as_os_str().is_empty() {
626 return Err(format!("line {n}: subtitle without a path").into());
627 }
628 doc.subtitles.push((
629 // Relative to the project file, as a source path is.
630 if path.is_absolute() {
631 path
632 } else {
633 dir.join(path)
634 },
635 track,
636 ));
637 }
638 b"source" => {
639 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
640 return Err(format!("line {n}: source after a clip").into());
641 }
642 // The stream comes first and the path is everything after it,
643 // spaces and all; an older dialect wrote no stream and meant 0.
644 let (audio_stream, rest) = if streamless {
645 (0, rest)
646 } else {
647 // No space at all still has to reach `number`, so a v2 line
648 // in a v3 file is refused as the missing field it is rather
649 // than as a missing path.
650 let at = rest.iter().position(|&b| b == b' ');
651 (
652 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
653 &rest[at.map_or(rest.len(), |at| at + 1)..],
654 )
655 };
656 if rest.is_empty() {
657 return Err(format!("line {n}: source without a path").into());
658 }
659 let path = unescape(rest, n)?;
660 // Relative means "next to the project file", which is what
661 // makes a whole folder relocatable.
662 doc.sources.push(Source {
663 path: if path.is_absolute() {
664 path
665 } else {
666 dir.join(path)
667 },
668 audio_stream,
669 });
670 }
671 b"eq" if v5 => {
672 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
673 return Err(format!("line {n}: eq after a clip").into());
674 }
675 // A bare `eq` is the empty cascade -- a setting that moves
676 // nothing, which is not the same thing as no setting at all.
677 let bands = match rest.is_empty() {
678 true => Vec::new(),
679 false => rest
680 .split(|&b| b == b' ')
681 .map(|field| band(field, n))
682 .collect::<crate::Result<Vec<Band>>>()?,
683 };
684 doc.eq.push(EqParams { bands });
685 }
686 b"color" if v6 => {
687 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
688 return Err(format!("line {n}: color after a clip").into());
689 }
690 let f = fields(rest, 1, "color", n)?;
691 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
692 if parts.len() != 4 {
693 return Err(
694 format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
695 );
696 }
697 doc.color.push(ColorParams {
698 brightness: float(parts[0], n)?,
699 contrast: float(parts[1], n)?,
700 saturation: float(parts[2], n)?,
701 tint: float(parts[3], n)?,
702 });
703 }
704 // v1: one lane, no placement, no groups. Every clip becomes one
705 // grouped video+audio pair laid where the queue reached, which is
706 // what the file always meant.
707 b"clip" if v1 => {
708 let f = fields(rest, 3, "clip", n)?;
709 let clip = check(
710 Clip {
711 start: queued,
712 in_frame: number(f[0], n)?,
713 out_frame: number(f[1], n)?,
714 source: number(f[2], n)? as usize,
715 link: Some(doc.lanes[0].1.len() as u32),
716 eq: None,
717 color: None,
718 fit: FitPolicy::default(),
719 speed: Speed::NORMAL,
720 },
721 &doc,
722 n,
723 )?;
724 queued = clip.end();
725 doc.lanes[0].1.push(clip);
726 doc.lanes[1].1.push(clip);
727 }
728 b"video" | b"audio" if !v1 => {
729 let kind = match keyword {
730 b"video" => LaneKind::Video,
731 _ => LaneKind::Audio,
732 };
733 // v4 on names the lane, and a line naming nothing else is an
734 // empty lane's whole existence. Older dialects had one lane per
735 // kind.
736 let (ord, rest) = if numbered {
737 let at = rest.iter().position(|&b| b == b' ');
738 (
739 number(&rest[..at.unwrap_or(rest.len())], n)?,
740 &rest[at.map_or(rest.len(), |at| at + 1)..],
741 )
742 } else {
743 (1, rest)
744 };
745 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
746 if numbered && rest.is_empty() {
747 continue;
748 }
749 // v8 grew the speed field, v7 the fit one, v6 the colour one and
750 // v5 the eq one; every older dialect ends at the link.
751 let want =
752 5 + usize::from(v5) + usize::from(v6) + usize::from(v7) + usize::from(v8);
753 let f = fields(rest, want, "clip", n)?;
754 let clip = check(
755 Clip {
756 start: number(f[0], n)?,
757 in_frame: number(f[1], n)?,
758 out_frame: number(f[2], n)?,
759 source: number(f[3], n)? as usize,
760 link: match f[4] {
761 b"-" => None,
762 field => Some(number(field, n)?),
763 },
764 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
765 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
766 fit: fit_policy(f.get(7).copied(), n)?,
767 speed: speed_of(f.get(8).copied(), n)?,
768 },
769 &doc,
770 n,
771 )?;
772 let lane = &mut doc.lanes[at].1;
773 // The sorted, non-overlapping placement invariant, checked at
774 // the only door untrusted clips come in through.
775 if lane.last().is_some_and(|prev| prev.end() > clip.start) {
776 return Err(format!(
777 "line {n}: clip at {} overlaps the one before it, or comes before it",
778 clip.start
779 )
780 .into());
781 }
782 lane.push(clip);
783 }
784 // Empty lines land here too: nothing in this format is optional
785 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
786 // is a file mixing dialects, and is refused the same way.
787 _ => {
788 return Err(format!(
789 "line {n}: unknown keyword {:?}",
790 String::from_utf8_lossy(keyword)
791 )
792 .into());
793 }
794 }
795 }
796 // One per lane whatever the file said, so a caller may zip the two.
797 doc.gains.resize(doc.lanes.len(), 0.0);
798 // A file whose lanes are all empty *is* a project -- the emptied timeline,
799 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
800 // refuses that one, by the name it has there.
801 Ok(doc)
802}
803
804/// Where the lane a v4 line names sits, appending it if this is its first line.
805/// Lanes arrive in display order, so a number that skips one of its kind is a
806/// lane that was never declared, and is refused by the name it would have had.
807fn lane_of(
808 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
809 kind: LaneKind,
810 ord: u32,
811 line: usize,
812) -> crate::Result<usize> {
813 let mut seen = 0;
814 for (at, (k, _)) in lanes.iter().enumerate() {
815 if *k == kind {
816 seen += 1;
817 if seen == ord {
818 return Ok(at);
819 }
820 }
821 }
822 if ord != seen + 1 {
823 return Err(match ord.checked_sub(1) {
824 Some(prev) => format!(
825 "line {line}: lane {} comes before {}",
826 Lane::new(kind, prev as usize).label(),
827 Lane::new(kind, seen as usize).label()
828 ),
829 None => format!("line {line}: lane numbers start at 1"),
830 }
831 .into());
832 }
833 lanes.push((kind, Vec::new()));
834 Ok(lanes.len() - 1)
835}
836
837/// Splits a line's fields, refusing the wrong count by name.
838fn fields<'a>(
839 rest: &'a [u8],
840 want: usize,
841 what: &str,
842 line: usize,
843) -> crate::Result<Vec<&'a [u8]>> {
844 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
845 if fields.len() != want {
846 return Err(format!(
847 "line {line}: {what} wants {want} fields, found {}",
848 fields.len()
849 )
850 .into());
851 }
852 Ok(fields)
853}
854
855/// The per-clip structure checks both dialects share.
856fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
857 if clip.out_frame <= clip.in_frame {
858 return Err(format!(
859 "line {line}: clip [{}, {}) is empty",
860 clip.in_frame, clip.out_frame
861 )
862 .into());
863 }
864 if clip.source >= doc.sources.len() {
865 return Err(format!(
866 "line {line}: clip names source {} of {}",
867 clip.source,
868 doc.sources.len()
869 )
870 .into());
871 }
872 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
873 // adds `start + len` as plain `u32`, which panics in debug and wraps in
874 // release on a crafted file. Bound it here, at the door.
875 if clip.start.checked_add(clip.frames()).is_none() {
876 return Err(format!(
877 "line {line}: clip at {} runs past the last frame there is",
878 clip.start
879 )
880 .into());
881 }
882 Ok(clip)
883}
884
885/// A clip's `<speed>` field: thousandths of real time, as
886/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A
887/// dialect with no such field (everything before v8) means real time, which is
888/// what such a project always played at. A number outside the range the editor
889/// can set is *refused* rather than clamped: a project file is generated, so
890/// that is a corrupt line and not a dialect.
891fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result<Speed> {
892 let Some(field) = field else {
893 return Ok(Speed::NORMAL);
894 };
895 let permille = number(field, line)?;
896 let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16);
897 if u32::from(speed.permille()) != permille {
898 return Err(format!(
899 "line {line}: speed {permille} is outside {}-{} thousandths",
900 Speed::MIN.permille(),
901 Speed::MAX.permille()
902 )
903 .into());
904 }
905 Ok(speed)
906}
907
908/// How a fit policy is spelled in the file. One word each, so a clip line stays
909/// readable, and the same word the parser takes back.
910fn fit_name(fit: FitPolicy) -> &'static str {
911 match fit {
912 FitPolicy::Fit => "fit",
913 FitPolicy::Fill => "fill",
914 FitPolicy::Stretch => "stretch",
915 FitPolicy::Center => "center",
916 }
917}
918
919/// A clip's `<fit>` field. A dialect that has no such field at all means the
920/// default -- those projects held one resolution, so no clip of theirs was ever
921/// placed on anything.
922fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
923 let Some(field) = field else {
924 return Ok(FitPolicy::default());
925 };
926 match field {
927 b"fit" => Ok(FitPolicy::Fit),
928 b"fill" => Ok(FitPolicy::Fill),
929 b"stretch" => Ok(FitPolicy::Stretch),
930 b"center" => Ok(FitPolicy::Center),
931 other => Err(format!(
932 "line {line}: {:?} is not a fit policy",
933 String::from_utf8_lossy(other)
934 )
935 .into()),
936 }
937}
938
939/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
940/// at all), or a line of a table that is already declared. Refused by the name
941/// of what it points at, so the message reads as the file does.
942fn table_index(
943 field: Option<&[u8]>,
944 len: usize,
945 what: &str,
946 line: usize,
947) -> crate::Result<Option<u16>> {
948 let field = match field {
949 None | Some(b"-") => return Ok(None),
950 Some(field) => field,
951 };
952 let i = number(field, line)?;
953 if i as usize >= len || i > u32::from(u16::MAX) {
954 return Err(format!("line {line}: clip names {what} {i} of {len}").into());
955 }
956 Ok(Some(i as u16))
957}
958
959/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
960fn band(field: &[u8], line: usize) -> crate::Result<Band> {
961 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
962 if parts.len() != 4 {
963 return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
964 }
965 Ok(Band {
966 freq_hz: float(parts[0], line)?,
967 gain_db: float(parts[1], line)?,
968 q: float(parts[2], line)?,
969 kind: match parts[3] {
970 b"ls" => BandKind::LowShelf,
971 b"pk" => BandKind::Peak,
972 b"hs" => BandKind::HighShelf,
973 other => {
974 return Err(format!(
975 "line {line}: {:?} is not a band shape",
976 String::from_utf8_lossy(other)
977 )
978 .into());
979 }
980 },
981 })
982}
983
984/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
985/// and NaN are refused rather than carried -- they are the values a coefficient
986/// cannot be built from, and the ones that would not compare equal to
987/// themselves on the way back.
988fn float(field: &[u8], line: usize) -> crate::Result<f32> {
989 match std::str::from_utf8(field)
990 .ok()
991 .and_then(|s| s.parse::<f32>().ok())
992 .filter(|f| f.is_finite())
993 {
994 Some(f) => Ok(f),
995 None => Err(format!(
996 "line {line}: {:?} is not a number",
997 String::from_utf8_lossy(field)
998 )
999 .into()),
1000 }
1001}
1002
1003fn number(field: &[u8], line: usize) -> crate::Result<u32> {
1004 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
1005 Some(n) => Ok(n),
1006 None => Err(format!(
1007 "line {line}: {:?} is not a number",
1008 String::from_utf8_lossy(field)
1009 )
1010 .into()),
1011 }
1012}
1013
1014/// The two bytes a line-based format cannot hold, and the escape byte itself.
1015fn escape(path: &Path, out: &mut Vec<u8>) {
1016 for &b in path.as_os_str().as_bytes() {
1017 match b {
1018 b'%' => out.extend_from_slice(b"%25"),
1019 b'\n' => out.extend_from_slice(b"%0A"),
1020 _ => out.push(b),
1021 }
1022 }
1023}
1024
1025/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
1026/// may spell a space or a quote that way, and there is no reason to refuse it.
1027fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
1028 let mut out = Vec::with_capacity(field.len());
1029 let mut i = 0;
1030 while i < field.len() {
1031 if field[i] != b'%' {
1032 out.push(field[i]);
1033 i += 1;
1034 continue;
1035 }
1036 let byte = field
1037 .get(i + 1..i + 3)
1038 .and_then(|h| std::str::from_utf8(h).ok())
1039 .and_then(|h| u8::from_str_radix(h, 16).ok())
1040 .ok_or_else(|| -> crate::Error {
1041 format!("line {line}: truncated % escape in the path").into()
1042 })?;
1043 out.push(byte);
1044 i += 3;
1045 }
1046 Ok(PathBuf::from(OsString::from_vec(out)))
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051 use super::*;
1052
1053 /// [`super::emit`] for a project whose mix is flat: every lane at unity, no
1054 /// limiter, no rate written. Shadows the real one for the tests that were
1055 /// written before there was a mix to write -- the dialect they are about is
1056 /// the one this emits, and a v9 file with flat settings is a v8 file bar
1057 /// its version line, which is exactly what they assert.
1058 #[allow(clippy::too_many_arguments)]
1059 fn emit(
1060 dir: &Path,
1061 sources: &[Source],
1062 lanes: &[(LaneKind, Vec<Clip>)],
1063 eq: &[EqParams],
1064 color: &[ColorParams],
1065 resolution: (u32, u32),
1066 playhead: u32,
1067 ) -> Vec<u8> {
1068 super::emit(
1069 dir,
1070 sources,
1071 lanes,
1072 &[],
1073 &[],
1074 eq,
1075 color,
1076 resolution,
1077 None,
1078 crate::tonemap::Preset::default(),
1079 Limiter::default(),
1080 playhead,
1081 )
1082 }
1083
1084 /// A subtitle track as a save hands one over: the cues are not written and
1085 /// so are not here either.
1086 fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack {
1087 SubtitleTrack {
1088 path: PathBuf::from(path),
1089 track,
1090 label: String::new(),
1091 cues: Vec::new(),
1092 bitmap: false,
1093 refused: None,
1094 }
1095 }
1096
1097 /// The v10 line: which track of which file, written beside the sources and
1098 /// read back as the pair a load opens. And what a v9 file is -- one with no
1099 /// subtitles at all, which still opens and re-saves as v10.
1100 #[test]
1101 fn subtitles_round_trip_as_references_and_a_v9_file_has_none() {
1102 let dir = PathBuf::from("/proj");
1103 let (_, sources, lanes) = doc();
1104 let tracks = [
1105 subtitle("/proj/subs.srt", None),
1106 subtitle("/proj/a.mp4", Some(3)),
1107 subtitle("/elsewhere/od d name.ass", None),
1108 ];
1109 let bytes = super::emit(
1110 &dir,
1111 &sources,
1112 &lanes,
1113 &[],
1114 &tracks,
1115 &[],
1116 &[],
1117 (1280, 720),
1118 None,
1119 crate::tonemap::Preset::default(),
1120 Limiter::default(),
1121 0,
1122 );
1123 let text = String::from_utf8_lossy(&bytes);
1124 assert!(
1125 text.contains(
1126 "subtitle - subs.srt\n\
1127 subtitle 3 a.mp4\n\
1128 subtitle - /elsewhere/od d name.ass\n"
1129 ),
1130 "the path is relative where it can be, and runs to the end of its \
1131 line, spaces and all: {text}"
1132 );
1133 let back = parse(&bytes, &dir).expect("v10 parses");
1134 assert_eq!(
1135 back.subtitles,
1136 vec![
1137 (PathBuf::from("/proj/subs.srt"), None),
1138 (PathBuf::from("/proj/a.mp4"), Some(3)),
1139 (PathBuf::from("/elsewhere/od d name.ass"), None),
1140 ]
1141 );
1142
1143 // A v9 file is a project with no subtitles, and re-saving it writes v10.
1144 let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1145 video 1 0 0 30 0 - - - fit 1000\n";
1146 let old = parse(v9, &dir).expect("v9 still loads");
1147 assert_eq!(old.subtitles, Vec::new());
1148 assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 11\n"));
1149 // ...and the line itself is not a v9 line: a dialect may not be mixed.
1150 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
1151 .unwrap_err()
1152 .to_string();
1153 assert_eq!(mixed, "line 3: unknown keyword \"subtitle\"");
1154 // A subtitle line with no path is refused, as a source with none is.
1155 for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] {
1156 let file = format!("edith 10\nsource 0 a.mp4\n{line}");
1157 assert!(
1158 parse(file.as_bytes(), &dir).is_err(),
1159 "{line:?} is not a subtitle line"
1160 );
1161 }
1162 }
1163
1164 /// The v11 line: the HDR rendition, written by name, read back as the very
1165 /// preset -- and the dialect before it, which had no way to say one and
1166 /// meant the published conversion.
1167 #[test]
1168 fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
1169 let dir = PathBuf::from("/proj");
1170 let (_, sources, lanes) = doc();
1171 for preset in crate::tonemap::Preset::ALL {
1172 let bytes = super::emit(
1173 &dir,
1174 &sources,
1175 &lanes,
1176 &[],
1177 &[],
1178 &[],
1179 &[],
1180 (1280, 720),
1181 None,
1182 preset,
1183 Limiter::default(),
1184 0,
1185 );
1186 let text = String::from_utf8_lossy(&bytes).to_string();
1187 assert_eq!(
1188 text.contains(&format!("tonemap {}\n", preset.name())),
1189 preset != crate::tonemap::Preset::default(),
1190 "the default is the line left out: {text}"
1191 );
1192 assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
1193 }
1194
1195 // A v10 file is a project shown the published way, and re-saving it
1196 // writes v11 with nothing more in it.
1197 let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1198 video 1 0 0 30 0 - - - fit 1000\n";
1199 let old = parse(v10, &dir).expect("v10 still loads");
1200 assert_eq!(old.tone, crate::tonemap::Preset::Reference);
1201 // ...and the line itself is not a v10 line: a dialect may not be mixed.
1202 let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
1203 .unwrap_err()
1204 .to_string();
1205 assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
1206 // A rendition nobody wrote is a corrupt line, by name -- not a silent
1207 // fall back to another picture.
1208 for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
1209 let file = format!("edith 11\nsource 0 a.mp4\n{line}");
1210 assert!(
1211 parse(file.as_bytes(), &dir).is_err(),
1212 "{line:?} is not a tonemap line"
1213 );
1214 }
1215 }
1216
1217 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
1218 Clip {
1219 start,
1220 in_frame,
1221 out_frame,
1222 source,
1223 link,
1224 eq: None,
1225 color: None,
1226 fit: FitPolicy::default(),
1227 speed: Speed::NORMAL,
1228 }
1229 }
1230
1231 /// [`emit`] for a timeline that equalizes nothing, which is every case that
1232 /// predates the eq lines.
1233 fn flat(
1234 dir: &Path,
1235 sources: &[Source],
1236 lanes: &[(LaneKind, Vec<Clip>)],
1237 playhead: u32,
1238 ) -> Vec<u8> {
1239 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
1240 }
1241
1242 /// Two sources, one under the project's own directory and one not, a clip
1243 /// from each on the video lane, and an audio lane with a gap in the middle
1244 /// -- the shape every case below starts from.
1245 fn source(path: &str, audio_stream: usize) -> Source {
1246 Source {
1247 path: PathBuf::from(path),
1248 audio_stream,
1249 }
1250 }
1251
1252 /// Lanes in display order, as [`Document::lanes`] holds them.
1253 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
1254
1255 /// `V1` then `A1`, the shape every dialect before v4 held.
1256 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
1257 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
1258 }
1259
1260 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
1261 (
1262 PathBuf::from("/proj"),
1263 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
1264 two(
1265 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
1266 vec![clip(0, 0, 30, 0, Some(0))],
1267 ),
1268 )
1269 }
1270
1271 #[test]
1272 fn relative_and_absolute_paths_round_trip() {
1273 let (dir, sources, lanes) = doc();
1274 let bytes = flat(&dir, &sources, &lanes, 12);
1275 assert_eq!(
1276 String::from_utf8_lossy(&bytes),
1277 "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1278 source 2 /elsewhere/b.mp4\n\
1279 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1280 audio 1 0 0 30 0 0 - - fit 1000\n",
1281 "the file under the project directory is written relative to it, \
1282 each with the audio stream it plays"
1283 );
1284 let back = parse(&bytes, &dir).expect("parse");
1285 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
1286 assert_eq!(
1287 back.lanes, lanes,
1288 "both lanes, in display order; the trailing gap needs no line"
1289 );
1290 assert_eq!(back.playhead, 12);
1291 // ...and emitting the parsed document reproduces the same bytes.
1292 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
1293 }
1294
1295 /// The whole of the bump: a project of any number of lanes writes and reads
1296 /// back, in display order, empty lanes and cross-lane groups included.
1297 #[test]
1298 fn any_number_of_lanes_round_trips() {
1299 let dir = PathBuf::from("/proj");
1300 let sources = vec![source("/proj/a.mp4", 0)];
1301 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
1302 // shows, not video-then-audio -- with one take grouped across V1 and A2
1303 // (no paired ord, the lanes between them empty of it) and an A1 holding
1304 // nothing at all.
1305 let lanes = vec![
1306 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
1307 (LaneKind::Audio, Vec::new()),
1308 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
1309 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
1310 ];
1311 let bytes = flat(&dir, &sources, &lanes, 7);
1312 assert_eq!(
1313 String::from_utf8_lossy(&bytes),
1314 "edith 11\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
1315 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
1316 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
1317 "an empty lane is a line of its own; everything else is its clips"
1318 );
1319 let back = parse(&bytes, &dir).expect("parse");
1320 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
1321 assert_eq!(back.playhead, 7);
1322 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
1323
1324 // A lane number may not skip one of its kind: that lane was declared by
1325 // nothing, and the refusal names it.
1326 for (file, want) in [
1327 (
1328 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
1329 "line 3: lane V2 comes before V1",
1330 ),
1331 (
1332 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
1333 "line 4: lane A3 comes before A1",
1334 ),
1335 (
1336 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
1337 "line 3: lane numbers start at 1",
1338 ),
1339 // The clip fields are still the clip fields, one lane number on.
1340 (
1341 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
1342 "line 3: clip wants 5 fields, found 4",
1343 ),
1344 // ...and a v4 line in a v3 file reads as the garbled clip it is.
1345 (
1346 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
1347 "line 3: clip wants 5 fields, found 6",
1348 ),
1349 ] {
1350 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1351 }
1352 // Lanes and nothing on them is the emptied timeline, saved: a project.
1353 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
1354 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
1355 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
1356 }
1357
1358 /// One band, spelled the way an eq line spells it.
1359 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
1360 Band {
1361 freq_hz,
1362 gain_db,
1363 q,
1364 kind,
1365 }
1366 }
1367
1368 /// The whole of the v5 bump: the clips name a shared equalizer table, the
1369 /// bytes are the ones documented at the top of this file, and every f32 in
1370 /// them comes back *bit* for bit -- which is what makes a re-save of a
1371 /// loaded project produce the same file rather than a drifting one.
1372 #[test]
1373 fn equalizers_round_trip_bit_exactly_and_are_shared() {
1374 let dir = PathBuf::from("/proj");
1375 let sources = vec![source("/proj/a.mp4", 0)];
1376 let eq = vec![
1377 EqParams {
1378 bands: vec![
1379 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
1380 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
1381 ],
1382 },
1383 // The awkward ones: a value needing all 24 mantissa bits, one whose
1384 // shortest spelling is exponential, a subnormal, and a negative
1385 // zero -- plus the empty cascade, which is a setting like any other.
1386 EqParams {
1387 bands: vec![band_of(
1388 16_777_215.0,
1389 -0.1,
1390 f32::MIN_POSITIVE / 3.0,
1391 BandKind::HighShelf,
1392 )],
1393 },
1394 EqParams { bands: Vec::new() },
1395 ];
1396 // Two clips share entry 0, so it is written once; one clip plays flat.
1397 let lanes = two(
1398 vec![
1399 Clip {
1400 eq: Some(0),
1401 ..clip(0, 0, 30, 0, Some(0))
1402 },
1403 Clip {
1404 eq: Some(1),
1405 ..clip(30, 10, 20, 0, None)
1406 },
1407 ],
1408 vec![
1409 Clip {
1410 eq: Some(0),
1411 ..clip(0, 0, 30, 0, Some(0))
1412 },
1413 Clip {
1414 eq: Some(2),
1415 ..clip(30, 0, 10, 0, None)
1416 },
1417 ],
1418 );
1419 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
1420 assert_eq!(
1421 String::from_utf8_lossy(&bytes),
1422 "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1423 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
1424 eq 16777215.0:-0.1:3.918315e-39:hs\n\
1425 eq\n\
1426 video 1 0 0 30 0 0 0 - fit 1000\nvideo 1 30 10 20 0 - 1 - fit 1000\n\
1427 audio 1 0 0 30 0 0 0 - fit 1000\naudio 1 30 0 10 0 - 2 - fit 1000\n",
1428 "the table comes before the clips, and a clip names a line of it"
1429 );
1430
1431 let back = parse(&bytes, &dir).expect("parse");
1432 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
1433 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
1434 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
1435 assert_eq!(
1436 (
1437 got.freq_hz.to_bits(),
1438 got.gain_db.to_bits(),
1439 got.q.to_bits(),
1440 got.kind
1441 ),
1442 (
1443 want.freq_hz.to_bits(),
1444 want.gain_db.to_bits(),
1445 want.q.to_bits(),
1446 want.kind
1447 ),
1448 "eq {i} band {b} came back as other bits"
1449 );
1450 }
1451 }
1452 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
1453 assert_eq!(
1454 emit(
1455 &dir,
1456 &back.sources,
1457 &back.lanes,
1458 &back.eq,
1459 &back.color,
1460 (1280, 720),
1461 0
1462 ),
1463 bytes
1464 );
1465 }
1466
1467 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
1468 /// colour table, the bytes are the ones documented at the top of this file,
1469 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
1470 #[test]
1471 fn colours_round_trip_bit_exactly_and_are_shared() {
1472 let dir = PathBuf::from("/proj");
1473 let sources = vec![source("/proj/a.mp4", 0)];
1474 let color = vec![
1475 ColorParams {
1476 brightness: 0.1,
1477 contrast: 1.2,
1478 saturation: 0.9,
1479 tint: -0.3,
1480 },
1481 // The awkward ones again: all 24 mantissa bits, an exponential
1482 // spelling, a subnormal and a negative zero -- and the identity,
1483 // which is a setting like any other.
1484 ColorParams {
1485 brightness: -0.000_000_1,
1486 contrast: 16_777_215.0,
1487 saturation: f32::MIN_POSITIVE / 3.0,
1488 tint: -0.0,
1489 },
1490 ColorParams::default(),
1491 ];
1492 // Two clips share entry 0, so it is written once; one clip is ungraded.
1493 let lanes = two(
1494 vec![
1495 Clip {
1496 color: Some(0),
1497 fit: FitPolicy::default(),
1498 speed: Speed::NORMAL,
1499 ..clip(0, 0, 30, 0, Some(0))
1500 },
1501 Clip {
1502 color: Some(1),
1503 fit: FitPolicy::default(),
1504 speed: Speed::NORMAL,
1505 ..clip(30, 10, 20, 0, None)
1506 },
1507 ],
1508 vec![
1509 Clip {
1510 color: Some(0),
1511 fit: FitPolicy::default(),
1512 speed: Speed::NORMAL,
1513 ..clip(0, 0, 30, 0, Some(0))
1514 },
1515 Clip {
1516 color: Some(2),
1517 fit: FitPolicy::default(),
1518 speed: Speed::NORMAL,
1519 ..clip(30, 0, 10, 0, None)
1520 },
1521 ],
1522 );
1523 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1524 assert_eq!(
1525 String::from_utf8_lossy(&bytes),
1526 "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1527 color 0.1:1.2:0.9:-0.3\n\
1528 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1529 color 0.0:1.0:1.0:0.0\n\
1530 video 1 0 0 30 0 0 - 0 fit 1000\nvideo 1 30 10 20 0 - - 1 fit 1000\n\
1531 audio 1 0 0 30 0 0 - 0 fit 1000\naudio 1 30 0 10 0 - - 2 fit 1000\n",
1532 "the table comes before the clips, and a clip names a line of it"
1533 );
1534
1535 let back = parse(&bytes, &dir).expect("parse");
1536 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
1537 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
1538 assert_eq!(
1539 (
1540 got.brightness.to_bits(),
1541 got.contrast.to_bits(),
1542 got.saturation.to_bits(),
1543 got.tint.to_bits()
1544 ),
1545 (
1546 want.brightness.to_bits(),
1547 want.contrast.to_bits(),
1548 want.saturation.to_bits(),
1549 want.tint.to_bits()
1550 ),
1551 "color {i} came back as other bits"
1552 );
1553 }
1554 assert_eq!(back.color.len(), 3);
1555 assert_eq!(
1556 emit(
1557 &dir,
1558 &back.sources,
1559 &back.lanes,
1560 &back.eq,
1561 &back.color,
1562 (1280, 720),
1563 0
1564 ),
1565 bytes
1566 );
1567 }
1568
1569 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
1570 /// intact, and re-saving it writes the new magic and a `-` colour field.
1571 #[test]
1572 fn a_v5_file_grades_nothing() {
1573 let dir = PathBuf::from("/proj");
1574 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
1575 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
1576 let old = parse(v5, &dir).expect("v5 parses");
1577 assert!(old.color.is_empty(), "nothing before v6 grades anything");
1578 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
1579 assert_eq!(old.lanes[0].1[0].eq, Some(0));
1580 assert!(old.lanes[0].1[0].color.is_none());
1581 assert_eq!(
1582 String::from_utf8_lossy(&emit(
1583 &dir,
1584 &old.sources,
1585 &old.lanes,
1586 &old.eq,
1587 &old.color,
1588 (1280, 720),
1589 old.playhead
1590 )),
1591 "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1592 eq 80.0:-3.0:0.707:ls\n\
1593 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1594 );
1595 }
1596
1597 /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
1598 /// written on its own line, comes back as the very number that was set, and
1599 /// a v7 file -- which has no such field -- loads at real time and re-saves
1600 /// saying so.
1601 #[test]
1602 fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
1603 let dir = PathBuf::from("/proj");
1604 let sources = vec![Source::new("/proj/a.mp4", 0)];
1605 let speeded = |start, in_frame, out_frame, permille| Clip {
1606 start,
1607 in_frame,
1608 out_frame,
1609 source: 0,
1610 link: None,
1611 eq: None,
1612 color: None,
1613 fit: FitPolicy::default(),
1614 speed: Speed::from_permille(permille),
1615 };
1616 // 30 source frames at 2x is 15 timeline frames, which is where the
1617 // second clip starts -- the file writes the source range and the rate,
1618 // and the length on the timeline is derived from the two.
1619 let lanes = vec![
1620 (
1621 LaneKind::Video,
1622 vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
1623 ),
1624 (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
1625 ];
1626 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
1627 assert_eq!(
1628 String::from_utf8_lossy(&bytes),
1629 "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1630 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
1631 audio 1 0 0 30 0 - - - fit 2000\n",
1632 "the rate is the clip line's last field, in thousandths"
1633 );
1634 let back = parse(&bytes, &dir).expect("parse");
1635 assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
1636
1637 // ...and the dialect before it, which had no rate to name.
1638 let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1639 video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
1640 let old = parse(v7, &dir).expect("v7 parses");
1641 assert!(
1642 old.lanes
1643 .iter()
1644 .flat_map(|(_, clips)| clips)
1645 .all(|c| c.speed == Speed::NORMAL),
1646 "nothing before v8 plays at anything but real time"
1647 );
1648 assert_eq!(
1649 String::from_utf8_lossy(&emit(
1650 &dir,
1651 &old.sources,
1652 &old.lanes,
1653 &old.eq,
1654 &old.color,
1655 (1280, 720),
1656 old.playhead
1657 )),
1658 "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1659 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1660 );
1661 // A rate outside what the editor can set is a corrupt line, by name.
1662 let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
1663 assert_eq!(
1664 parse(bad, &dir).unwrap_err().to_string(),
1665 "line 3: speed 9000 is outside 250-4000 thousandths"
1666 );
1667 }
1668
1669 /// The whole of the v9 bump, the speed test's twin: the mix a project was
1670 /// left at -- every track's own volume and the master limiter -- plus the
1671 /// rate it was cut at, all written, all read back as the very numbers, and
1672 /// a v8 file (which has none of them) loading flat and unlimited.
1673 #[test]
1674 fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
1675 let dir = PathBuf::from("/proj");
1676 let sources = vec![Source::new("/proj/a.mp4", 0)];
1677 let lanes = vec![
1678 (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
1679 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
1680 // A second audio track, turned down: the gain lines are per lane,
1681 // so the two must not run into one another.
1682 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
1683 ];
1684 let limiter = Limiter {
1685 ceiling_db: -1.5,
1686 on: true,
1687 };
1688 let bytes = super::emit(
1689 &dir,
1690 &sources,
1691 &lanes,
1692 &[0.0, 3.0, -6.5],
1693 &[],
1694 &[],
1695 &[],
1696 (1280, 720),
1697 Some(23.976023976023978),
1698 crate::tonemap::Preset::default(),
1699 limiter,
1700 0,
1701 );
1702 assert_eq!(
1703 String::from_utf8_lossy(&bytes),
1704 "edith 11\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
1705 limiter -1.5 on\nsource 0 a.mp4\n\
1706 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
1707 audio 2 0 0 30 0 - - - fit 1000\n\
1708 gain audio 1 3.0\ngain audio 2 -6.5\n",
1709 "the mix is lines of its own, the gains after the lanes they name"
1710 );
1711 let back = parse(&bytes, &dir).expect("parse");
1712 assert_eq!(back.lanes, lanes);
1713 assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
1714 assert_eq!(back.limiter, limiter);
1715 assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
1716
1717 // ...and the dialect before it, which carried none of the three: a v8
1718 // file mixes flat, limits nothing, and says nothing about its rate.
1719 let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1720 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
1721 let old = parse(v8, &dir).expect("v8 parses");
1722 assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
1723 assert_eq!(old.limiter, Limiter::default());
1724 assert_eq!(old.fps, None);
1725 // A v9 file may leave all three out too, and means the same thing.
1726 assert_eq!(
1727 String::from_utf8_lossy(&emit(
1728 &dir,
1729 &old.sources,
1730 &old.lanes,
1731 &old.eq,
1732 &old.color,
1733 (1280, 720),
1734 old.playhead
1735 )),
1736 "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1737 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1738 );
1739
1740 // Each of the three refuses by name, on its own line.
1741 for (text, want) in [
1742 (
1743 "edith 9\nfps nope\nsource 0 a.mp4\n",
1744 "line 2: \"nope\" is not a frame rate",
1745 ),
1746 (
1747 "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
1748 "line 2: limiter is on or off, not \"maybe\"",
1749 ),
1750 (
1751 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
1752 "line 4: gain names a lane that is not there",
1753 ),
1754 (
1755 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
1756 "line 4: gain names \"lane\", not a lane kind",
1757 ),
1758 ] {
1759 assert_eq!(
1760 parse(text.as_bytes(), &dir).unwrap_err().to_string(),
1761 want,
1762 "{text:?}"
1763 );
1764 }
1765 // A hand-written ceiling nothing could limit at is clamped, not taken.
1766 let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
1767 assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
1768 }
1769
1770 /// The refusals the colour grammar adds, each naming its line.
1771 #[test]
1772 fn a_malformed_colour_names_its_line() {
1773 let dir = PathBuf::from("/proj");
1774 let head = "edith 6\nsource 0 a.mp4\n";
1775 // v6, deliberately: the colour grammar is the same one v7 inherits, and
1776 // a v6 clip line is one field shorter.
1777 for (file, want) in [
1778 (
1779 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
1780 "line 3: color wants 4 fields, found 3",
1781 ),
1782 (
1783 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"),
1784 "line 3: color wants 1 fields, found 2",
1785 ),
1786 (
1787 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1788 "line 3: \"warm\" is not a number",
1789 ),
1790 // The two values the format cannot write and read back as itself.
1791 (
1792 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1793 "line 3: \"inf\" is not a number",
1794 ),
1795 (
1796 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
1797 "line 3: \"NaN\" is not a number",
1798 ),
1799 (
1800 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
1801 "line 4: clip names color 1 of 1",
1802 ),
1803 (
1804 format!("{head}video 1 0 0 5 0 - - 0\n"),
1805 "line 3: clip names color 0 of 0",
1806 ),
1807 // A clip's colour field is not optional in v6, and the table has to
1808 // be declared before the clip that names it.
1809 (
1810 format!("{head}video 1 0 0 5 0 - -\n"),
1811 "line 3: clip wants 7 fields, found 6",
1812 ),
1813 (
1814 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
1815 "line 4: color after a clip",
1816 ),
1817 // ...and a colour line in a file that predates them is a corrupt one.
1818 (
1819 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
1820 "line 3: unknown keyword \"color\"",
1821 ),
1822 ] {
1823 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1824 }
1825 }
1826
1827 /// The refusals the eq grammar adds, each naming its line.
1828 #[test]
1829 fn a_malformed_equalizer_names_its_line() {
1830 let dir = PathBuf::from("/proj");
1831 let head = "edith 5\nsource 0 a.mp4\n";
1832 for (file, want) in [
1833 (
1834 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
1835 "line 3: band wants 4 fields, found 3",
1836 ),
1837 (
1838 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
1839 "line 3: \"notch\" is not a band shape",
1840 ),
1841 (
1842 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
1843 "line 3: \"wide\" is not a number",
1844 ),
1845 // Neither of the two values a coefficient cannot be built from, and
1846 // NaN would not even compare equal to itself on the way back.
1847 (
1848 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1849 "line 3: \"inf\" is not a number",
1850 ),
1851 (
1852 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1853 "line 3: \"NaN\" is not a number",
1854 ),
1855 (
1856 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
1857 "line 4: clip names eq 1 of 1",
1858 ),
1859 (
1860 format!("{head}video 1 0 0 5 0 - 0\n"),
1861 "line 3: clip names eq 0 of 0",
1862 ),
1863 // A clip's eq field is not optional in v5, and the table has to be
1864 // declared before the clip that names it.
1865 (
1866 format!("{head}video 1 0 0 5 0 -\n"),
1867 "line 3: clip wants 6 fields, found 5",
1868 ),
1869 (
1870 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
1871 "line 4: eq after a clip",
1872 ),
1873 // ...and an eq line in a file that predates them is a corrupt file.
1874 (
1875 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
1876 "line 3: unknown keyword \"eq\"",
1877 ),
1878 ] {
1879 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1880 }
1881 }
1882
1883 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
1884 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
1885 /// and not one byte else.
1886 #[test]
1887 fn a_v4_file_equalizes_nothing() {
1888 let dir = PathBuf::from("/proj");
1889 let (_, sources, lanes) = doc();
1890 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1891 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
1892 let old = parse(v4, &dir).expect("v4 parses");
1893 assert_eq!(
1894 (&old.sources, &old.lanes, old.playhead),
1895 (&sources, &lanes, 12)
1896 );
1897 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1898 assert_eq!(
1899 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1900 "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1901 source 2 /elsewhere/b.mp4\n\
1902 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1903 audio 1 0 0 30 0 0 - - fit 1000\n"
1904 );
1905 // An empty lane's line is still the whole of that lane, eq or no eq.
1906 let empty = parse(
1907 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
1908 &dir,
1909 )
1910 .expect("parse");
1911 assert!(empty.lanes[1].1.is_empty());
1912 }
1913
1914 /// The other half of the compatibility promise: a v3 file is a v4 one
1915 /// without the lane numbers, and a v2 file names no audio stream and means
1916 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
1917 /// they always were, and saving either writes v5 with nothing else changed.
1918 #[test]
1919 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
1920 let dir = PathBuf::from("/proj");
1921 let (_, _, lanes) = doc();
1922 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1923 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1924 let old = parse(v3, &dir).expect("v3 parses");
1925 assert_eq!(
1926 (&old.sources, &old.lanes, old.playhead),
1927 (
1928 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
1929 &lanes,
1930 12
1931 ),
1932 "a v3 file loads as exactly the state its v5 twin does"
1933 );
1934 // ...and re-saved it *is* that twin: the magic and a lane number per
1935 // clip line, and not one byte else.
1936 assert_eq!(
1937 flat(&dir, &old.sources, &old.lanes, old.playhead),
1938 flat(&dir, &old.sources, &lanes, 12),
1939 );
1940
1941 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
1942 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1943 let back = parse(v2, &dir).expect("v2 parses");
1944 assert_eq!(
1945 back.sources,
1946 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
1947 );
1948 assert_eq!(back.lanes, lanes);
1949
1950 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1951 assert_eq!(
1952 String::from_utf8_lossy(&v5),
1953 "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1954 source 0 /elsewhere/b.mp4\n\
1955 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1956 audio 1 0 0 30 0 0 - - fit 1000\n",
1957 "a re-saved v2 project differs only by its version, the lane \
1958 numbers, the streams it always meant and an equalizer it has none of"
1959 );
1960 let again = parse(&v5, &dir).expect("v5 parses");
1961 assert_eq!(again.sources, back.sources);
1962 }
1963
1964 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
1965 /// lanes, and saving it again writes v5.
1966 #[test]
1967 fn a_v1_file_loads_as_two_grouped_lanes() {
1968 let dir = PathBuf::from("/proj");
1969 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
1970 let back = parse(v1, &dir).expect("v1 parses");
1971 assert_eq!(
1972 back.lanes[0].1,
1973 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
1974 "v1 clips queue up: the second starts where the first ended"
1975 );
1976 assert_eq!(
1977 back.lanes,
1978 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
1979 "one take per clip, on both lanes"
1980 );
1981 assert_eq!(back.playhead, 5);
1982 // Saved again it is the current version, which round-trips to the
1983 // same document.
1984 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1985 assert!(v5.starts_with(b"edith 11\n"));
1986 let again = parse(&v5, &dir).expect("v5 parses");
1987 assert_eq!(again.lanes, back.lanes);
1988 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
1989 for (bytes, want) in [
1990 (
1991 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
1992 "line 3: unknown keyword \"video\"",
1993 ),
1994 (
1995 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
1996 "line 3: unknown keyword \"clip\"",
1997 ),
1998 ] {
1999 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
2000 }
2001 }
2002
2003 /// A gap is the absence of a line, so a lane's placements must arrive in
2004 /// order and never overlap -- the invariant the whole model rests on.
2005 #[test]
2006 fn a_lane_out_of_order_or_overlapping_is_refused() {
2007 let dir = PathBuf::from("/proj");
2008 for bytes in [
2009 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
2010 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
2011 ] {
2012 let err = parse(bytes, &dir).unwrap_err().to_string();
2013 assert!(err.starts_with("line 4: clip at "), "{err}");
2014 }
2015 // The lanes are independent, so a video line never crowds an audio one.
2016 assert!(
2017 parse(
2018 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
2019 &dir
2020 )
2021 .is_ok()
2022 );
2023 // ...and a lane may be empty as long as the other one is not.
2024 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
2025 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
2026 }
2027
2028 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
2029 /// and wrap in release, and a wrapped end passes the overlap check --
2030 /// crafted numbers must be refused by name, in both dialects.
2031 #[test]
2032 fn a_clip_whose_end_overflows_is_refused() {
2033 let dir = PathBuf::from("/proj");
2034 for bytes in [
2035 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
2036 // Two of them: the second would land *before* the first once wrapped.
2037 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
2038 // v1 has no `start` field, but its queue reaches the same ceiling.
2039 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
2040 ] {
2041 let err = parse(bytes, &dir).unwrap_err().to_string();
2042 assert!(
2043 err.contains("runs past the last frame there is"),
2044 "not refused by name: {err}"
2045 );
2046 }
2047 }
2048
2049 /// The relocatability promise, from the two directions a project path
2050 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
2051 /// clip.mp4`, whose parent is `""`) and a directory reached through a
2052 /// symlink. Both used to emit absolute source lines.
2053 #[test]
2054 fn a_non_canonical_project_path_still_writes_relative_sources() {
2055 assert_eq!(
2056 project_dir(Path::new("a.edith")),
2057 std::env::current_dir().expect("cwd"),
2058 "a bare filename is saved into the working directory"
2059 );
2060
2061 let dir = crate::scratch::Scratch::dir("ve_edith_link");
2062 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
2063 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
2064 let source = dir.join("real/a.mp4");
2065 let path = dir.join("link/p.edith");
2066
2067 let one = [clip(0, 0, 30, 0, None)];
2068 let entry = Source {
2069 path: source,
2070 audio_stream: 1,
2071 };
2072 save(
2073 &path,
2074 &[entry],
2075 &two(one.to_vec(), one.to_vec()),
2076 &[],
2077 &[],
2078 &[],
2079 &[],
2080 (1280, 720),
2081 None,
2082 crate::tonemap::Preset::default(),
2083 Limiter::default(),
2084 0,
2085 )
2086 .expect("save");
2087 let bytes = std::fs::read(&path).expect("read back");
2088 assert_eq!(
2089 String::from_utf8_lossy(&bytes),
2090 "edith 11\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
2091 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
2092 );
2093 // Loading rejoins the *given* directory, so the file is reached by the
2094 // way the project was opened -- the same file, through the link, still
2095 // playing the stream it was saved on.
2096 assert_eq!(
2097 load(&path).expect("load").sources,
2098 vec![Source {
2099 path: dir.join("link/a.mp4"),
2100 audio_stream: 1,
2101 }]
2102 );
2103 std::fs::remove_dir_all(&dir).expect("cleanup");
2104 }
2105
2106 #[test]
2107 fn escapes_survive_the_bytes_json_would_not() {
2108 let dir = PathBuf::from("/proj");
2109 // A newline and a percent in a filename, plus a non-UTF-8 byte.
2110 let nasty = Source {
2111 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
2112 audio_stream: 0,
2113 };
2114 let bytes = flat(
2115 &dir,
2116 &[nasty.clone()],
2117 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
2118 0,
2119 );
2120 assert_eq!(
2121 bytes.iter().filter(|&&b| b == b'\n').count(),
2122 6,
2123 "the escaped newline must not become a line break: magic, playhead, \
2124 resolution, source, the clip, and the empty audio lane's own line"
2125 );
2126 let back = parse(&bytes, &dir).expect("parse");
2127 // The spaces in it are the reason the stream field leads rather than
2128 // trails: everything after the first one is path.
2129 assert_eq!(back.sources, vec![nasty]);
2130 }
2131
2132 #[test]
2133 fn a_wrong_first_line_is_refused_by_name() {
2134 let dir = PathBuf::from("/proj");
2135 let err = parse(b"edith 12\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
2136 .unwrap_err()
2137 .to_string();
2138 assert_eq!(err, "line 1: unsupported version 12");
2139 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
2140 assert_eq!(
2141 parse(junk, &dir).unwrap_err().to_string(),
2142 "line 1: not a edith file"
2143 );
2144 }
2145 }
2146
2147 #[test]
2148 fn malformed_lines_name_their_line_number() {
2149 let dir = PathBuf::from("/proj");
2150 let cases: [(&[u8], &str); 10] = [
2151 // v3 wants the stream before the path, and a path after it.
2152 (
2153 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
2154 "line 2: \"a.mp4\" is not a number",
2155 ),
2156 (
2157 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
2158 "line 2: source without a path",
2159 ),
2160 (
2161 b"edith 1\nsource a.mp4\nclip 0 5\n",
2162 "line 3: clip wants 3 fields, found 2",
2163 ),
2164 (
2165 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
2166 "line 3: \"five\" is not a number",
2167 ),
2168 (
2169 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
2170 "line 3: clip [5, 5) is empty",
2171 ),
2172 (
2173 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
2174 "line 3: clip [7, 5) is empty",
2175 ),
2176 (
2177 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
2178 "line 3: clip names source 1 of 1",
2179 ),
2180 (
2181 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
2182 "line 4: source after a clip",
2183 ),
2184 (
2185 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
2186 "line 3: unknown keyword \"\"",
2187 ),
2188 (
2189 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
2190 "line 3: playhead belongs once, before the sources",
2191 ),
2192 ];
2193 for (bytes, want) in cases {
2194 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
2195 }
2196 }
2197
2198 /// The emptied timeline writes and reads back: every lane declared, no clip
2199 /// on any of them, and the source that gave the project its frame rate still
2200 /// named. Nothing about the format changes for it -- an empty lane already
2201 /// had a line of its own.
2202 #[test]
2203 fn a_project_without_clips_round_trips() {
2204 let dir = PathBuf::from("/proj");
2205 let source = Source {
2206 path: PathBuf::from("/proj/a.mp4"),
2207 audio_stream: 0,
2208 };
2209 let bytes = flat(&dir, &[source.clone()], &two(Vec::new(), Vec::new()), 0);
2210 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
2211 assert_eq!(back.sources, vec![source]);
2212 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
2213 assert_eq!(back.playhead, 0);
2214 // Older dialects, where the two lanes are implied rather than declared.
2215 assert_eq!(
2216 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
2217 two(Vec::new(), Vec::new())
2218 );
2219 assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty());
2220 }
2221
2222 /// Every truncation of a good file either parses or refuses; none panics.
2223 #[test]
2224 fn truncations_never_panic() {
2225 let (dir, sources, lanes) = doc();
2226 let bytes = flat(&dir, &sources, &lanes, 12);
2227 for cut in 0..bytes.len() {
2228 let _ = parse(&bytes[..cut], &dir);
2229 // ...and the same file with a byte lopped off the front, which
2230 // shifts every field into the wrong place.
2231 let _ = parse(&bytes[cut..], &dir);
2232 }
2233 // A % escape at the very end of a line has nothing to consume.
2234 assert_eq!(
2235 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
2236 .unwrap_err()
2237 .to_string(),
2238 "line 2: truncated % escape in the path"
2239 );
2240 }
2241}