forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB5984e27Tahinli3 months ago583 commits

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