forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBe3392c8Tahinli3 months ago529 commits

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