forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc2943bbTahinli3 months ago647 commits

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