forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB64e09f9Tahinli3 months ago453 commits

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