forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB86e9455Tahinli3 months ago398 commits

edith.rs2243 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 language: String::new(),
1091 name: String::new(),
1092 label: String::new(),
1093 cues: Vec::new(),
1094 bitmap: false,
1095 refused: None,
1096 }
1097 }
1098
1099 /// The v10 line: which track of which file, written beside the sources and
1100 /// read back as the pair a load opens. And what a v9 file is -- one with no
1101 /// subtitles at all, which still opens and re-saves as v10.
1102 #[test]
1103 fn subtitles_round_trip_as_references_and_a_v9_file_has_none() {
1104 let dir = PathBuf::from("/proj");
1105 let (_, sources, lanes) = doc();
1106 let tracks = [
1107 subtitle("/proj/subs.srt", None),
1108 subtitle("/proj/a.mp4", Some(3)),
1109 subtitle("/elsewhere/od d name.ass", None),
1110 ];
1111 let bytes = super::emit(
1112 &dir,
1113 &sources,
1114 &lanes,
1115 &[],
1116 &tracks,
1117 &[],
1118 &[],
1119 (1280, 720),
1120 None,
1121 crate::tonemap::Preset::default(),
1122 Limiter::default(),
1123 0,
1124 );
1125 let text = String::from_utf8_lossy(&bytes);
1126 assert!(
1127 text.contains(
1128 "subtitle - subs.srt\n\
1129 subtitle 3 a.mp4\n\
1130 subtitle - /elsewhere/od d name.ass\n"
1131 ),
1132 "the path is relative where it can be, and runs to the end of its \
1133 line, spaces and all: {text}"
1134 );
1135 let back = parse(&bytes, &dir).expect("v10 parses");
1136 assert_eq!(
1137 back.subtitles,
1138 vec![
1139 (PathBuf::from("/proj/subs.srt"), None),
1140 (PathBuf::from("/proj/a.mp4"), Some(3)),
1141 (PathBuf::from("/elsewhere/od d name.ass"), None),
1142 ]
1143 );
1144
1145 // A v9 file is a project with no subtitles, and re-saving it writes v10.
1146 let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1147 video 1 0 0 30 0 - - - fit 1000\n";
1148 let old = parse(v9, &dir).expect("v9 still loads");
1149 assert_eq!(old.subtitles, Vec::new());
1150 assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 11\n"));
1151 // ...and the line itself is not a v9 line: a dialect may not be mixed.
1152 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
1153 .unwrap_err()
1154 .to_string();
1155 assert_eq!(mixed, "line 3: unknown keyword \"subtitle\"");
1156 // A subtitle line with no path is refused, as a source with none is.
1157 for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] {
1158 let file = format!("edith 10\nsource 0 a.mp4\n{line}");
1159 assert!(
1160 parse(file.as_bytes(), &dir).is_err(),
1161 "{line:?} is not a subtitle line"
1162 );
1163 }
1164 }
1165
1166 /// The v11 line: the HDR rendition, written by name, read back as the very
1167 /// preset -- and the dialect before it, which had no way to say one and
1168 /// meant the published conversion.
1169 #[test]
1170 fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
1171 let dir = PathBuf::from("/proj");
1172 let (_, sources, lanes) = doc();
1173 for preset in crate::tonemap::Preset::ALL {
1174 let bytes = super::emit(
1175 &dir,
1176 &sources,
1177 &lanes,
1178 &[],
1179 &[],
1180 &[],
1181 &[],
1182 (1280, 720),
1183 None,
1184 preset,
1185 Limiter::default(),
1186 0,
1187 );
1188 let text = String::from_utf8_lossy(&bytes).to_string();
1189 assert_eq!(
1190 text.contains(&format!("tonemap {}\n", preset.name())),
1191 preset != crate::tonemap::Preset::default(),
1192 "the default is the line left out: {text}"
1193 );
1194 assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
1195 }
1196
1197 // A v10 file is a project shown the published way, and re-saving it
1198 // writes v11 with nothing more in it.
1199 let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1200 video 1 0 0 30 0 - - - fit 1000\n";
1201 let old = parse(v10, &dir).expect("v10 still loads");
1202 assert_eq!(old.tone, crate::tonemap::Preset::Reference);
1203 // ...and the line itself is not a v10 line: a dialect may not be mixed.
1204 let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
1205 .unwrap_err()
1206 .to_string();
1207 assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
1208 // A rendition nobody wrote is a corrupt line, by name -- not a silent
1209 // fall back to another picture.
1210 for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
1211 let file = format!("edith 11\nsource 0 a.mp4\n{line}");
1212 assert!(
1213 parse(file.as_bytes(), &dir).is_err(),
1214 "{line:?} is not a tonemap line"
1215 );
1216 }
1217 }
1218
1219 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
1220 Clip {
1221 start,
1222 in_frame,
1223 out_frame,
1224 source,
1225 link,
1226 eq: None,
1227 color: None,
1228 fit: FitPolicy::default(),
1229 speed: Speed::NORMAL,
1230 }
1231 }
1232
1233 /// [`emit`] for a timeline that equalizes nothing, which is every case that
1234 /// predates the eq lines.
1235 fn flat(
1236 dir: &Path,
1237 sources: &[Source],
1238 lanes: &[(LaneKind, Vec<Clip>)],
1239 playhead: u32,
1240 ) -> Vec<u8> {
1241 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
1242 }
1243
1244 /// Two sources, one under the project's own directory and one not, a clip
1245 /// from each on the video lane, and an audio lane with a gap in the middle
1246 /// -- the shape every case below starts from.
1247 fn source(path: &str, audio_stream: usize) -> Source {
1248 Source {
1249 path: PathBuf::from(path),
1250 audio_stream,
1251 }
1252 }
1253
1254 /// Lanes in display order, as [`Document::lanes`] holds them.
1255 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
1256
1257 /// `V1` then `A1`, the shape every dialect before v4 held.
1258 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
1259 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
1260 }
1261
1262 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
1263 (
1264 PathBuf::from("/proj"),
1265 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
1266 two(
1267 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
1268 vec![clip(0, 0, 30, 0, Some(0))],
1269 ),
1270 )
1271 }
1272
1273 #[test]
1274 fn relative_and_absolute_paths_round_trip() {
1275 let (dir, sources, lanes) = doc();
1276 let bytes = flat(&dir, &sources, &lanes, 12);
1277 assert_eq!(
1278 String::from_utf8_lossy(&bytes),
1279 "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1280 source 2 /elsewhere/b.mp4\n\
1281 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1282 audio 1 0 0 30 0 0 - - fit 1000\n",
1283 "the file under the project directory is written relative to it, \
1284 each with the audio stream it plays"
1285 );
1286 let back = parse(&bytes, &dir).expect("parse");
1287 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
1288 assert_eq!(
1289 back.lanes, lanes,
1290 "both lanes, in display order; the trailing gap needs no line"
1291 );
1292 assert_eq!(back.playhead, 12);
1293 // ...and emitting the parsed document reproduces the same bytes.
1294 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
1295 }
1296
1297 /// The whole of the bump: a project of any number of lanes writes and reads
1298 /// back, in display order, empty lanes and cross-lane groups included.
1299 #[test]
1300 fn any_number_of_lanes_round_trips() {
1301 let dir = PathBuf::from("/proj");
1302 let sources = vec![source("/proj/a.mp4", 0)];
1303 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
1304 // shows, not video-then-audio -- with one take grouped across V1 and A2
1305 // (no paired ord, the lanes between them empty of it) and an A1 holding
1306 // nothing at all.
1307 let lanes = vec![
1308 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
1309 (LaneKind::Audio, Vec::new()),
1310 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
1311 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
1312 ];
1313 let bytes = flat(&dir, &sources, &lanes, 7);
1314 assert_eq!(
1315 String::from_utf8_lossy(&bytes),
1316 "edith 11\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
1317 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
1318 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
1319 "an empty lane is a line of its own; everything else is its clips"
1320 );
1321 let back = parse(&bytes, &dir).expect("parse");
1322 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
1323 assert_eq!(back.playhead, 7);
1324 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
1325
1326 // A lane number may not skip one of its kind: that lane was declared by
1327 // nothing, and the refusal names it.
1328 for (file, want) in [
1329 (
1330 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
1331 "line 3: lane V2 comes before V1",
1332 ),
1333 (
1334 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
1335 "line 4: lane A3 comes before A1",
1336 ),
1337 (
1338 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
1339 "line 3: lane numbers start at 1",
1340 ),
1341 // The clip fields are still the clip fields, one lane number on.
1342 (
1343 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
1344 "line 3: clip wants 5 fields, found 4",
1345 ),
1346 // ...and a v4 line in a v3 file reads as the garbled clip it is.
1347 (
1348 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
1349 "line 3: clip wants 5 fields, found 6",
1350 ),
1351 ] {
1352 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1353 }
1354 // Lanes and nothing on them is the emptied timeline, saved: a project.
1355 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
1356 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
1357 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
1358 }
1359
1360 /// One band, spelled the way an eq line spells it.
1361 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
1362 Band {
1363 freq_hz,
1364 gain_db,
1365 q,
1366 kind,
1367 }
1368 }
1369
1370 /// The whole of the v5 bump: the clips name a shared equalizer table, the
1371 /// bytes are the ones documented at the top of this file, and every f32 in
1372 /// them comes back *bit* for bit -- which is what makes a re-save of a
1373 /// loaded project produce the same file rather than a drifting one.
1374 #[test]
1375 fn equalizers_round_trip_bit_exactly_and_are_shared() {
1376 let dir = PathBuf::from("/proj");
1377 let sources = vec![source("/proj/a.mp4", 0)];
1378 let eq = vec![
1379 EqParams {
1380 bands: vec![
1381 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
1382 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
1383 ],
1384 },
1385 // The awkward ones: a value needing all 24 mantissa bits, one whose
1386 // shortest spelling is exponential, a subnormal, and a negative
1387 // zero -- plus the empty cascade, which is a setting like any other.
1388 EqParams {
1389 bands: vec![band_of(
1390 16_777_215.0,
1391 -0.1,
1392 f32::MIN_POSITIVE / 3.0,
1393 BandKind::HighShelf,
1394 )],
1395 },
1396 EqParams { bands: Vec::new() },
1397 ];
1398 // Two clips share entry 0, so it is written once; one clip plays flat.
1399 let lanes = two(
1400 vec![
1401 Clip {
1402 eq: Some(0),
1403 ..clip(0, 0, 30, 0, Some(0))
1404 },
1405 Clip {
1406 eq: Some(1),
1407 ..clip(30, 10, 20, 0, None)
1408 },
1409 ],
1410 vec![
1411 Clip {
1412 eq: Some(0),
1413 ..clip(0, 0, 30, 0, Some(0))
1414 },
1415 Clip {
1416 eq: Some(2),
1417 ..clip(30, 0, 10, 0, None)
1418 },
1419 ],
1420 );
1421 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
1422 assert_eq!(
1423 String::from_utf8_lossy(&bytes),
1424 "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1425 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
1426 eq 16777215.0:-0.1:3.918315e-39:hs\n\
1427 eq\n\
1428 video 1 0 0 30 0 0 0 - fit 1000\nvideo 1 30 10 20 0 - 1 - fit 1000\n\
1429 audio 1 0 0 30 0 0 0 - fit 1000\naudio 1 30 0 10 0 - 2 - fit 1000\n",
1430 "the table comes before the clips, and a clip names a line of it"
1431 );
1432
1433 let back = parse(&bytes, &dir).expect("parse");
1434 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
1435 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
1436 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
1437 assert_eq!(
1438 (
1439 got.freq_hz.to_bits(),
1440 got.gain_db.to_bits(),
1441 got.q.to_bits(),
1442 got.kind
1443 ),
1444 (
1445 want.freq_hz.to_bits(),
1446 want.gain_db.to_bits(),
1447 want.q.to_bits(),
1448 want.kind
1449 ),
1450 "eq {i} band {b} came back as other bits"
1451 );
1452 }
1453 }
1454 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
1455 assert_eq!(
1456 emit(
1457 &dir,
1458 &back.sources,
1459 &back.lanes,
1460 &back.eq,
1461 &back.color,
1462 (1280, 720),
1463 0
1464 ),
1465 bytes
1466 );
1467 }
1468
1469 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
1470 /// colour table, the bytes are the ones documented at the top of this file,
1471 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
1472 #[test]
1473 fn colours_round_trip_bit_exactly_and_are_shared() {
1474 let dir = PathBuf::from("/proj");
1475 let sources = vec![source("/proj/a.mp4", 0)];
1476 let color = vec![
1477 ColorParams {
1478 brightness: 0.1,
1479 contrast: 1.2,
1480 saturation: 0.9,
1481 tint: -0.3,
1482 },
1483 // The awkward ones again: all 24 mantissa bits, an exponential
1484 // spelling, a subnormal and a negative zero -- and the identity,
1485 // which is a setting like any other.
1486 ColorParams {
1487 brightness: -0.000_000_1,
1488 contrast: 16_777_215.0,
1489 saturation: f32::MIN_POSITIVE / 3.0,
1490 tint: -0.0,
1491 },
1492 ColorParams::default(),
1493 ];
1494 // Two clips share entry 0, so it is written once; one clip is ungraded.
1495 let lanes = two(
1496 vec![
1497 Clip {
1498 color: Some(0),
1499 fit: FitPolicy::default(),
1500 speed: Speed::NORMAL,
1501 ..clip(0, 0, 30, 0, Some(0))
1502 },
1503 Clip {
1504 color: Some(1),
1505 fit: FitPolicy::default(),
1506 speed: Speed::NORMAL,
1507 ..clip(30, 10, 20, 0, None)
1508 },
1509 ],
1510 vec![
1511 Clip {
1512 color: Some(0),
1513 fit: FitPolicy::default(),
1514 speed: Speed::NORMAL,
1515 ..clip(0, 0, 30, 0, Some(0))
1516 },
1517 Clip {
1518 color: Some(2),
1519 fit: FitPolicy::default(),
1520 speed: Speed::NORMAL,
1521 ..clip(30, 0, 10, 0, None)
1522 },
1523 ],
1524 );
1525 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1526 assert_eq!(
1527 String::from_utf8_lossy(&bytes),
1528 "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1529 color 0.1:1.2:0.9:-0.3\n\
1530 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1531 color 0.0:1.0:1.0:0.0\n\
1532 video 1 0 0 30 0 0 - 0 fit 1000\nvideo 1 30 10 20 0 - - 1 fit 1000\n\
1533 audio 1 0 0 30 0 0 - 0 fit 1000\naudio 1 30 0 10 0 - - 2 fit 1000\n",
1534 "the table comes before the clips, and a clip names a line of it"
1535 );
1536
1537 let back = parse(&bytes, &dir).expect("parse");
1538 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
1539 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
1540 assert_eq!(
1541 (
1542 got.brightness.to_bits(),
1543 got.contrast.to_bits(),
1544 got.saturation.to_bits(),
1545 got.tint.to_bits()
1546 ),
1547 (
1548 want.brightness.to_bits(),
1549 want.contrast.to_bits(),
1550 want.saturation.to_bits(),
1551 want.tint.to_bits()
1552 ),
1553 "color {i} came back as other bits"
1554 );
1555 }
1556 assert_eq!(back.color.len(), 3);
1557 assert_eq!(
1558 emit(
1559 &dir,
1560 &back.sources,
1561 &back.lanes,
1562 &back.eq,
1563 &back.color,
1564 (1280, 720),
1565 0
1566 ),
1567 bytes
1568 );
1569 }
1570
1571 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
1572 /// intact, and re-saving it writes the new magic and a `-` colour field.
1573 #[test]
1574 fn a_v5_file_grades_nothing() {
1575 let dir = PathBuf::from("/proj");
1576 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
1577 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
1578 let old = parse(v5, &dir).expect("v5 parses");
1579 assert!(old.color.is_empty(), "nothing before v6 grades anything");
1580 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
1581 assert_eq!(old.lanes[0].1[0].eq, Some(0));
1582 assert!(old.lanes[0].1[0].color.is_none());
1583 assert_eq!(
1584 String::from_utf8_lossy(&emit(
1585 &dir,
1586 &old.sources,
1587 &old.lanes,
1588 &old.eq,
1589 &old.color,
1590 (1280, 720),
1591 old.playhead
1592 )),
1593 "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1594 eq 80.0:-3.0:0.707:ls\n\
1595 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1596 );
1597 }
1598
1599 /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
1600 /// written on its own line, comes back as the very number that was set, and
1601 /// a v7 file -- which has no such field -- loads at real time and re-saves
1602 /// saying so.
1603 #[test]
1604 fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
1605 let dir = PathBuf::from("/proj");
1606 let sources = vec![Source::new("/proj/a.mp4", 0)];
1607 let speeded = |start, in_frame, out_frame, permille| Clip {
1608 start,
1609 in_frame,
1610 out_frame,
1611 source: 0,
1612 link: None,
1613 eq: None,
1614 color: None,
1615 fit: FitPolicy::default(),
1616 speed: Speed::from_permille(permille),
1617 };
1618 // 30 source frames at 2x is 15 timeline frames, which is where the
1619 // second clip starts -- the file writes the source range and the rate,
1620 // and the length on the timeline is derived from the two.
1621 let lanes = vec![
1622 (
1623 LaneKind::Video,
1624 vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
1625 ),
1626 (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
1627 ];
1628 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
1629 assert_eq!(
1630 String::from_utf8_lossy(&bytes),
1631 "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1632 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
1633 audio 1 0 0 30 0 - - - fit 2000\n",
1634 "the rate is the clip line's last field, in thousandths"
1635 );
1636 let back = parse(&bytes, &dir).expect("parse");
1637 assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
1638
1639 // ...and the dialect before it, which had no rate to name.
1640 let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1641 video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
1642 let old = parse(v7, &dir).expect("v7 parses");
1643 assert!(
1644 old.lanes
1645 .iter()
1646 .flat_map(|(_, clips)| clips)
1647 .all(|c| c.speed == Speed::NORMAL),
1648 "nothing before v8 plays at anything but real time"
1649 );
1650 assert_eq!(
1651 String::from_utf8_lossy(&emit(
1652 &dir,
1653 &old.sources,
1654 &old.lanes,
1655 &old.eq,
1656 &old.color,
1657 (1280, 720),
1658 old.playhead
1659 )),
1660 "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1661 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1662 );
1663 // A rate outside what the editor can set is a corrupt line, by name.
1664 let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
1665 assert_eq!(
1666 parse(bad, &dir).unwrap_err().to_string(),
1667 "line 3: speed 9000 is outside 250-4000 thousandths"
1668 );
1669 }
1670
1671 /// The whole of the v9 bump, the speed test's twin: the mix a project was
1672 /// left at -- every track's own volume and the master limiter -- plus the
1673 /// rate it was cut at, all written, all read back as the very numbers, and
1674 /// a v8 file (which has none of them) loading flat and unlimited.
1675 #[test]
1676 fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
1677 let dir = PathBuf::from("/proj");
1678 let sources = vec![Source::new("/proj/a.mp4", 0)];
1679 let lanes = vec![
1680 (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
1681 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
1682 // A second audio track, turned down: the gain lines are per lane,
1683 // so the two must not run into one another.
1684 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
1685 ];
1686 let limiter = Limiter {
1687 ceiling_db: -1.5,
1688 on: true,
1689 };
1690 let bytes = super::emit(
1691 &dir,
1692 &sources,
1693 &lanes,
1694 &[0.0, 3.0, -6.5],
1695 &[],
1696 &[],
1697 &[],
1698 (1280, 720),
1699 Some(23.976023976023978),
1700 crate::tonemap::Preset::default(),
1701 limiter,
1702 0,
1703 );
1704 assert_eq!(
1705 String::from_utf8_lossy(&bytes),
1706 "edith 11\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
1707 limiter -1.5 on\nsource 0 a.mp4\n\
1708 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
1709 audio 2 0 0 30 0 - - - fit 1000\n\
1710 gain audio 1 3.0\ngain audio 2 -6.5\n",
1711 "the mix is lines of its own, the gains after the lanes they name"
1712 );
1713 let back = parse(&bytes, &dir).expect("parse");
1714 assert_eq!(back.lanes, lanes);
1715 assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
1716 assert_eq!(back.limiter, limiter);
1717 assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
1718
1719 // ...and the dialect before it, which carried none of the three: a v8
1720 // file mixes flat, limits nothing, and says nothing about its rate.
1721 let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1722 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
1723 let old = parse(v8, &dir).expect("v8 parses");
1724 assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
1725 assert_eq!(old.limiter, Limiter::default());
1726 assert_eq!(old.fps, None);
1727 // A v9 file may leave all three out too, and means the same thing.
1728 assert_eq!(
1729 String::from_utf8_lossy(&emit(
1730 &dir,
1731 &old.sources,
1732 &old.lanes,
1733 &old.eq,
1734 &old.color,
1735 (1280, 720),
1736 old.playhead
1737 )),
1738 "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1739 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1740 );
1741
1742 // Each of the three refuses by name, on its own line.
1743 for (text, want) in [
1744 (
1745 "edith 9\nfps nope\nsource 0 a.mp4\n",
1746 "line 2: \"nope\" is not a frame rate",
1747 ),
1748 (
1749 "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
1750 "line 2: limiter is on or off, not \"maybe\"",
1751 ),
1752 (
1753 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
1754 "line 4: gain names a lane that is not there",
1755 ),
1756 (
1757 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
1758 "line 4: gain names \"lane\", not a lane kind",
1759 ),
1760 ] {
1761 assert_eq!(
1762 parse(text.as_bytes(), &dir).unwrap_err().to_string(),
1763 want,
1764 "{text:?}"
1765 );
1766 }
1767 // A hand-written ceiling nothing could limit at is clamped, not taken.
1768 let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
1769 assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
1770 }
1771
1772 /// The refusals the colour grammar adds, each naming its line.
1773 #[test]
1774 fn a_malformed_colour_names_its_line() {
1775 let dir = PathBuf::from("/proj");
1776 let head = "edith 6\nsource 0 a.mp4\n";
1777 // v6, deliberately: the colour grammar is the same one v7 inherits, and
1778 // a v6 clip line is one field shorter.
1779 for (file, want) in [
1780 (
1781 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
1782 "line 3: color wants 4 fields, found 3",
1783 ),
1784 (
1785 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"),
1786 "line 3: color wants 1 fields, found 2",
1787 ),
1788 (
1789 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1790 "line 3: \"warm\" is not a number",
1791 ),
1792 // The two values the format cannot write and read back as itself.
1793 (
1794 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1795 "line 3: \"inf\" is not a number",
1796 ),
1797 (
1798 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
1799 "line 3: \"NaN\" is not a number",
1800 ),
1801 (
1802 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
1803 "line 4: clip names color 1 of 1",
1804 ),
1805 (
1806 format!("{head}video 1 0 0 5 0 - - 0\n"),
1807 "line 3: clip names color 0 of 0",
1808 ),
1809 // A clip's colour field is not optional in v6, and the table has to
1810 // be declared before the clip that names it.
1811 (
1812 format!("{head}video 1 0 0 5 0 - -\n"),
1813 "line 3: clip wants 7 fields, found 6",
1814 ),
1815 (
1816 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
1817 "line 4: color after a clip",
1818 ),
1819 // ...and a colour line in a file that predates them is a corrupt one.
1820 (
1821 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
1822 "line 3: unknown keyword \"color\"",
1823 ),
1824 ] {
1825 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1826 }
1827 }
1828
1829 /// The refusals the eq grammar adds, each naming its line.
1830 #[test]
1831 fn a_malformed_equalizer_names_its_line() {
1832 let dir = PathBuf::from("/proj");
1833 let head = "edith 5\nsource 0 a.mp4\n";
1834 for (file, want) in [
1835 (
1836 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
1837 "line 3: band wants 4 fields, found 3",
1838 ),
1839 (
1840 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
1841 "line 3: \"notch\" is not a band shape",
1842 ),
1843 (
1844 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
1845 "line 3: \"wide\" is not a number",
1846 ),
1847 // Neither of the two values a coefficient cannot be built from, and
1848 // NaN would not even compare equal to itself on the way back.
1849 (
1850 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1851 "line 3: \"inf\" is not a number",
1852 ),
1853 (
1854 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
1855 "line 3: \"NaN\" is not a number",
1856 ),
1857 (
1858 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
1859 "line 4: clip names eq 1 of 1",
1860 ),
1861 (
1862 format!("{head}video 1 0 0 5 0 - 0\n"),
1863 "line 3: clip names eq 0 of 0",
1864 ),
1865 // A clip's eq field is not optional in v5, and the table has to be
1866 // declared before the clip that names it.
1867 (
1868 format!("{head}video 1 0 0 5 0 -\n"),
1869 "line 3: clip wants 6 fields, found 5",
1870 ),
1871 (
1872 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
1873 "line 4: eq after a clip",
1874 ),
1875 // ...and an eq line in a file that predates them is a corrupt file.
1876 (
1877 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
1878 "line 3: unknown keyword \"eq\"",
1879 ),
1880 ] {
1881 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1882 }
1883 }
1884
1885 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
1886 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
1887 /// and not one byte else.
1888 #[test]
1889 fn a_v4_file_equalizes_nothing() {
1890 let dir = PathBuf::from("/proj");
1891 let (_, sources, lanes) = doc();
1892 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1893 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
1894 let old = parse(v4, &dir).expect("v4 parses");
1895 assert_eq!(
1896 (&old.sources, &old.lanes, old.playhead),
1897 (&sources, &lanes, 12)
1898 );
1899 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1900 assert_eq!(
1901 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1902 "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1903 source 2 /elsewhere/b.mp4\n\
1904 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1905 audio 1 0 0 30 0 0 - - fit 1000\n"
1906 );
1907 // An empty lane's line is still the whole of that lane, eq or no eq.
1908 let empty = parse(
1909 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
1910 &dir,
1911 )
1912 .expect("parse");
1913 assert!(empty.lanes[1].1.is_empty());
1914 }
1915
1916 /// The other half of the compatibility promise: a v3 file is a v4 one
1917 /// without the lane numbers, and a v2 file names no audio stream and means
1918 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
1919 /// they always were, and saving either writes v5 with nothing else changed.
1920 #[test]
1921 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
1922 let dir = PathBuf::from("/proj");
1923 let (_, _, lanes) = doc();
1924 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1925 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1926 let old = parse(v3, &dir).expect("v3 parses");
1927 assert_eq!(
1928 (&old.sources, &old.lanes, old.playhead),
1929 (
1930 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
1931 &lanes,
1932 12
1933 ),
1934 "a v3 file loads as exactly the state its v5 twin does"
1935 );
1936 // ...and re-saved it *is* that twin: the magic and a lane number per
1937 // clip line, and not one byte else.
1938 assert_eq!(
1939 flat(&dir, &old.sources, &old.lanes, old.playhead),
1940 flat(&dir, &old.sources, &lanes, 12),
1941 );
1942
1943 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
1944 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
1945 let back = parse(v2, &dir).expect("v2 parses");
1946 assert_eq!(
1947 back.sources,
1948 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
1949 );
1950 assert_eq!(back.lanes, lanes);
1951
1952 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1953 assert_eq!(
1954 String::from_utf8_lossy(&v5),
1955 "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1956 source 0 /elsewhere/b.mp4\n\
1957 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1958 audio 1 0 0 30 0 0 - - fit 1000\n",
1959 "a re-saved v2 project differs only by its version, the lane \
1960 numbers, the streams it always meant and an equalizer it has none of"
1961 );
1962 let again = parse(&v5, &dir).expect("v5 parses");
1963 assert_eq!(again.sources, back.sources);
1964 }
1965
1966 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
1967 /// lanes, and saving it again writes v5.
1968 #[test]
1969 fn a_v1_file_loads_as_two_grouped_lanes() {
1970 let dir = PathBuf::from("/proj");
1971 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
1972 let back = parse(v1, &dir).expect("v1 parses");
1973 assert_eq!(
1974 back.lanes[0].1,
1975 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
1976 "v1 clips queue up: the second starts where the first ended"
1977 );
1978 assert_eq!(
1979 back.lanes,
1980 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
1981 "one take per clip, on both lanes"
1982 );
1983 assert_eq!(back.playhead, 5);
1984 // Saved again it is the current version, which round-trips to the
1985 // same document.
1986 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1987 assert!(v5.starts_with(b"edith 11\n"));
1988 let again = parse(&v5, &dir).expect("v5 parses");
1989 assert_eq!(again.lanes, back.lanes);
1990 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
1991 for (bytes, want) in [
1992 (
1993 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
1994 "line 3: unknown keyword \"video\"",
1995 ),
1996 (
1997 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
1998 "line 3: unknown keyword \"clip\"",
1999 ),
2000 ] {
2001 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
2002 }
2003 }
2004
2005 /// A gap is the absence of a line, so a lane's placements must arrive in
2006 /// order and never overlap -- the invariant the whole model rests on.
2007 #[test]
2008 fn a_lane_out_of_order_or_overlapping_is_refused() {
2009 let dir = PathBuf::from("/proj");
2010 for bytes in [
2011 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
2012 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
2013 ] {
2014 let err = parse(bytes, &dir).unwrap_err().to_string();
2015 assert!(err.starts_with("line 4: clip at "), "{err}");
2016 }
2017 // The lanes are independent, so a video line never crowds an audio one.
2018 assert!(
2019 parse(
2020 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
2021 &dir
2022 )
2023 .is_ok()
2024 );
2025 // ...and a lane may be empty as long as the other one is not.
2026 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
2027 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
2028 }
2029
2030 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
2031 /// and wrap in release, and a wrapped end passes the overlap check --
2032 /// crafted numbers must be refused by name, in both dialects.
2033 #[test]
2034 fn a_clip_whose_end_overflows_is_refused() {
2035 let dir = PathBuf::from("/proj");
2036 for bytes in [
2037 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
2038 // Two of them: the second would land *before* the first once wrapped.
2039 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
2040 // v1 has no `start` field, but its queue reaches the same ceiling.
2041 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
2042 ] {
2043 let err = parse(bytes, &dir).unwrap_err().to_string();
2044 assert!(
2045 err.contains("runs past the last frame there is"),
2046 "not refused by name: {err}"
2047 );
2048 }
2049 }
2050
2051 /// The relocatability promise, from the two directions a project path
2052 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
2053 /// clip.mp4`, whose parent is `""`) and a directory reached through a
2054 /// symlink. Both used to emit absolute source lines.
2055 #[test]
2056 fn a_non_canonical_project_path_still_writes_relative_sources() {
2057 assert_eq!(
2058 project_dir(Path::new("a.edith")),
2059 std::env::current_dir().expect("cwd"),
2060 "a bare filename is saved into the working directory"
2061 );
2062
2063 let dir = crate::scratch::Scratch::dir("ve_edith_link");
2064 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
2065 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
2066 let source = dir.join("real/a.mp4");
2067 let path = dir.join("link/p.edith");
2068
2069 let one = [clip(0, 0, 30, 0, None)];
2070 let entry = Source {
2071 path: source,
2072 audio_stream: 1,
2073 };
2074 save(
2075 &path,
2076 &[entry],
2077 &two(one.to_vec(), one.to_vec()),
2078 &[],
2079 &[],
2080 &[],
2081 &[],
2082 (1280, 720),
2083 None,
2084 crate::tonemap::Preset::default(),
2085 Limiter::default(),
2086 0,
2087 )
2088 .expect("save");
2089 let bytes = std::fs::read(&path).expect("read back");
2090 assert_eq!(
2091 String::from_utf8_lossy(&bytes),
2092 "edith 11\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
2093 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
2094 );
2095 // Loading rejoins the *given* directory, so the file is reached by the
2096 // way the project was opened -- the same file, through the link, still
2097 // playing the stream it was saved on.
2098 assert_eq!(
2099 load(&path).expect("load").sources,
2100 vec![Source {
2101 path: dir.join("link/a.mp4"),
2102 audio_stream: 1,
2103 }]
2104 );
2105 std::fs::remove_dir_all(&dir).expect("cleanup");
2106 }
2107
2108 #[test]
2109 fn escapes_survive_the_bytes_json_would_not() {
2110 let dir = PathBuf::from("/proj");
2111 // A newline and a percent in a filename, plus a non-UTF-8 byte.
2112 let nasty = Source {
2113 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
2114 audio_stream: 0,
2115 };
2116 let bytes = flat(
2117 &dir,
2118 &[nasty.clone()],
2119 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
2120 0,
2121 );
2122 assert_eq!(
2123 bytes.iter().filter(|&&b| b == b'\n').count(),
2124 6,
2125 "the escaped newline must not become a line break: magic, playhead, \
2126 resolution, source, the clip, and the empty audio lane's own line"
2127 );
2128 let back = parse(&bytes, &dir).expect("parse");
2129 // The spaces in it are the reason the stream field leads rather than
2130 // trails: everything after the first one is path.
2131 assert_eq!(back.sources, vec![nasty]);
2132 }
2133
2134 #[test]
2135 fn a_wrong_first_line_is_refused_by_name() {
2136 let dir = PathBuf::from("/proj");
2137 let err = parse(b"edith 12\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
2138 .unwrap_err()
2139 .to_string();
2140 assert_eq!(err, "line 1: unsupported version 12");
2141 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
2142 assert_eq!(
2143 parse(junk, &dir).unwrap_err().to_string(),
2144 "line 1: not a edith file"
2145 );
2146 }
2147 }
2148
2149 #[test]
2150 fn malformed_lines_name_their_line_number() {
2151 let dir = PathBuf::from("/proj");
2152 let cases: [(&[u8], &str); 10] = [
2153 // v3 wants the stream before the path, and a path after it.
2154 (
2155 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
2156 "line 2: \"a.mp4\" is not a number",
2157 ),
2158 (
2159 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
2160 "line 2: source without a path",
2161 ),
2162 (
2163 b"edith 1\nsource a.mp4\nclip 0 5\n",
2164 "line 3: clip wants 3 fields, found 2",
2165 ),
2166 (
2167 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
2168 "line 3: \"five\" is not a number",
2169 ),
2170 (
2171 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
2172 "line 3: clip [5, 5) is empty",
2173 ),
2174 (
2175 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
2176 "line 3: clip [7, 5) is empty",
2177 ),
2178 (
2179 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
2180 "line 3: clip names source 1 of 1",
2181 ),
2182 (
2183 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
2184 "line 4: source after a clip",
2185 ),
2186 (
2187 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
2188 "line 3: unknown keyword \"\"",
2189 ),
2190 (
2191 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
2192 "line 3: playhead belongs once, before the sources",
2193 ),
2194 ];
2195 for (bytes, want) in cases {
2196 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
2197 }
2198 }
2199
2200 /// The emptied timeline writes and reads back: every lane declared, no clip
2201 /// on any of them, and the source that gave the project its frame rate still
2202 /// named. Nothing about the format changes for it -- an empty lane already
2203 /// had a line of its own.
2204 #[test]
2205 fn a_project_without_clips_round_trips() {
2206 let dir = PathBuf::from("/proj");
2207 let source = Source {
2208 path: PathBuf::from("/proj/a.mp4"),
2209 audio_stream: 0,
2210 };
2211 let bytes = flat(&dir, &[source.clone()], &two(Vec::new(), Vec::new()), 0);
2212 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
2213 assert_eq!(back.sources, vec![source]);
2214 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
2215 assert_eq!(back.playhead, 0);
2216 // Older dialects, where the two lanes are implied rather than declared.
2217 assert_eq!(
2218 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
2219 two(Vec::new(), Vec::new())
2220 );
2221 assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty());
2222 }
2223
2224 /// Every truncation of a good file either parses or refuses; none panics.
2225 #[test]
2226 fn truncations_never_panic() {
2227 let (dir, sources, lanes) = doc();
2228 let bytes = flat(&dir, &sources, &lanes, 12);
2229 for cut in 0..bytes.len() {
2230 let _ = parse(&bytes[..cut], &dir);
2231 // ...and the same file with a byte lopped off the front, which
2232 // shifts every field into the wrong place.
2233 let _ = parse(&bytes[cut..], &dir);
2234 }
2235 // A % escape at the very end of a line has nothing to consume.
2236 assert_eq!(
2237 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
2238 .unwrap_err()
2239 .to_string(),
2240 "line 2: truncated % escape in the path"
2241 );
2242 }
2243}