forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc327308Tahinli25 days ago1014 commits

edith.rs8522 lines, 382.9 KiBHistoryRawDownload
1//! The project file: a line of text per thing, and nothing else.
2//!
3//! ```text
4//! edith 30
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//! cue 0 3 Retyped\nby hand
18//! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
19//! color 0.1:1.2:0.9:-0.3
20//! transform 0.1:-0.1:1.5:90.0:0.0:0.0:0.0:0.0
21//! video 1 0 0 120 0 0 0 0 fit 1000 0 0 0 -
22//! audio 1 0 0 120 0 0 0 - fit 1000 30 30 0 -
23//! video 2 120 0 120 1 - - - fill 2000 0 0 0 0
24//! audio 2
25//! sub 1 0 60 0 500000 1500000
26//! sub 2
27//! gain audio 1 -3.0
28//! flags audio 1 muted
29//! ```
30//!
31//! The `fps` line is the rate the timeline was cut at -- the scaffolding
32//! source's own unless a rate was picked
33//! ([`crate::PlaybackSession::set_frame_rate`]), and the *only* thing that says
34//! so once one was, since every clip number in the file is counted in it.
35//! Printed so it reads back bit-exactly. A file without one (every dialect
36//! before v9) means 0"whatever the scaffolding source runs at", which is what
37//! such a project always was and is an answer only a project holding a video has
38//! ([`crate::PlaybackSession::open_project`]).
39//!
40//! A `subtitle` line is `subtitle <track> <path>`: which track of that file the
41//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle
42//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the
43//! reason a source's is. Only the reference is written: the cues themselves are
44//! read back out of the file on the way in, exactly as a clip's pictures are, so
45//! a project file stays an edit list. A subtitle file that has gone missing
46//! since the save comes back listed and refused by name rather than dropped,
47//! which is what keeps a re-save from losing it.
48//!
49//! A `sublang` line is `sublang <track> <code>`: the language of a subtitle
50//! track, the track by its position in the `subtitle` lines and the code as the
51//! rest of the line (escaped as a `cue`'s text is). Written after the `subtitle`
52//! lines, one for each track that has a language: an import names a standalone
53//! file's from its file name or the person's `lang`, and a retype replaces an
54//! embedded track's container language. **Version 33** is the first dialect
55//! with one; a project with none is written exactly as it always was.
56//!
57//! A `chapter` line is `chapter <frame> <name>`: a chapter marker at a timeline
58//! frame, the name as the rest of the line, escaped as a `cue` line's is. Written
59//! after the `title` lines in frame order, one per frame. **Version 34** is the
60//! first dialect with one; a project with none is written exactly as a v33 one.
61//!
62//! A `speedkeys` line is `speedkeys <kind> <ord> <index> <at>:<permille> ...`: a
63//! clip's speed ramp ([`crate::project::Clip::speed_keys`]), the keys in frame
64//! order, each speed in thousandths like the clip's own `speed` field. Written after
65//! the lanes it names, only for a clip with keys. **Version 35** is the first
66//! dialect with one; a project with no ramp is written exactly as a v34 one.
67//!
68//! A `marker` line is `marker <frame> <length> <color> <name>`: a comment marker, a
69//! point when the length in frames is 0 and a range otherwise, the colour one of
70//! red, orange, yellow, green, blue or purple, the name the rest of the line (escaped
71//! as a `cue` line's is). Written after the `chapter` lines in frame order; several may
72//! share a frame. A `marknote <n> <text>` line gives the note of the n-th `marker` line
73//! (the first is 0), only for a marker that has one. **Version 36** is the first
74//! dialect with either; a project with no marker is written exactly as a v35 one.
75//!
76//! A `transition` line is `transition <kind> <ord> <index> <name>`: how a clip's
77//! `transition_out` is drawn ([`crate::transitions::TransitionKind`]), by its
78//! name -- `dip-black`, `wipe-left`, `zoom` and so on. Written after the lanes it
79//! names, only for a clip whose kind is not the dissolve. **Version 37** is the
80//! first dialect with one; a project with only dissolves is written exactly as
81//! before, and a file without the line means dissolves.
82//!
83//! A `reverse` line is `reverse <kind> <ord> <index>`: the clip plays its source window
84//! backwards ([`crate::project::Clip::reversed`]), named as a `speedkeys` line names its
85//! clip. The clip's window, speed and footprint are the lines it already has; the
86//! source-keyed `gainkeys` and `tkeys` are written as the clip plays them, so they
87//! need no knowing of the direction to be read. Written after the lanes it names, only
88//! for a reversed clip. **Version 38** is the first dialect with one; a project with
89//! none is written exactly as a v35 (or older) one.
90//!
91//! An `okeys` line is `okeys video <ord> <index> <at>:<ease>:<opacity> ...` and a
92//! `ckeys` line `ckeys video <ord> <index> <at>:<ease>:<b>,<c>,<s>,<t> ...`: a video
93//! clip's opacity and colour animations, keys in source order, each with the ease of
94//! the segment that leaves it (`lin`, `ease`, `in`, `out`, `hold`). **Version 39** is the
95//! first dialect with either, and the first where a `gainkeys` or `tkeys` point may
96//! carry an ease beyond linear and `ease`; a project with none is written as before.
97//!
98//! A `capstyle` line is `capstyle <animation> <rrggbb> <box 0|1> <uppercase 0|1> <words per
99//! line>`: the project's caption animation, written only when it is not the default. A
100//! `cuewords` line is `cuewords <track> <cue> <start_us> <end_us> <word> ...`: a cue's real
101//! word times, only for a cue that has them. **Version 40** is the first dialect with
102//! either; a project with neither is written under the header it needed before.
103//!
104//! A `cue` line is `cue <track> <cue> <text>`: an override of one cue's words,
105//! the track by position in the `subtitle` lines (the first is track 0) and the
106//! cue by its position in that track as its file parses -- so it needs the file
107//! it names to be the one it was edited against, which a project holds it to by
108//! not changing the file. The text is the rest of the line, escaped: `\\` for a
109//! backslash, `\n` and `\r` for the two line breaks, and nothing else. Applied
110//! on the way in, after the track is read, so the edited words come back where
111//! the file's would have been. Written after the `subtitle` lines it names and
112//! only when somebody has retyped a cue, so a project nobody has edited is the
113//! bytes it was. Like the `flags` lines it is v24: a v23 file has none.
114//!
115//! The `tonemap` line is which HDR-to-SDR rendition the project is watched and
116//! exported in ([`crate::tonemap::Preset`]), spelled `reference`, `standard` or
117//! `vivid`. Left out when it is the default, which is `reference` -- so a
118//! project holding no HDR media, and one whose owner never picked, are the bytes
119//! they were.
120//!
121//! The `proxy` line is whether this project is cut on the stand-ins
122//! ([`crate::proxy`]) rather than on the films themselves, spelled `on` or
123//! `off`. Left out when it is off, which is what every dialect before v12 was.
124//! *Which* sources have a stand-in is not written: a proxy is found by the
125//! film's own path, length and modification time, so the cache is the only
126//! answer and a project file cannot go stale about it.
127//!
128//! The `autoproxy` line is whether a film this machine cuts slowly gets a
129//! stand-in made for it the moment it is imported ([`crate::proxy::wanted`]),
130//! spelled `on` or `off`. Left out when it is on, which is what every dialect
131//! before v13 did and could not be told not to. With it off an import makes
132//! nothing at all, and turning the `proxy` switch on is what asks for the
133//! stand-ins this project is missing -- which is the only way to ask, so a
134//! project that never wants them never spends a minute of encode on one.
135//!
136//! The `encoder` line is which seat an export of this project writes its
137//! picture with ([`crate::export::EncoderSeat`]), spelled `auto`, `hardware` or
138//! `software`. Left out when it is `auto` -- hardware where this machine has a
139//! seat and software everywhere else -- which is what every dialect before v14
140//! did and could not be told otherwise. It is the project's and not the
141//! machine's for the reason the tone map is: a person who picked the software
142//! encoder for *this* delivery picked it for every export of it, and a pick
143//! that vanished on a reload is a pick nobody could keep.
144//!
145//! The `limiter` line is the master limiter over the whole mix
146//! ([`crate::limiter`]): its true-peak ceiling in dBTP and whether it is in circuit,
147//! spelled `on` or `off`. Left out when it is the default, which is off.
148//!
149//! A `gain` line is `gain <kind> <lane> <dB>`: how loud that whole lane plays,
150//! everything on it and every frequency of it -- a different thing from a
151//! clip's `eq` line, which is one take and one band. It names its lane the way
152//! a clip line does and comes *after* the lanes, because a lane is declared by
153//! its clips and a gain declares nothing. Only a lane somebody has turned gets
154//! one; the rest are at 0 dB, which is where every lane of every dialect before
155//! v9 is.
156//!
157//! A `voice` line is `voice audio <lane> <processor> <fields>...`: one audio lane's voice
158//! cleanup ([`crate::voice`]), one line per processor that is not at its default --
159//! `gate <on> <threshold> <attack> <release> <hold> <range>`, `nr <on> <strength> <floor>
160//! <profile>` (the noise profile as 256 comma-separated dB, or `-`), `comp <on> <threshold>
161//! <ratio> <attack> <release> <knee> <makeup> <auto>` and `deess <on> <threshold> <amount>
162//! <lo> <hi>`. **Version 41** is the first dialect with one; a project with every lane at
163//! the defaults is written under the header it needed before, and a v40 file loads with every
164//! processor off.
165//!
166//! An `effect` line is `effect video <lane> <clip> <kind> <on> <value>...`: one effect of
167//! a clip's effects stack ([`crate::effects`]), the lines of one clip in stack order. `kind`
168//! is the effect's name (`blur`, `vignette`, `chroma_key`, ...), `on` is `1` or `0`, and the
169//! values are its parameters in [`crate::effects::EffectKind::params`] order, each in its
170//! range. **Version 42** is the first dialect with one; a project with no effect on any clip
171//! is written under the header it needed before.
172//!
173//! A `stab` line is `stab video <ord> <index> <strength> <crop>`: a video clip's
174//! stabilisation ([`crate::stabilise`]), strength `0..=1` and crop `zoom` or `full`. Only a
175//! stabilised clip gets one. **Version 44** is the first dialect with one; a project with no
176//! stabilised clip is written under the header it needed before.
177//!
178//! A `lanename` line is `lanename <kind> <lane> <name>`: the display label a lane was given
179//! (the text escaped as a title's is); the lane keeps its address. A `deint` line is
180//! `deint video <ord> <index> <mode>` with mode `field` or `off` (`frame` is the default and
181//! written by no one): how a clip's interlaced source is deinterlaced. **Version 46** is the
182//! first dialect with either; a project with no named lane and no such clip is written under
183//! the header it needed before.
184//!
185//! A `flags` line is `flags <kind> <lane> <switch>...`: which lane, named as a
186//! gain names one, and then the switches that are set on it -- any of `hidden`,
187//! `muted` and `locked`, each at most once, in any order. `hidden` is for a
188//! video or subtitle lane and `muted` for an audio one: a switch the kind of
189//! lane cannot have is refused, as the setters refuse it. Like a gain it comes
190//! after the lanes and only a lane somebody has switched gets one, so a
191//! project with none is the bytes a v23 one was bar the version line.
192//!
193//! A `duck` line is `duck audio <lane> <under> <depth> <threshold> <attack> <release>`:
194//! the audio lane that is ducked, the audio lane it is ducked under (its key),
195//! both named as a gain names an audio lane (1-based, `audio 1` is `A1`), then
196//! the depth in dB (`-40..=0`), the key threshold in dBFS (`-90..=0`), and the
197//! attack and release in ms (attack `1..=2000`, release `1..=10000`). Like a
198//! gain it comes after the lanes, a duck names its key lane, and only a lane
199//! somebody has ducked gets one; a key may not be the lane it ducks. A project
200//! with none is the bytes a v24 one was bar the version line. **Version 30** lets
201//! a lane be ducked under several keys: one `duck` line per key, in the order
202//! the lane holds them, and the same key twice is refused. Before it a lane has
203//! one `duck` line, and a second for it is refused by name.
204//!
205//! A `title` line is one title card or text overlay:
206//! `title <start> <frames> <fade_in> <fade_out> <size> <outline> <boxed> <place> <text>`.
207//! The frames are timeline frames (the title shows on `start..start+frames`),
208//! the fades are frames, `size` is the em size in permille of the frame height
209//! (`10..=200`), `outline` is `none`, `thin` or `thick`, `boxed` is `0` or `1`,
210//! and `place` is `bottom`, `top` or `centre`. The text is the rest of the line,
211//! escaped as a `cue` line's is, so it may hold spaces and a line break as `\n`.
212//! Titles are written in list order, after the `duck` lines; a project with none
213//! is the bytes a v25 one was bar the version line.
214//!
215//! **Version 49** gives a title a look: a `titlestyle <title> <position> <align> <weight>
216//! <rrggbb> <rrggbbaa>` line after the `title` lines, one per title that is not white, regular,
217//! centred on a black 60% box, naming the title by its place in the list (0 is the first).
218//! `position` is where the block sits across the frame and `align` how its lines line up in it
219//! (both `centre`, `left` or `right`); `weight` is `regular` or `bold`; the first colour is the
220//! letters, the second the box with its opacity last. A project with none is the bytes a v48 one
221//! was bar the version line.
222//!
223//! **Version 54** gives a title an entrance and an exit animation: a `titleanim <title> <in> <out>
224//! <frames>` line after the `titlestyle` lines, one per title that has either, naming the title by
225//! its place in the list. `in` and `out` are the animation's name ([`TitleAnim::name`], `none` for
226//! none) and `frames` how long each takes. A project with none is the bytes a v53 one was bar the
227//! version line.
228//!
229//! **Version 56** animates any effect parameter: an `ekeys video <ord> <index> <slot> <at>:<ease>:<v0>,<v1>,...`
230//! line per effect with keys, the keys in source order, with one value for each of the effect's
231//! parameters ([`crate::effects::EffectKind::params`]) and the ease of the segment that leaves each
232//! key (a custom bezier is written as [`KeyEase::token`] gives it). A parameter that cannot be
233//! keyed (a switch or a choice) holds its static value. A v53 file's `mkeys` lines, which keyed
234//! only a mask's position, size and soft edge, are still read. A project with none is the bytes a
235//! v55 one was bar the version line.
236//!
237//! A `ttkeys` line is `ttkeys <title> <at>:<ease>:<x>,<y>,<scale>,<opacity> ...`: a title's own
238//! keyframe animation ([`crate::titleanim::TitleKey`]), the title named by its place in the list
239//! and the keys in frame order, `at` counted from the title's first frame. Written after the
240//! title's `titleanim` line, one per title that has keys. It is also v56, so a project with title
241//! keys is written as v56 and a project with none is the bytes a v55 one was bar the version line.
242//!
243//! A `cueadd` line is one cue added to a subtitle track, which no file has:
244//! `cueadd <track> <start_us> <end_us> <text>`, the track by its position in
245//! the `subtitle` lines, the times in microseconds on the track's own clock, and
246//! the text escaped as a `cue` line's is. It comes after the `cue` lines, so an
247//! added cue lands among the file's cues however they were retyped. A project
248//! with none is the bytes a v28 one was bar the version line.
249//!
250//! A `pitch` line is `pitch audio <ord> <index> <semitones>`: an audio clip's pitch
251//! shift in whole semitones, `-12` to `12`, written for each clip that is not at `0`,
252//! after the lanes it names (as `clippan` is). **Version 52** is the first dialect
253//! with one; a project with none is the bytes a v51 one was bar the version line.
254//!
255//! The `resolution` line is the **project's** picture size, which is a
256//! different thing from any source's: media of other sizes are placed on it.
257//! It belongs once, beside the playhead, and a file without one (every dialect
258//! before v7) means "source 0's own picture", which is what such a project
259//! always was.
260//!
261//! A source line is `source <audio stream> <path>`: which of the file's audio
262//! tracks that source plays, in the file order
263//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
264//! stream first because a path runs to the end of the line (it may hold
265//! spaces) and an optional *trailing* field could not be told from one.
266//!
267//! An eq line is `eq <band>...`, one band per field, each
268//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk`, `hs`,
269//! `lc` (low cut) or `hc` (high cut) ([`crate::eq::BandKind`]). Like a source it is named by *position* --
270//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
271//! curve write it once. `eq` on its own is the empty cascade, which is a
272//! setting like any other. The numbers are printed to round trip bit-exactly;
273//! anything not finite is refused, here and at [`crate::Project::set_eq`].
274//!
275//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
276//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
277//! -- the first colour line is color 0 -- printed and refused by the same rules.
278//!
279//! A colour line's look ([`crate::color::Look`]) rides on three line types
280//! written at the end of the file and naming the colour line by position:
281//! `wheels <color> <lift> <gamma> <gain>` (each `<master>:<red>:<green>:<blue>`,
282//! -1..1), `curve <color> <channel> <x>:<y>,...` (channel `master`, `red`, `green`
283//! or `blue`, up to 16 points in 0..1 with rising inputs) and `lut <color> <mix>
284//! <path>` (mix 0..1, the path written as a source's is). **Version 43** is the
285//! first dialect with them; a project whose grades have no look is written under
286//! the header it needed before. A LUT file that is missing or malformed does not
287//! stop the load: the clip plays without it and the project names it
288//! ([`crate::Project::lut_problems`]).
289//!
290//! A transform line is `transform <pos_x>:<pos_y>:<scale>:<rotate>:<crop_l>:
291//! <crop_r>:<crop_t>:<crop_b>` ([`crate::transform::TransformParams`]), named by
292//! position exactly as an eq or a colour line is -- the first transform line is
293//! transform 0 -- printed and refused by the same rules: how a clip's picture
294//! sits, is sized, is turned and is trimmed on the canvas, on top of whatever
295//! its fit policy already placed.
296//!
297//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
298//! <color> <fit> <speed> <fade_in> <fade_out> <transition_out> <transform> <visualizer> <viz_paint>`:
299//! which lane the clip is on -- its kind and its 1-based number
300//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
301//! column shows -- then where the clip sits on the timeline, the half-open
302//! source range it plays, the file it plays from, its group id, the eq line it
303//! plays through, the colour line it is graded by (`-` for none of those three)
304//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
305//! `stretch` or `center` ([`crate::scale::FitPolicy`]), how fast it plays,
306//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip
307//! nobody has speeded), and finally its ramp up from silence and ramp down to
308//! it, in timeline frames ([`crate::project::Clip::fade_in`],
309//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), its
310//! cross-dissolve into whatever abuts its end
311//! ([`crate::project::Clip::transition_out`], `0` for a hard cut), and last of
312//! all the transform line it is placed, sized, turned and cropped by, on top
313//! of everything its fit policy already did (`-` for a clip left at its fit
314//! policy's own spot, [`crate::project::Clip::transform`]), a visualizer
315//! flags byte (`0` for an ordinary picture, bit 0 for a waveform of the
316//! source's sound, the rest outline/smooth/fast/tint) and that waveform's
317//! packed look ([`crate::project::Clip::viz_paint`]): hue, sat, strands and
318//! glow in the low four bytes, then the strand colour's own hue and sat,
319//! with the top bit set once a clip has chosen one.
320//! Timeline placement is
321//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
322//! to write for one, and nothing that can disagree about its length. The `<in>`
323//! and `<out>` are *source* frames whatever the speed says: how long the clip is
324//! on the timeline is that range divided by the rate, and is written nowhere.
325//!
326//! A lane is declared by the clips on it, in the order the lanes are displayed
327//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
328//! is the only way an empty lane could still be there on the way back. A lane
329//! number may not skip one of its kind.
330//!
331//! A subtitle lane is a lane like the other two and is written in its place
332//! among them, `sub` for its kind: `sub <lane> <start> <frames> <track>
333//! <in> <out>` ([`crate::project::SubClip`]) -- where the caption sits on the
334//! timeline and how many frames it covers, then which `subtitle` line's words
335//! it shows (by position, the first one is track 0) and the half-open window of
336//! that track it shows, in *microseconds*, which is the clock the cues
337//! themselves are timed in. Two clocks on one line because a subtitle has two:
338//! a placement is in timeline frames like everything else, and a window is in
339//! the file's own time whatever the timeline runs at. A lane holding nothing
340//! has the bare `sub <lane>` line for the reason a video one does, and the
341//! track a caption names has to be one the file declared -- a `sub` line naming
342//! track 3 of a two-track palette is refused here, as a clip naming a source
343//! that is not there is.
344//!
345//! **Version 23** was this without the `flags` lines: such a project has no
346//! lane hidden, muted or locked, which is what every lane of every dialect
347//! before it is.
348//! **Version 22** was this with a 32-bit packed look: such a project's clips
349//! chose no strand colour, which is what the top bit still clear means, and
350//! their value is the low half of the one v23 writes.
351//! **Version 19** was this without the clip's transform field: such a project
352//! places no clip anywhere but its fit policy's own spot, which is what `-`
353//! still means. **Version 18** was that without the clip's transition field:
354//! such a project dissolves no clip into its neighbor, which is what `0` still
355//! means. **Version 17** was this without the clip's two fade fields: such a project
356//! holds no clip anyone has faded, which is what a `0 0` pair still means.
357//! **Version 15** was this without the caption's group field: such a project
358//! holds captions no hand ever grouped, which is every caption there could be.
359//! **Version 14** was that without the `sub` lines: such a project holds no
360//! subtitle lane at all -- its `subtitle` lines are the palette, and where the
361//! words of it were shown was nowhere in the file.
362//! **Version 13** was that without the `encoder` line: such a project takes the
363//! hardware seat where there is one and the software encoder
364//! everywhere else, which is the only choice those projects had.
365//! **Version 12** was that without the `autoproxy` line: such a project makes a
366//! stand-in for every film that wants one the moment it arrives, which is all
367//! any project could do.
368//! **Version 11** was that without the `proxy` line: such a project is cut on
369//! its films themselves, which is all any project could do.
370//! **Version 10** was that without the `tonemap` line: such a project is shown
371//! in the reference rendition, which is the only one there was.
372//! **Version 9** was that without the `subtitle` lines: such a project shows no
373//! subtitles, which is all any project could do.
374//! **Version 8** was that without the `fps` and `limiter` lines and without
375//! the `gain` ones: such a project mixes every lane at unity, limits nothing,
376//! and comes back at the rate its scaffolding source runs at.
377//! **Version 7** was that without the clip's speed field -- every clip of such
378//! a project plays at real time, which is the only rate there was.
379//! **Version 6** was that without the `resolution` line and without the clip's
380//! fit field -- such a project is the size of its first source and letterboxes
381//! nothing, because nothing on it could differ in size. **Version 5** was that
382//! without the colour lines and without the clip's colour
383//! field. **Version 4** was that without the eq lines and without the clip's eq
384//! field. **Version 3** was that without the lane number, and held one video
385//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
386//! well, which is this file's stream 0 -- one per file, whichever audio track
387//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
388//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
389//! cumulatively and copied onto both lanes as one group each, which is exactly
390//! what a v1 timeline meant, and an older file simply equalizes and grades
391//! nothing, and an older one plays everything at real time, and an older one
392//! mixes flat, and an older one shows no subtitles, and an older one is shown
393//! in the reference rendition, and an older one places none of the words it
394//! names, and an older one has no lane hidden, muted or locked -- and saving
395//! any of them writes v24. An older
396//! reader refuses a newer file by name.
397//!
398//! Text because an edit list is a few integers and a path, and a path is
399//! *bytes* on this platform -- a JSON string would have to lossily decode one.
400//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
401//! everything a line-based format cannot carry) and survives round-trip
402//! exactly. Paths under the project file's own directory are written relative
403//! to it, so a folder holding the media and the `.edith` can be moved or
404//! copied anywhere and still open; anything else is absolute.
405//!
406//! The parser is strict and every refusal names its 1-based line: a project
407//! file is generated, so a line it did not generate is a corrupt file, not a
408//! dialect. Structure is checked here (fields, ordering, empty clips,
409//! out-of-range source indexes); whether the files on disk still match the
410//! timeline is [`crate::PlaybackSession::open_project`]'s business.
411//!
412//! Writing goes through `<path>.part` and a rename, as an export does, so an
413//! interrupted save cannot destroy the previous version of the project. The
414//! bytes are fsynced before the rename and the directory after it, so what a
415//! power loss can lose is a whole save, never half of one under the real name.
416
417use std::ffi::OsString;
418use std::io::Write;
419use std::os::unix::ffi::{OsStrExt, OsStringExt};
420use std::path::{Path, PathBuf};
421
422use crate::color::ColorParams;
423use crate::duck::{
424 Duck, MAX_ATTACK_MS, MAX_DEPTH_DB, MAX_RELEASE_MS, MAX_THRESHOLD_DB, MIN_DEPTH_DB,
425 MIN_THRESHOLD_DB, MIN_TIME_MS,
426};
427use crate::eq::{Band, BandKind, EqParams};
428use crate::limiter::Limiter;
429use crate::project::{
430 Chapter, Clip, Deinterlace, GainKey, Marker, MarkerColor, Lane, LaneFlags, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_KEYS,
431 MAX_SPEED_KEYS, MIN_CLIP_GAIN_DB, STILL_DEFAULT_SECS, STILL_MAX_SECS, STILL_MIN_SECS, Source, Speed, SpeedKey, SubClip,
432 Title, check_chapter, check_marker, check_title,
433};
434use crate::scale::FitPolicy;
435use crate::subtitle::SubtitleTrack;
436use crate::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};
437use crate::voice::{Compressor, DeEsser, Gate, NoiseReduction, VoiceFx};
438use crate::text::{Align, HPlace, Outline, Place, TextStyle, Weight};
439use crate::titleanim::{TitleAnim, TitleKey};
440use crate::color::{ColorKey, MAX_COLOR_KEYS};
441use crate::transitions::TransitionKind;
442use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, TransformParams};
443
444/// The newest project format version: the `N` in the `edith N` first line that
445/// [`save`] writes for a project that uses the newest features. A reader refuses any
446/// higher version by name.
447pub const NEWEST_VERSION: u32 = 56;
448
449/// What [`save`] writes. Read support goes back to `edith 1`; see the module
450/// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`].
451const MAGIC: &[u8] = b"edith 56";
452const MAGIC_V55: &[u8] = b"edith 55";
453const MAGIC_V54: &[u8] = b"edith 54";
454const MAGIC_V53: &[u8] = b"edith 53";
455const MAGIC_V52: &[u8] = b"edith 52";
456const MAGIC_V51: &[u8] = b"edith 51";
457const MAGIC_V50: &[u8] = b"edith 50";
458const MAGIC_V49: &[u8] = b"edith 49";
459const MAGIC_V48: &[u8] = b"edith 48";
460const MAGIC_V47: &[u8] = b"edith 47";
461const MAGIC_V46: &[u8] = b"edith 46";
462/// The most bands one equalizer line may declare. A hand-built cascade is a
463/// handful; the cap keeps a crafted line from making every clip run a million
464/// filters.
465const MAX_EQ_BANDS: usize = 64;
466/// The most words one `cuewords` line may carry (a cue is a line or two).
467const MAX_CUE_WORDS: usize = 1_000;
468/// The most sequences (tabs) a project may hold, each a parse of its own.
469const MAX_SEQUENCES: usize = 256;
470/// The most chapters, and the most markers, a project may hold.
471const MAX_LIST_ENTRIES: usize = 100_000;
472
473const MAGIC_V45: &[u8] = b"edith 45";
474const MAGIC_V44: &[u8] = b"edith 44";
475const MAGIC_V43: &[u8] = b"edith 43";
476const MAGIC_V42: &[u8] = b"edith 42";
477const MAGIC_V41: &[u8] = b"edith 41";
478const MAGIC_V40: &[u8] = b"edith 40";
479const MAGIC_V39: &[u8] = b"edith 39";
480const MAGIC_V38: &[u8] = b"edith 38";
481const MAGIC_V37: &[u8] = b"edith 37";
482const MAGIC_V36: &[u8] = b"edith 36";
483const MAGIC_V35: &[u8] = b"edith 35";
484const MAGIC_V34: &[u8] = b"edith 34";
485const MAGIC_V33: &[u8] = b"edith 33";
486const MAGIC_V32: &[u8] = b"edith 32";
487const MAGIC_V31: &[u8] = b"edith 31";
488const MAGIC_V30: &[u8] = b"edith 30";
489const MAGIC_V29: &[u8] = b"edith 29";
490const MAGIC_V28: &[u8] = b"edith 28";
491const MAGIC_V27: &[u8] = b"edith 27";
492const MAGIC_V26: &[u8] = b"edith 26";
493const MAGIC_V25: &[u8] = b"edith 25";
494const MAGIC_V24: &[u8] = b"edith 24";
495const MAGIC_V23: &[u8] = b"edith 23";
496const MAGIC_V22: &[u8] = b"edith 22";
497const MAGIC_V21: &[u8] = b"edith 21";
498const MAGIC_V20: &[u8] = b"edith 20";
499const MAGIC_V19: &[u8] = b"edith 19";
500const MAGIC_V18: &[u8] = b"edith 18";
501const MAGIC_V17: &[u8] = b"edith 17";
502const MAGIC_V16: &[u8] = b"edith 16";
503const MAGIC_V15: &[u8] = b"edith 15";
504const MAGIC_V14: &[u8] = b"edith 14";
505const MAGIC_V13: &[u8] = b"edith 13";
506const MAGIC_V12: &[u8] = b"edith 12";
507const MAGIC_V11: &[u8] = b"edith 11";
508const MAGIC_V10: &[u8] = b"edith 10";
509const MAGIC_V9: &[u8] = b"edith 9";
510const MAGIC_V8: &[u8] = b"edith 8";
511const MAGIC_V7: &[u8] = b"edith 7";
512const MAGIC_V6: &[u8] = b"edith 6";
513const MAGIC_V5: &[u8] = b"edith 5";
514const MAGIC_V4: &[u8] = b"edith 4";
515const MAGIC_V3: &[u8] = b"edith 3";
516const MAGIC_V2: &[u8] = b"edith 2";
517const MAGIC_V1: &[u8] = b"edith 1";
518
519/// What a project file says: an edit list plus where the playhead stood.
520/// Structurally valid by construction -- see [`parse`].
521#[derive(Debug)]
522pub struct Document {
523 /// Paths absolute, relative entries already joined to the file's own
524 /// directory.
525 pub sources: Vec<Source>,
526 /// Every lane, in display order, which is the order
527 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
528 /// `A1` -- for every dialect before v4.
529 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
530 /// What is placed on each lane, in the order `lanes` is in and as long as
531 /// it -- the `sub` lines. Empty for every video and audio lane, which hold
532 /// no [`SubClip`], and for every lane of every dialect before v15, which
533 /// placed no words anywhere ([`crate::Project::with_subs`] takes it back).
534 pub subs: Vec<Vec<SubClip>>,
535 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
536 /// every dialect before v5.
537 pub eq: Vec<EqParams>,
538 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
539 /// every dialect before v6.
540 pub color: Vec<ColorParams>,
541 /// The transform table [`Clip::transform`] indexes into, in file order.
542 /// Empty for every dialect before v20.
543 pub transform: Vec<TransformParams>,
544 /// The project's own picture size. `None` for every dialect before v7 and
545 /// for a v7 file that leaves it out, which both mean "source 0's picture".
546 pub resolution: Option<(u32, u32)>,
547 /// Every lane's own volume in dB, in the order `lanes` is in and as long as
548 /// it; `0.0` for a lane nobody has turned, which is every lane of every
549 /// dialect before v9.
550 pub gains: Vec<f32>,
551 /// Every lane's switches -- hidden, muted, locked -- in the order `lanes` is
552 /// in and as long as it. All clear for every dialect before v24, which had
553 /// no such switches, and for a lane a `flags` line does not name.
554 pub flags: Vec<LaneFlags>,
555 /// Every lane's auto-ducks, in the order `lanes` is in and as long as it;
556 /// empty for every lane but an audio lane somebody has ducked. Each lane
557 /// has at most one duck per key. Empty of every list for every dialect
558 /// before v25, which had no ducks, and at most one per lane before v30.
559 pub ducks: Vec<Vec<Duck>>,
560 /// The title cards and text overlays, in the order the file has them.
561 /// Empty for every dialect before v26, which had none.
562 pub titles: Vec<Title>,
563 /// The chapter markers, in frame order. Empty for every dialect before v34.
564 pub chapters: Vec<Chapter>,
565 /// The comment markers, in frame order. Empty for every dialect before v36.
566 pub markers: Vec<Marker>,
567 /// How burned captions animate, the `capstyle` line. The default (static cues) for every
568 /// dialect before v40.
569 pub caption_style: CaptionStyle,
570 /// Every lane's voice processors, in the order `lanes` is in and as long as it.
571 /// All off for every dialect before v41, and for a lane no `voice` line names.
572 pub voices: Vec<VoiceFx>,
573 /// One display name per lane (empty for none), from the `lanename` lines (v46).
574 pub names: Vec<String>,
575 /// The master limiter. Off for every dialect before v9, and for a v9 file
576 /// that leaves the line out.
577 pub limiter: Limiter,
578 /// The subtitle tracks, as the file names them: the path the cues are in
579 /// and which track of it, which is what [`crate::subtitle::open`] takes.
580 /// Reading them is the loader's business, not this module's -- a `.edith`
581 /// holds no cues. Empty for every dialect before v10.
582 pub subtitles: Vec<(PathBuf, Option<u64>)>,
583 /// The language of a subtitle track, `(track, code)`: the track by its
584 /// position in `subtitles`, the code as the file holds it (ISO 639-2 for
585 /// one set by a person, a container's own tag for an embedded track that
586 /// was not retyped). Empty for every dialect before v33.
587 pub sub_langs: Vec<(usize, String)>,
588 /// The cue overrides, `(track, cue, text)`: the track by its position in
589 /// `subtitles`, the cue by its position in that track. Empty for every
590 /// dialect before v24.
591 pub cue_edits: Vec<(usize, usize, String)>,
592 /// The cues added to a track ([`crate::project::AddedCue`]), each on its
593 /// track's own clock. Empty for every dialect before v29.
594 pub cue_adds: Vec<crate::project::AddedCue>,
595 /// The word times of cues, `(track, cue, words)` with the cue by its position in the track
596 /// as it stands after the edits and additions: the `cuewords` lines (v40). Empty before v40.
597 pub cue_words: Vec<crate::project::CueWordRow>,
598 /// The timeline's frame rate. `None` for every dialect before v9 and for a
599 /// v9 file that leaves it out, which both mean "whatever the scaffolding
600 /// source runs at" -- the inference a project of nothing but stills and
601 /// songs has no answer for (see
602 /// [`crate::PlaybackSession::open_project`]).
603 pub fps: Option<f64>,
604 /// The HDR-to-SDR rendition every clip on an HDR curve is shown in.
605 /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and
606 /// for a v11 file that leaves the line out, which both mean the published
607 /// conversion -- the only one those projects had.
608 pub tone: crate::tonemap::Preset,
609 /// Whether the films are cut on their stand-ins ([`crate::proxy`]). `false`
610 /// for every dialect before v12 and for a v12 file that leaves the line
611 /// out, which both mean the films themselves -- the only thing those
612 /// projects could do.
613 pub proxy: bool,
614 /// Whether an import makes a stand-in for a film that wants one by itself
615 /// ([`crate::proxy`]). `true` for every dialect before v13 and for a v13
616 /// file that leaves the line out, which both mean by itself -- the only
617 /// thing those projects did.
618 pub auto_proxy: bool,
619 /// Which encoder an export writes the picture with
620 /// ([`crate::export::EncoderSeat`]). `Auto` for every dialect before v14 and
621 /// for a v14 file that leaves the line out, which both mean the seat this
622 /// machine has -- the only choice those projects offered.
623 pub encoder: crate::export::EncoderSeat,
624 /// The rate the project's *sound* is mixed and exported at, chosen rather
625 /// than probed. `None` for every dialect before v17 and for a v17 file that
626 /// leaves the line out, which both mean what they always did: the rate of
627 /// the sources' own: the highest rate among the sources that have sound,
628 /// or 48 kHz when every one of them is below 44.1 kHz. Playback and export
629 /// both resample every other source
630 /// to whichever rate this resolves to, exactly as they already resample a
631 /// source shot at another rate than the timeline's -- an explicit choice
632 /// here only changes what that timeline's own rate *is*.
633 pub sample_rate: Option<u32>,
634 pub playhead: u32,
635 /// The active sequence's id and name, from the `seqactive` line (v45). `None` for a file
636 /// that holds one sequence, which is every dialect before v45.
637 pub seq_active: Option<(u32, String)>,
638 /// The tab order, from the `seqorder` line.
639 pub seq_order: Vec<u32>,
640 /// The other sequences, each a complete document of its own (`seq` ... `endseq`).
641 pub sequences: Vec<SeqDoc>,
642 /// The `mcam` lines (v47): a multicam source sequence's id and one angle's name each, in
643 /// angle order. Empty for a file with no multicam clip.
644 pub mcams: Vec<(u32, String)>,
645 /// The library's bins, from the `bin` lines (v51). Empty for a file with none.
646 pub bins: Vec<crate::project::Bin>,
647 /// The project notes, from the `notes` line (v52). Empty for a file with none, and for
648 /// every dialect before v52.
649 pub notes: String,
650 /// The length a still is placed at, from the `still` line (v52). `None` for a file that
651 /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s.
652 pub still_secs: Option<f64>,
653}
654
655/// A parked sequence read off a v45 file.
656#[derive(Debug)]
657pub struct SeqDoc {
658 pub id: u32,
659 pub name: String,
660 pub doc: Document,
661}
662
663/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
664/// already be orphan-free ([`crate::Project::without_orphan_sources`]);
665/// `gains` is one dB per lane in the same order the lanes are in
666/// ([`crate::Project::lane_gains`]) and `subs` is one list of placements per
667/// lane in that same order ([`crate::Project::lane_subs`]).
668///
669/// The same as [`save_flagged`] with every lane's switches clear, for the
670/// callers that have none to write.
671#[allow(clippy::too_many_arguments)]
672pub fn save(
673 path: &Path,
674 sources: &[Source],
675 lanes: &[(LaneKind, Vec<Clip>)],
676 gains: &[f32],
677 subs: &[Vec<SubClip>],
678 subtitles: &[SubtitleTrack],
679 eq: &[EqParams],
680 color: &[ColorParams],
681 transform: &[TransformParams],
682 resolution: (u32, u32),
683 fps: Option<f64>,
684 tone: crate::tonemap::Preset,
685 proxy: bool,
686 auto_proxy: bool,
687 encoder: crate::export::EncoderSeat,
688 limiter: Limiter,
689 sample_rate: Option<u32>,
690 playhead: u32,
691) -> crate::Result<()> {
692 save_flagged(
693 path,
694 sources,
695 lanes,
696 gains,
697 subs,
698 subtitles,
699 eq,
700 color,
701 transform,
702 resolution,
703 fps,
704 tone,
705 proxy,
706 auto_proxy,
707 encoder,
708 limiter,
709 sample_rate,
710 playhead,
711 &[],
712 &[],
713 &[],
714 &[],
715 &[],
716 &[],
717 &[],
718 &CaptionStyle::default(),
719 &[],
720 &[],
721 )
722}
723
724/// The bytes [`save_flagged`] writes, for a caller that assembles a file of several parts
725/// ([`sequenced`]). `dir` is the project's directory, which relative paths are written against.
726#[allow(clippy::too_many_arguments)]
727pub fn encode_flagged(
728 dir: &Path,
729 sources: &[Source],
730 lanes: &[(LaneKind, Vec<Clip>)],
731 gains: &[f32],
732 subs: &[Vec<SubClip>],
733 subtitles: &[SubtitleTrack],
734 eq: &[EqParams],
735 color: &[ColorParams],
736 transform: &[TransformParams],
737 resolution: (u32, u32),
738 fps: Option<f64>,
739 tone: crate::tonemap::Preset,
740 proxy: bool,
741 auto_proxy: bool,
742 encoder: crate::export::EncoderSeat,
743 limiter: Limiter,
744 sample_rate: Option<u32>,
745 playhead: u32,
746 flags: &[LaneFlags],
747 ducks: &[Vec<Duck>],
748 cue_edits: &[(usize, usize, String)],
749 cue_adds: &[crate::project::AddedCue],
750 titles: &[Title],
751 chapters: &[Chapter],
752 markers: &[Marker],
753 caption_style: &CaptionStyle,
754 voices: &[VoiceFx],
755 names: &[String],
756) -> Vec<u8> {
757 let mut bytes = emit(
758 dir,
759 sources,
760 lanes,
761 gains,
762 subs,
763 subtitles,
764 eq,
765 color,
766 transform,
767 resolution,
768 fps,
769 tone,
770 proxy,
771 auto_proxy,
772 encoder,
773 limiter,
774 sample_rate,
775 playhead,
776 );
777 // The cue overrides after the subtitle lines `emit` wrote, which
778 // they name; then the switches, which name lanes, as the gains do.
779 bytes.extend_from_slice(&cue_lines(cue_edits));
780 bytes.extend_from_slice(&cue_add_lines(cue_adds));
781 let cue_words = cue_word_lines(subtitles);
782 bytes.extend_from_slice(&flag_lines(lanes, flags));
783 bytes.extend_from_slice(&duck_lines(lanes, ducks));
784 bytes.extend_from_slice(&title_lines(titles));
785 // The chapters after the titles, and a file that has any is v34 whatever
786 // `emit` picked, and a file with a speed ramp is v35, one with a marker v36, one with a transition kind v37, one with a voice processor v41: the header line is
787 // the one line `emit` wrote that these change, so it is swapped here,
788 // where the lines they need are.
789 let ramped = lanes
790 .iter()
791 .any(|(_, clips)| clips.iter().any(|c| !c.speed_keys.is_empty()));
792 let transitioned = lanes.iter().any(|(_, clips)| {
793 clips.iter().any(|c| c.transition_kind != TransitionKind::Dissolve)
794 });
795 let reversed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.reversed));
796 // ...and one with an opacity or colour animation, or a key easing beyond
797 // linear and `ease`, is v39.
798 let animated = lanes.iter().any(|(_, clips)| clips.iter().any(needs_v39));
799 // ...and one with a project caption style or cue word times is v40.
800 let captioned = *caption_style != CaptionStyle::default() || !cue_words.is_empty();
801 // ...and one with a lane's voice processor is v41.
802 let voiced = voices.iter().any(|v| !v.is_default());
803 // ...and one with a clip's effect is v42.
804 let effected = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.effects.is_empty()));
805 // ...and one with a grade's wheels, curves or LUT is v43.
806 let looked = color.iter().any(|p| p.look != crate::color::Look::default());
807 // ...and one with a stabilised clip is v44.
808 let steadied = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.stabilise.is_some()));
809 // ...and one with a named lane or a clip's deinterlace choice is v46.
810 let named = names.iter().any(|n| !n.is_empty());
811 let deinterlaced = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.deinterlace != Deinterlace::Frame));
812 // ...and one with a multicam clip's angle is v47.
813 let angled = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.angle.is_default()));
814 // ...and one with a generated source (a solid, a gradient, a countdown, bars, an adjustment
815 // layer), a clip's colour label or a switched-off clip is v48.
816 // ...and one with a title's colour, weight, alignment, position or box colour is v49.
817 let styled = titles.iter().any(|t| !title_look_is_default(&t.style));
818 // ...and one with a title's entrance or exit animation is v54.
819 let titled = titles.iter().any(|t| t.in_anim != TitleAnim::None || t.out_anim != TitleAnim::None);
820 let marked = sources.iter().any(|s| crate::generate::is_generated(&s.path))
821 || lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.mark.is_default()));
822 // ...and one with a clip pan or a lane pan is v50.
823 let panned = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pan != 0)) || flags.iter().any(|f| f.pan != 0.0);
824 // ...and one with an effect's keys is v56 (`ekeys`), as is one with a custom bezier key easing.
825 let keyed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty())));
826 // ...and one with a clip's pitch shift is v55.
827 let pitched = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch != 0));
828 // ...and one with a title's own keys is v56 (`ttkeys`).
829 let title_keyed = titles.iter().any(|t| !t.keys.is_empty());
830 let curved = keyed || title_keyed || lanes.iter().any(|(_, clips)| clips.iter().any(has_bezier));
831 if curved || pitched || titled || panned || styled || marked || angled || named || deinterlaced || steadied || looked || effected || voiced || captioned || animated || reversed || transitioned || ramped || !chapters.is_empty() || !markers.is_empty() {
832 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
833 let header = if curved {
834 MAGIC
835 } else if pitched {
836 MAGIC_V55
837 } else if titled {
838 MAGIC_V54
839 } else if panned {
840 MAGIC_V50
841 } else if styled {
842 MAGIC_V49
843 } else if marked {
844 MAGIC_V48
845 } else if angled {
846 MAGIC_V47
847 } else if named || deinterlaced {
848 MAGIC_V46
849 } else if steadied {
850 MAGIC_V44
851 } else if looked {
852 MAGIC_V43
853 } else if effected {
854 MAGIC_V42
855 } else if voiced {
856 MAGIC_V41
857 } else if captioned {
858 MAGIC_V40
859 } else if animated {
860 MAGIC_V39
861 } else if reversed {
862 MAGIC_V38
863 } else if transitioned {
864 MAGIC_V37
865 } else if !markers.is_empty() {
866 MAGIC_V36
867 } else if ramped {
868 MAGIC_V35
869 } else {
870 MAGIC_V34
871 };
872 bytes.splice(..first_end, header.iter().copied());
873 }
874 bytes.extend_from_slice(&chapter_lines(chapters));
875 bytes.extend_from_slice(&marker_lines(markers));
876 bytes.extend_from_slice(&capstyle_line(caption_style));
877 bytes.extend_from_slice(&cue_words);
878 bytes.extend_from_slice(&voice_lines(lanes, voices));
879 bytes.extend_from_slice(&clip_gain_lines(lanes));
880 bytes.extend_from_slice(&gain_key_lines(lanes));
881 bytes.extend_from_slice(&tkey_lines(lanes));
882 bytes.extend_from_slice(&speed_key_lines(lanes));
883 bytes.extend_from_slice(&transition_lines(lanes));
884 bytes.extend_from_slice(&reverse_lines(lanes));
885 bytes.extend_from_slice(&opacity_key_lines(lanes));
886 bytes.extend_from_slice(&color_key_lines(lanes));
887 bytes.extend_from_slice(&effect_lines(lanes));
888 bytes.extend_from_slice(&effect_key_lines(lanes));
889 bytes.extend_from_slice(&look_lines(color, dir));
890 bytes.extend_from_slice(&stab_lines(lanes));
891 bytes.extend_from_slice(&deint_lines(lanes));
892 bytes.extend_from_slice(&lane_name_lines(lanes, names));
893 bytes.extend_from_slice(&angle_lines(lanes));
894 bytes.extend_from_slice(&mark_lines(lanes));
895 bytes.extend_from_slice(&pan_lines(lanes, flags));
896 bytes.extend_from_slice(&pitch_lines(lanes));
897 bytes
898}
899
900/// `main` (a document as [`encode_flagged`] wrote it) with the library's lines after it (v51):
901/// `bin <id> <parent> <name>` for each bin, `srcbin <source> <bin>` for each filed source and
902/// `srcfav <source>` for each starred one. A library with none of these is `main` untouched, so
903/// such a project is the bytes it was before v51.
904/// `current` (a file's first line, without its newline) with `candidate` in its place when
905/// `candidate` is a newer dialect, else `current` untouched. The library and notes lines raise
906/// the header to what they need and never lower it, so a file with effect keys (v56) keeps v56.
907fn raise_header(current: &[u8], candidate: &[u8]) -> Vec<u8> {
908 let version = |h: &[u8]| {
909 std::str::from_utf8(h).ok().and_then(|l| l.strip_prefix("edith ")).and_then(|n| n.parse::<u32>().ok()).unwrap_or(0)
910 };
911 if version(candidate) > version(current) { candidate.to_vec() } else { current.to_vec() }
912}
913
914pub fn binned(mut main: Vec<u8>, sources: &[Source], bins: &[crate::project::Bin]) -> Vec<u8> {
915 let mut lines = Vec::new();
916 for b in bins {
917 lines.extend_from_slice(format!("bin {} {} ", b.id, b.parent).as_bytes());
918 escape_text(&b.name, &mut lines);
919 lines.push(b'\n');
920 }
921 for (i, s) in sources.iter().enumerate() {
922 if s.bin != 0 {
923 lines.extend_from_slice(format!("srcbin {i} {}\n", s.bin).as_bytes());
924 }
925 if s.fav {
926 lines.extend_from_slice(format!("srcfav {i}\n").as_bytes());
927 }
928 }
929 if lines.is_empty() {
930 return main;
931 }
932 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
933 let header = raise_header(&main[..first_end], MAGIC_V51);
934 main.splice(..first_end, header);
935 if main.last() != Some(&b'\n') {
936 main.push(b'\n');
937 }
938 main.extend_from_slice(&lines);
939 main
940}
941
942/// `main` with the project notes and the still length after it (v52): a `notes` line when there
943/// are notes, a `still` line when the length is not the default. A project with neither is `main`
944/// untouched, so it keeps the bytes it had before v52.
945pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64) -> Vec<u8> {
946 let mut lines = Vec::new();
947 if !notes.is_empty() {
948 lines.extend_from_slice(b"notes ");
949 escape_text(notes, &mut lines);
950 lines.push(b'\n');
951 }
952 if still_secs != STILL_DEFAULT_SECS {
953 lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes());
954 }
955 if lines.is_empty() {
956 return main;
957 }
958 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
959 let header = raise_header(&main[..first_end], MAGIC_V52);
960 main.splice(..first_end, header);
961 if main.last() != Some(&b'\n') {
962 main.push(b'\n');
963 }
964 main.extend_from_slice(&lines);
965 main
966}
967
968/// [`save`], with each lane's switches -- `flags` is one entry per lane in the
969/// same order as `lanes`, as `gains` is ([`crate::Project::lane_flags`]).
970#[allow(clippy::too_many_arguments)]
971pub fn save_flagged(
972 path: &Path,
973 sources: &[Source],
974 lanes: &[(LaneKind, Vec<Clip>)],
975 gains: &[f32],
976 subs: &[Vec<SubClip>],
977 subtitles: &[SubtitleTrack],
978 eq: &[EqParams],
979 color: &[ColorParams],
980 transform: &[TransformParams],
981 resolution: (u32, u32),
982 fps: Option<f64>,
983 tone: crate::tonemap::Preset,
984 proxy: bool,
985 auto_proxy: bool,
986 encoder: crate::export::EncoderSeat,
987 limiter: Limiter,
988 sample_rate: Option<u32>,
989 playhead: u32,
990 flags: &[LaneFlags],
991 ducks: &[Vec<Duck>],
992 cue_edits: &[(usize, usize, String)],
993 cue_adds: &[crate::project::AddedCue],
994 titles: &[Title],
995 chapters: &[Chapter],
996 markers: &[Marker],
997 caption_style: &CaptionStyle,
998 voices: &[VoiceFx],
999 names: &[String],
1000) -> crate::Result<()> {
1001 let dir = project_dir(path);
1002 let bytes = encode_flagged(
1003 &dir,
1004 sources,
1005 lanes,
1006 gains,
1007 subs,
1008 subtitles,
1009 eq,
1010 color,
1011 transform,
1012 resolution,
1013 fps,
1014 tone,
1015 proxy,
1016 auto_proxy,
1017 encoder,
1018 limiter,
1019 sample_rate,
1020 playhead,
1021 flags,
1022 ducks,
1023 cue_edits,
1024 cue_adds,
1025 titles,
1026 chapters,
1027 markers,
1028 caption_style,
1029 voices,
1030 names,
1031 );
1032 write_atomic(path, &bytes)
1033}
1034
1035/// One parked sequence as a file holds it: a whole standalone document of its own.
1036pub struct SeqBlock {
1037 pub id: u32,
1038 pub name: String,
1039 pub bytes: Vec<u8>,
1040}
1041
1042/// `main` (the active sequence, as [`encode_flagged`] wrote it) with the other sequences after
1043/// it, as a v45 file: the `seqactive` and `seqorder` lines, then each parked sequence between
1044/// `seq <id> <name>` and `endseq`. The body of each block is a complete document, so its lines
1045/// read exactly as a project file's do.
1046pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[SeqBlock], mcam: &[(u32, Vec<String>)]) -> Vec<u8> {
1047 let mut bytes = main;
1048 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
1049 // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46
1050 // when a part is v46; a newer-only line under an older header is refused.
1051 let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n');
1052 let v56 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1053 let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55));
1054 let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54));
1055 let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53));
1056 let v52 = v53 || is(&bytes, MAGIC_V52) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V52));
1057 let v51 = v52 || is(&bytes, MAGIC_V51) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V51));
1058 let v50 = v51 || is(&bytes, MAGIC_V50) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V50));
1059 let v49 = v50 || is(&bytes, MAGIC_V49) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V49));
1060 let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48));
1061 let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47));
1062 let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46));
1063 let header = if v56 { MAGIC } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 };
1064 bytes.splice(..first_end, header.iter().copied());
1065 bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes());
1066 escape_text(active.1, &mut bytes);
1067 bytes.push(b'\n');
1068 let ids: Vec<String> = order.iter().map(u32::to_string).collect();
1069 bytes.extend_from_slice(format!("seqorder {}\n", ids.join(" ")).as_bytes());
1070 for (id, names) in mcam {
1071 for name in names {
1072 bytes.extend_from_slice(format!("mcam {id} ").as_bytes());
1073 escape_text(name, &mut bytes);
1074 bytes.push(b'\n');
1075 }
1076 }
1077 for b in blocks {
1078 bytes.extend_from_slice(format!("seq {} ", b.id).as_bytes());
1079 escape_text(&b.name, &mut bytes);
1080 bytes.push(b'\n');
1081 bytes.extend_from_slice(&b.bytes);
1082 if bytes.last() != Some(&b'\n') {
1083 bytes.push(b'\n');
1084 }
1085 bytes.extend_from_slice(b"endseq\n");
1086 }
1087 bytes
1088}
1089
1090/// Writes `bytes` to `path` atomically: a `.part` file beside it, synced, renamed over it, and the
1091/// directory synced, so until the rename the old file is still the whole truth.
1092pub fn write_atomic(path: &Path, bytes: &[u8]) -> crate::Result<()> {
1093 let dir = project_dir(path);
1094 let mut part = path.to_path_buf().into_os_string();
1095 part.push(".part");
1096 let part = PathBuf::from(part);
1097 let result = std::fs::File::create(&part)
1098 .and_then(|mut f| {
1099 f.write_all(bytes)?;
1100 f.sync_all()
1101 })
1102 .and_then(|()| std::fs::rename(&part, path))
1103 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
1104 if result.is_err() {
1105 let _ = std::fs::remove_file(&part);
1106 }
1107 result.map_err(Into::into)
1108}
1109
1110pub fn load(path: &Path) -> crate::Result<Document> {
1111 let data = std::fs::read(path)?;
1112 // Relative lines are joined to the directory the project was opened
1113 // through, so the file is reached the way the project was opened; the
1114 // save side compares canonically (`written_path`), so whichever way it
1115 // was opened, a saved source is written relative.
1116 parse(&data, path.parent().unwrap_or(Path::new("")))
1117}
1118
1119/// The form a source or subtitle path is written in: relative to the project's
1120/// directory when the file is inside it, however the path was spelled -- a
1121/// `..` or a symlink on the way in is resolved before the comparison -- and as
1122/// it is otherwise. This is the one rule every save follows.
1123fn written_path(path: &Path, dir: &Path) -> PathBuf {
1124 if let Ok(rel) = path.strip_prefix(dir) {
1125 return rel.to_path_buf();
1126 }
1127 if let Ok(real) = path.canonicalize()
1128 && let Ok(rel) = real.strip_prefix(dir)
1129 {
1130 return rel.to_path_buf();
1131 }
1132 path.to_path_buf()
1133}
1134
1135/// The directory a project file's relative source lines are measured from, in
1136/// the same canonical form [`crate::Project`] keeps its sources in -- without
1137/// that the prefix simply never matches and every line comes out absolute,
1138/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
1139/// a bare filename is `""`). Canonicalizing fails only if the directory does
1140/// not exist, and then the write is about to fail anyway.
1141pub(crate) fn project_dir(path: &Path) -> PathBuf {
1142 let dir = path
1143 .parent()
1144 .filter(|p| !p.as_os_str().is_empty())
1145 .unwrap_or(Path::new("."));
1146 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
1147}
1148
1149/// The `cue` lines: one per retyped cue, after the `subtitle` lines that name
1150/// their tracks. Only a cue somebody has retyped has one, so an unedited project
1151/// is the bytes it was.
1152fn cue_lines(edits: &[(usize, usize, String)]) -> Vec<u8> {
1153 let mut out = Vec::new();
1154 for (track, cue, text) in edits {
1155 out.extend_from_slice(format!("cue {track} {cue} ").as_bytes());
1156 escape_text(text, &mut out);
1157 out.push(b'\n');
1158 }
1159 out
1160}
1161
1162/// The `cuewords` lines (v40): `cuewords <track> <cue> <start_us> <end_us> <word> ...` for each
1163/// cue that has word times, the cue by its position in the track as it stands when saved. The
1164/// times are on the track's own clock; a word has no whitespace, so a space separates fields.
1165fn cue_word_lines(subtitles: &[SubtitleTrack]) -> Vec<u8> {
1166 let mut out = Vec::new();
1167 for (t, track) in subtitles.iter().enumerate() {
1168 for (c, cue) in track.cues.iter().enumerate().filter(|(_, c)| !c.words.is_empty()) {
1169 out.extend_from_slice(format!("cuewords {t} {c}").as_bytes());
1170 for (start, end, word) in &cue.words {
1171 out.extend_from_slice(format!(" {start} {end} ").as_bytes());
1172 escape_text(word, &mut out);
1173 }
1174 out.push(b'\n');
1175 }
1176 }
1177 out
1178}
1179
1180/// The `cueadd` lines: one per cue added to a track, after the `cue` lines, as
1181/// `cueadd <track> <start_us> <end_us> <text>`, the text escaped as a `cue` line's is.
1182fn cue_add_lines(adds: &[crate::project::AddedCue]) -> Vec<u8> {
1183 let mut out = Vec::new();
1184 for a in adds {
1185 out.extend_from_slice(format!("cueadd {} {} {} ", a.track, a.start_us, a.end_us).as_bytes());
1186 escape_text(&a.text, &mut out);
1187 out.push(b'\n');
1188 }
1189 out
1190}
1191
1192/// The `duck` lines: one per duck, in lane order and then in the order the lane
1193/// holds them, the key named as the lanes are (1-based), so a project with none
1194/// is the bytes a v24 one was bar the version line.
1195fn duck_lines(lanes: &[(LaneKind, Vec<Clip>)], ducks: &[Vec<Duck>]) -> Vec<u8> {
1196 let mut out = Vec::new();
1197 let mut audio = 0u32;
1198 for ((kind, _), lane_ducks) in lanes.iter().zip(ducks) {
1199 if *kind != LaneKind::Audio {
1200 continue;
1201 }
1202 audio += 1;
1203 for d in lane_ducks {
1204 out.extend_from_slice(
1205 format!(
1206 "duck audio {audio} {} {:?} {:?} {:?} {:?}\n",
1207 d.under + 1,
1208 d.depth_db,
1209 d.threshold_db,
1210 d.attack_ms,
1211 d.release_ms
1212 )
1213 .as_bytes(),
1214 );
1215 }
1216 }
1217 out
1218}
1219
1220/// The `voice` lines: `voice audio <ord> <processor> <fields>...`, one per processor of an
1221/// audio lane that is not at its default (so a lane nobody has cleaned writes none, and a
1222/// project with none is the bytes a v36 one was bar the version line). The processors:
1223/// `gate <on> <threshold> <attack> <release> <hold> <range>`, `nr <on> <strength> <floor>
1224/// <profile>` (the profile a comma-separated list of dB, or `-`), `comp <on> <threshold>
1225/// <ratio> <attack> <release> <knee> <makeup> <auto>` and `deess <on> <threshold> <amount>
1226/// <lo> <hi>`; `<on>` and `<auto>` are `0` or `1`.
1227fn voice_lines(lanes: &[(LaneKind, Vec<Clip>)], voices: &[VoiceFx]) -> Vec<u8> {
1228 let mut out = String::new();
1229 let mut audio = 0u32;
1230 for ((kind, _), v) in lanes.iter().zip(voices) {
1231 if *kind != LaneKind::Audio {
1232 continue;
1233 }
1234 audio += 1;
1235 let b = |x: bool| u8::from(x);
1236 if v.gate != Gate::DEFAULT {
1237 let g = &v.gate;
1238 out += &format!(
1239 "voice audio {audio} gate {} {:?} {:?} {:?} {:?} {:?}\n",
1240 b(g.on), g.threshold_db, g.attack_ms, g.release_ms, g.hold_ms, g.range_db
1241 );
1242 }
1243 if v.nr != NoiseReduction::default() {
1244 let n = &v.nr;
1245 let profile = if n.profile.is_empty() {
1246 "-".to_string()
1247 } else {
1248 n.profile.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>().join(",")
1249 };
1250 out += &format!("voice audio {audio} nr {} {:?} {:?} {profile}\n", b(n.on), n.strength, n.floor_db);
1251 }
1252 if v.comp != Compressor::DEFAULT {
1253 let c = &v.comp;
1254 out += &format!(
1255 "voice audio {audio} comp {} {:?} {:?} {:?} {:?} {:?} {:?} {}\n",
1256 b(c.on), c.threshold_db, c.ratio, c.attack_ms, c.release_ms, c.knee_db, c.makeup_db, b(c.auto_makeup)
1257 );
1258 }
1259 if v.deess != DeEsser::DEFAULT {
1260 let d = &v.deess;
1261 out += &format!(
1262 "voice audio {audio} deess {} {:?} {:?} {:?} {:?}\n",
1263 b(d.on), d.threshold_db, d.amount, d.lo_hz, d.hi_hz
1264 );
1265 }
1266 }
1267 out.into_bytes()
1268}
1269
1270/// The pan lines (v50): `clippan audio <ord> <index> <pan>` for each audio clip that is not in the
1271/// middle, and `lanepan audio <ord> <pan>` for each audio lane that is not.
1272fn pan_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1273 let mut out = Vec::new();
1274 let mut audio = 0u32;
1275 for (n, (kind, clips)) in lanes.iter().enumerate() {
1276 if *kind != LaneKind::Audio {
1277 continue;
1278 }
1279 audio += 1;
1280 if let Some(f) = flags.get(n).filter(|f| f.pan != 0.0) {
1281 out.extend_from_slice(format!("lanepan audio {audio} {}\n", f.pan).as_bytes());
1282 }
1283 for (idx, c) in clips.iter().enumerate() {
1284 if c.pan != 0 {
1285 out.extend_from_slice(format!("clippan audio {audio} {idx} {}\n", c.pan_value()).as_bytes());
1286 }
1287 }
1288 }
1289 out
1290}
1291
1292/// The pitch lines (v55): `pitch audio <ord> <index> <semitones>` for each audio clip whose
1293/// pitch shift is not `0`.
1294fn pitch_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1295 let mut out = Vec::new();
1296 let mut audio = 0u32;
1297 for (kind, clips) in lanes {
1298 if *kind != LaneKind::Audio {
1299 continue;
1300 }
1301 audio += 1;
1302 for (idx, c) in clips.iter().enumerate() {
1303 if c.pitch != 0 {
1304 out.extend_from_slice(format!("pitch audio {audio} {idx} {}\n", c.pitch).as_bytes());
1305 }
1306 }
1307 }
1308 out
1309}
1310
1311/// The `clipgain` lines: one per clip whose own gain is not unity, as
1312/// `clipgain <kind> <ord> <index> <db>`. `index` counts the lane's clips from
1313/// `0`, in lane order. Written after the lanes they name, and only for a clip
1314/// somebody has turned, so a project with none is the bytes a v26 one was bar
1315/// the version line.
1316fn clip_gain_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1317 let mut out = Vec::new();
1318 let (mut video, mut audio) = (0u32, 0u32);
1319 for (kind, clips) in lanes {
1320 let (keyword, ord) = match kind {
1321 LaneKind::Video => {
1322 video += 1;
1323 ("video", video)
1324 }
1325 LaneKind::Audio => {
1326 audio += 1;
1327 ("audio", audio)
1328 }
1329 LaneKind::Subtitle => continue,
1330 };
1331 for (idx, c) in clips.iter().enumerate() {
1332 if c.gain_db != 0.0 {
1333 out.extend_from_slice(
1334 format!("clipgain {keyword} {ord} {idx} {}\n", c.gain_db).as_bytes(),
1335 );
1336 }
1337 }
1338 }
1339 out
1340}
1341
1342/// The `gainkeys` lines: one per clip with a volume envelope, as
1343/// `gainkeys <kind> <ord> <index> <at>:<db> ...`, the points in source order.
1344/// `kind` and `ord` name the lane the way [`clip_gain_lines`] does; `index`
1345/// counts the lane's clips from `0`. Written after the lanes they name, and
1346/// only for a clip with points, so a project with none is the bytes a v27 one
1347/// was bar the version line.
1348fn gain_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1349 let mut out = Vec::new();
1350 let (mut video, mut audio) = (0u32, 0u32);
1351 for (kind, clips) in lanes {
1352 let (keyword, ord) = match kind {
1353 LaneKind::Video => {
1354 video += 1;
1355 ("video", video)
1356 }
1357 LaneKind::Audio => {
1358 audio += 1;
1359 ("audio", audio)
1360 }
1361 LaneKind::Subtitle => continue,
1362 };
1363 for (idx, c) in clips.iter().enumerate() {
1364 if c.gain_keys.is_empty() {
1365 continue;
1366 }
1367 let points: String = c
1368 .gain_keys
1369 .iter()
1370 .map(|k| match k.ease {
1371 KeyEase::Linear => format!(" {}:{}", k.at, k.db),
1372 ease => format!(" {}:{}:{}", k.at, k.db, ease.token()),
1373 })
1374 .collect();
1375 out.extend_from_slice(format!("gainkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1376 }
1377 }
1378 out
1379}
1380
1381/// The `tkeys` lines: one per clip with a placement animation, as
1382/// `speedkeys <kind> <ord> <index> <at>:<permille> ...`, the keys in frame order. The
1383/// speeds are thousandths, as a clip's own `speed` field is, so they read back exactly.
1384/// Only a clip with keys gets a line, and such a project is a v35 one.
1385fn speed_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1386 let mut out = Vec::new();
1387 let (mut video, mut audio) = (0u32, 0u32);
1388 for (kind, clips) in lanes {
1389 let (keyword, ord) = match kind {
1390 LaneKind::Video => {
1391 video += 1;
1392 ("video", video)
1393 }
1394 LaneKind::Audio => {
1395 audio += 1;
1396 ("audio", audio)
1397 }
1398 LaneKind::Subtitle => continue,
1399 };
1400 for (idx, c) in clips.iter().enumerate() {
1401 if c.speed_keys.is_empty() {
1402 continue;
1403 }
1404 let points: String = c
1405 .speed_keys
1406 .iter()
1407 .map(|k| format!(" {}:{}", k.at, k.speed.permille()))
1408 .collect();
1409 out.extend_from_slice(format!("speedkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1410 }
1411 }
1412 out
1413}
1414
1415/// The `transition` lines: one per clip whose transition is not a dissolve, as
1416/// `transition <kind> <ord> <index> <name>`. Such a project is a v37 one.
1417fn transition_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1418 let mut out = Vec::new();
1419 let (mut video, mut audio) = (0u32, 0u32);
1420 for (kind, clips) in lanes {
1421 let (keyword, ord) = match kind {
1422 LaneKind::Video => {
1423 video += 1;
1424 ("video", video)
1425 }
1426 LaneKind::Audio => {
1427 audio += 1;
1428 ("audio", audio)
1429 }
1430 LaneKind::Subtitle => continue,
1431 };
1432 for (idx, c) in clips.iter().enumerate() {
1433 if c.transition_kind != TransitionKind::Dissolve {
1434 out.extend_from_slice(
1435 format!("transition {keyword} {ord} {idx} {}\n", c.transition_kind.name()).as_bytes(),
1436 );
1437 }
1438 }
1439 }
1440 out
1441}
1442
1443/// Whether a clip needs the v39 dialect: an opacity or colour animation, or a
1444/// key easing that v35 has no word for (`in`, `out`, `hold` on a placement key,
1445/// anything but linear on a volume point).
1446fn needs_v39(c: &Clip) -> bool {
1447 !c.opacity_keys.is_empty()
1448 || !c.color_keys.is_empty()
1449 || c.gain_keys.iter().any(|k| k.ease != KeyEase::Linear)
1450 || c.transform_keys
1451 .iter()
1452 .any(|k| matches!(k.ease, KeyEase::EaseIn | KeyEase::EaseOut | KeyEase::Hold))
1453}
1454
1455/// Whether a clip has a key with a custom bezier easing, which only v56 can
1456/// hold: a placement, opacity, colour, volume or mask key.
1457fn has_bezier(c: &Clip) -> bool {
1458 let bezier = |e: KeyEase| matches!(e, KeyEase::Bezier(_));
1459 c.transform_keys.iter().any(|k| bezier(k.ease))
1460 || c.opacity_keys.iter().any(|k| bezier(k.ease))
1461 || c.color_keys.iter().any(|k| bezier(k.ease))
1462 || c.gain_keys.iter().any(|k| bezier(k.ease))
1463 || c.effects.iter().any(|e| e.keys.iter().any(|k| bezier(k.ease)))
1464}
1465
1466/// One line per video clip that `points` returns something for, as
1467/// `<name> video <ord> <index>{points}`: the shape of the `okeys` and `ckeys` lines.
1468fn video_key_lines(
1469 lanes: &[(LaneKind, Vec<Clip>)],
1470 name: &str,
1471 points: impl Fn(&Clip) -> String,
1472) -> Vec<u8> {
1473 let mut out = Vec::new();
1474 let mut video = 0u32;
1475 for (kind, clips) in lanes {
1476 if *kind != LaneKind::Video {
1477 continue;
1478 }
1479 video += 1;
1480 for (idx, c) in clips.iter().enumerate() {
1481 let points = points(c);
1482 if !points.is_empty() {
1483 out.extend_from_slice(format!("{name} video {video} {idx}{points}\n").as_bytes());
1484 }
1485 }
1486 }
1487 out
1488}
1489
1490/// The `reverse` lines: one per clip that plays backwards, as `reverse <kind> <ord>
1491/// <index>`. Only a reversed clip gets a line, and such a project is a v38 one.
1492fn reverse_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1493 let mut out = Vec::new();
1494 let (mut video, mut audio) = (0u32, 0u32);
1495 for (kind, clips) in lanes {
1496 let (keyword, ord) = match kind {
1497 LaneKind::Video => {
1498 video += 1;
1499 ("video", video)
1500 }
1501 LaneKind::Audio => {
1502 audio += 1;
1503 ("audio", audio)
1504 }
1505 LaneKind::Subtitle => continue,
1506 };
1507 for (idx, _) in clips.iter().enumerate().filter(|(_, c)| c.reversed) {
1508 out.extend_from_slice(format!("reverse {keyword} {ord} {idx}\n").as_bytes());
1509 }
1510 }
1511 out
1512}
1513
1514/// `deint video <ord> <index> <mode>`: one per clip whose mode is not `frame`, and such a
1515/// project is a v46 one.
1516fn deint_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1517 video_key_lines(lanes, "deint", |c| match c.deinterlace {
1518 Deinterlace::Frame => String::new(),
1519 d => format!(" {}", d.name()),
1520 })
1521}
1522
1523/// `lanename <kind> <ord> <name>`: one per lane that has a name.
1524fn lane_name_lines(lanes: &[(LaneKind, Vec<Clip>)], names: &[String]) -> Vec<u8> {
1525 let mut out = Vec::new();
1526 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
1527 for ((kind, _), name) in lanes.iter().zip(names) {
1528 let (keyword, ord) = match kind {
1529 LaneKind::Video => {
1530 video += 1;
1531 ("video", video)
1532 }
1533 LaneKind::Audio => {
1534 audio += 1;
1535 ("audio", audio)
1536 }
1537 LaneKind::Subtitle => {
1538 sub += 1;
1539 ("sub", sub)
1540 }
1541 };
1542 if !name.is_empty() {
1543 out.extend_from_slice(format!("lanename {keyword} {ord} ").as_bytes());
1544 escape_text(name, &mut out);
1545 out.push(b'\n');
1546 }
1547 }
1548 out
1549}
1550
1551/// `stab video <ord> <index> <strength> <crop>`: one per stabilised clip, and such a
1552/// project is a v44 one.
1553fn stab_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1554 video_key_lines(lanes, "stab", |c| {
1555 c.stabilise.map_or(String::new(), |st| format!(" {} {}", st.amount(), st.crop().name()))
1556 })
1557}
1558
1559/// The `mark` lines: one per clip that has a colour label or is switched off, as `mark <kind>
1560/// <ord> <index> <label> <on|off>` with the label 0 to 8. Only such a clip gets a line, and such a
1561/// project is a v48 one.
1562fn mark_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1563 let mut out = Vec::new();
1564 let (mut video, mut audio) = (0u32, 0u32);
1565 for (kind, clips) in lanes {
1566 let (keyword, ord) = match kind {
1567 LaneKind::Video => {
1568 video += 1;
1569 ("video", video)
1570 }
1571 LaneKind::Audio => {
1572 audio += 1;
1573 ("audio", audio)
1574 }
1575 LaneKind::Subtitle => continue,
1576 };
1577 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.mark.is_default()) {
1578 let state = if c.mark.off { "off" } else { "on" };
1579 out.extend_from_slice(format!("mark {keyword} {ord} {idx} {} {state}\n", c.mark.label).as_bytes());
1580 }
1581 }
1582 out
1583}
1584
1585/// The `angle` lines: one per clip that shows another angle than the first, as `angle <kind> <ord>
1586/// <index> <picture> <sound>` with angles counted from 1 and `-` for a sound that follows the
1587/// picture. Only such a clip gets a line, and such a project is a v47 one.
1588fn angle_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1589 let mut out = Vec::new();
1590 let (mut video, mut audio) = (0u32, 0u32);
1591 for (kind, clips) in lanes {
1592 let (keyword, ord) = match kind {
1593 LaneKind::Video => {
1594 video += 1;
1595 ("video", video)
1596 }
1597 LaneKind::Audio => {
1598 audio += 1;
1599 ("audio", audio)
1600 }
1601 LaneKind::Subtitle => continue,
1602 };
1603 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.angle.is_default()) {
1604 let sound = c.angle.audio.map_or("-".to_string(), |a| (u32::from(a) + 1).to_string());
1605 out.extend_from_slice(format!("angle {keyword} {ord} {idx} {} {sound}\n", u32::from(c.angle.video) + 1).as_bytes());
1606 }
1607 }
1608 out
1609}
1610
1611/// `okeys video <ord> <index> <at>:<ease>:<opacity> ...`, the opacity keys in
1612/// source order. Only a clip with keys gets a line, and such a project is a v39 one.
1613fn opacity_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1614 video_key_lines(lanes, "okeys", |c| {
1615 c.opacity_keys
1616 .iter()
1617 .map(|k| format!(" {}:{}:{}", k.at, k.ease.token(), k.opacity))
1618 .collect()
1619 })
1620}
1621
1622/// `ckeys video <ord> <index> <at>:<ease>:<brightness>,<contrast>,<saturation>,<tint> ...`,
1623/// the colour keys in source order. Only a clip with keys gets a line, and such
1624/// a project is a v39 one.
1625fn color_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1626 video_key_lines(lanes, "ckeys", |c| {
1627 c.color_keys
1628 .iter()
1629 .map(|k| {
1630 let p = &k.params;
1631 format!(
1632 " {}:{}:{},{},{},{}",
1633 k.at,
1634 k.ease.token(),
1635 p.brightness,
1636 p.contrast,
1637 p.saturation,
1638 p.tint
1639 )
1640 })
1641 .collect()
1642 })
1643}
1644
1645/// The `effect` lines (v42): `effect video <ord> <index> <kind> <on> <value>...`, one per
1646/// effect of a clip's stack, in stack order. Only a clip with effects gets any.
1647fn effect_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1648 let mut out = String::new();
1649 let mut video = 0u32;
1650 for (kind, clips) in lanes {
1651 if *kind != LaneKind::Video {
1652 continue;
1653 }
1654 video += 1;
1655 for (idx, c) in clips.iter().enumerate() {
1656 for e in &c.effects {
1657 out += &format!("effect video {video} {idx} {} {}", e.kind.name(), u8::from(e.on));
1658 for v in &e.values[..e.kind.params().len()] {
1659 out += &format!(" {v}");
1660 }
1661 out.push('\n');
1662 }
1663 }
1664 }
1665 out.into_bytes()
1666}
1667
1668/// The `ekeys` lines (v56): `ekeys video <ord> <index> <slot> <at>:<ease>:<v0>,<v1>,... ...`,
1669/// the keys of the effect at stack position `slot`, in source order, with one value for each
1670/// of its [`crate::effects::EffectKind::params`]. Only an effect with keys gets a line.
1671fn effect_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1672 let mut out = String::new();
1673 let mut video = 0u32;
1674 for (kind, clips) in lanes {
1675 if *kind != LaneKind::Video {
1676 continue;
1677 }
1678 video += 1;
1679 for (idx, c) in clips.iter().enumerate() {
1680 for (slot, e) in c.effects.iter().enumerate() {
1681 if e.keys.is_empty() {
1682 continue;
1683 }
1684 out += &format!("ekeys video {video} {idx} {slot}");
1685 let count = e.kind.params().len();
1686 for k in &e.keys {
1687 let values: Vec<String> = k.values[..count].iter().map(|v| v.to_string()).collect();
1688 out += &format!(" {}:{}:{}", k.at, k.ease.token(), values.join(","));
1689 }
1690 out.push('\n');
1691 }
1692 }
1693 }
1694 out.into_bytes()
1695}
1696
1697/// The v43 look lines, one group per colour line that has one, named by the
1698/// colour line's position:
1699///
1700/// * `wheels <color> <lift> <gamma> <gain>`, each `<master>:<red>:<green>:<blue>`,
1701/// * `curve <color> <channel> <x>:<y>,<x>:<y>...`, one per channel (`master`,
1702/// `red`, `green`, `blue`) that holds points,
1703/// * `lut <color> <mix> <path>`, the path written as a source's is (relative
1704/// when inside the project's folder) and running to the end of the line.
1705fn look_lines(color: &[ColorParams], dir: &Path) -> Vec<u8> {
1706 let quad = |q: &[f32; 4]| format!("{:?}:{:?}:{:?}:{:?}", q[0], q[1], q[2], q[3]);
1707 let mut out = Vec::new();
1708 for (i, p) in color.iter().enumerate() {
1709 let look = &p.look;
1710 if look.wheels != crate::color::Wheels::default() {
1711 let w = &look.wheels;
1712 out.extend_from_slice(
1713 format!("wheels {i} {} {} {}\n", quad(&w.lift), quad(&w.gamma), quad(&w.gain)).as_bytes(),
1714 );
1715 }
1716 for (c, curve) in look.curves.iter().enumerate() {
1717 if curve.points().is_empty() {
1718 continue;
1719 }
1720 let pts: Vec<String> = curve.points().iter().map(|q| format!("{:?}:{:?}", q[0], q[1])).collect();
1721 out.extend_from_slice(
1722 format!("curve {i} {} {}\n", crate::color::CHANNELS[c], pts.join(",")).as_bytes(),
1723 );
1724 }
1725 if let Some(lut) = look.lut {
1726 out.extend_from_slice(format!("lut {i} {:?} ", look.lut_mix).as_bytes());
1727 escape(&written_path(&lut.path(), dir), &mut out);
1728 out.push(b'\n');
1729 }
1730 }
1731 out
1732}
1733
1734/// A `wheels`, `curve` or `lut` line (v43): see [`look_lines`]. A LUT file that is
1735/// missing or broken still loads -- the clip plays without it and
1736/// [`crate::Project::lut_problems`] names it -- but a malformed line is refused.
1737fn parse_look(head: &[u8], rest: &[u8], n: usize, dir: &Path, doc: &mut Document) -> crate::Result<()> {
1738 let sp = rest.iter().position(|&b| b == b' ').unwrap_or(rest.len());
1739 let at = number(&rest[..sp], n)? as usize;
1740 let rest = rest.get(sp + 1..).unwrap_or(&[]);
1741 let what = String::from_utf8_lossy(head).into_owned();
1742 if at >= doc.color.len() {
1743 return Err(format!("line {n}: {what} names color {at}, and there are {}", doc.color.len()).into());
1744 }
1745 let look = &mut doc.color[at].look;
1746 match head {
1747 b"wheels" => {
1748 let f = fields(rest, 3, "wheels", n)?;
1749 let mut q = [[0f32; 4]; 3];
1750 for (k, field) in f.iter().enumerate() {
1751 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
1752 if parts.len() != 4 {
1753 return Err(format!("line {n}: a wheel wants 4 values").into());
1754 }
1755 for (c, part) in parts.iter().enumerate() {
1756 let v = float(part, n)?;
1757 if !(-1.0..=1.0).contains(&v) {
1758 return Err(format!("line {n}: wheels has a value outside -1..1").into());
1759 }
1760 q[k][c] = v;
1761 }
1762 }
1763 look.wheels = crate::color::Wheels { lift: q[0], gamma: q[1], gain: q[2] };
1764 }
1765 b"curve" => {
1766 let f = fields(rest, 2, "curve", n)?;
1767 let channel = crate::color::CHANNELS
1768 .iter()
1769 .position(|c| c.as_bytes() == f[0])
1770 .ok_or_else(|| format!("line {n}: curve channel {:?} is not master, red, green or blue", String::from_utf8_lossy(f[0])))?;
1771 let mut pts = Vec::new();
1772 for pair in f[1].split(|&b| b == b',') {
1773 let xy: Vec<&[u8]> = pair.split(|&b| b == b':').collect();
1774 if xy.len() != 2 {
1775 return Err(format!("line {n}: a curve point is <x>:<y>").into());
1776 }
1777 pts.push([float(xy[0], n)?, float(xy[1], n)?]);
1778 }
1779 look.curves[channel] = crate::color::Curve::new(&pts).map_err(|e| format!("line {n}: {e}"))?;
1780 }
1781 _ => {
1782 let sp = rest.iter().position(|&b| b == b' ').ok_or_else(|| format!("line {n}: lut wants <mix> <path>"))?;
1783 let mix = float(&rest[..sp], n)?;
1784 if !(0.0..=1.0).contains(&mix) {
1785 return Err(format!("line {n}: lut mix must be 0..=1").into());
1786 }
1787 let path = unescape(&rest[sp + 1..], n)?;
1788 if path.as_os_str().is_empty() {
1789 return Err(format!("line {n}: lut without a path").into());
1790 }
1791 let path = if path.is_absolute() { path } else { dir.join(path) };
1792 look.lut = Some(crate::cube::LutRef::open(&path));
1793 look.lut_mix = mix;
1794 }
1795 }
1796 Ok(())
1797}
1798
1799/// `tkeys <kind> <ord> <index> <at>:<ease>:<pos_x>,<pos_y>,<scale>,<rotate>,<crop_l>,<crop_r>,<crop_t>,<crop_b>,<opacity> ...`,
1800/// the keys in source order. `ease` is `lin` or `ease`. Floats are written the
1801/// way the `transform` table writes them, `{}`, which reads back exactly. Only a
1802/// clip with keys gets a line, and such a project is a v32 one.
1803fn tkey_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1804 let mut out = Vec::new();
1805 let (mut video, mut audio) = (0u32, 0u32);
1806 for (kind, clips) in lanes {
1807 let (keyword, ord) = match kind {
1808 LaneKind::Video => {
1809 video += 1;
1810 ("video", video)
1811 }
1812 LaneKind::Audio => {
1813 audio += 1;
1814 ("audio", audio)
1815 }
1816 LaneKind::Subtitle => continue,
1817 };
1818 for (idx, c) in clips.iter().enumerate() {
1819 if c.transform_keys.is_empty() {
1820 continue;
1821 }
1822 let points: String = c
1823 .transform_keys
1824 .iter()
1825 .map(|k| {
1826 let p = &k.params;
1827 let ease = k.ease.token();
1828 format!(
1829 " {}:{ease}:{},{},{},{},{},{},{},{},{}",
1830 k.at,
1831 p.pos_x,
1832 p.pos_y,
1833 p.scale,
1834 p.rotate,
1835 p.crop_l,
1836 p.crop_r,
1837 p.crop_t,
1838 p.crop_b,
1839 p.opacity
1840 )
1841 })
1842 .collect();
1843 out.extend_from_slice(format!("tkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1844 }
1845 }
1846 out
1847}
1848
1849/// The `chapter` lines: one per chapter, in frame order, as [`save_flagged`]
1850/// writes them after the titles. A project with none writes nothing.
1851fn chapter_lines(chapters: &[Chapter]) -> Vec<u8> {
1852 let mut out = Vec::new();
1853 for c in chapters {
1854 out.extend_from_slice(format!("chapter {} ", c.frame).as_bytes());
1855 escape_text(&c.title, &mut out);
1856 out.push(b'\n');
1857 }
1858 out
1859}
1860
1861/// The `marker` lines, one per marker in frame order, then a `marknote` line for each one
1862/// that has a note, as [`save_flagged`] writes them after the chapters. None for a project with none.
1863/// The `capstyle` line, `capstyle <animation> <rrggbb> <box 0|1> <uppercase 0|1> <words per
1864/// line>`: how burned captions animate. None for the default style, so a project that never
1865/// touched it is the bytes it was before v40, bar the version line.
1866fn capstyle_line(cs: &CaptionStyle) -> Vec<u8> {
1867 if *cs == CaptionStyle::default() {
1868 return Vec::new();
1869 }
1870 let [r, g, b] = cs.highlight;
1871 format!(
1872 "capstyle {} {r:02x}{g:02x}{b:02x} {} {} {}\n",
1873 cs.anim.name(),
1874 u8::from(cs.hl_box),
1875 u8::from(cs.uppercase),
1876 cs.words_per_line
1877 )
1878 .into_bytes()
1879}
1880
1881fn marker_lines(markers: &[Marker]) -> Vec<u8> {
1882 let mut out = Vec::new();
1883 for m in markers {
1884 out.extend_from_slice(format!("marker {} {} {} ", m.frame, m.length, m.color.name()).as_bytes());
1885 escape_text(&m.name, &mut out);
1886 out.push(b'\n');
1887 }
1888 for (i, m) in markers.iter().enumerate().filter(|(_, m)| !m.note.is_empty()) {
1889 out.extend_from_slice(format!("marknote {i} ").as_bytes());
1890 escape_text(&m.note, &mut out);
1891 out.push(b'\n');
1892 }
1893 out
1894}
1895
1896/// The `title` lines: one per title, in list order, as [`save_flagged`] writes
1897/// them. A project with none is the bytes a v25 one was bar the version line.
1898fn title_lines(titles: &[Title]) -> Vec<u8> {
1899 let mut out = Vec::new();
1900 for t in titles {
1901 let outline = match t.style.outline {
1902 Outline::None => "none",
1903 Outline::Thin => "thin",
1904 Outline::Thick => "thick",
1905 };
1906 let place = match t.style.place {
1907 Place::Bottom => "bottom",
1908 Place::Top => "top",
1909 Place::Centre => "centre",
1910 };
1911 out.extend_from_slice(
1912 format!(
1913 "title {} {} {} {} {} {outline} {} {place} ",
1914 t.start,
1915 t.frames,
1916 t.fade_in,
1917 t.fade_out,
1918 t.style.size,
1919 u8::from(t.style.boxed)
1920 )
1921 .as_bytes(),
1922 );
1923 escape_text(&t.text, &mut out);
1924 out.push(b'\n');
1925 }
1926 // A title's colour, weight, alignment, position and box colour, one line per title that has
1927 // any of them off the default, so a project without them is the bytes it was.
1928 for (i, t) in titles.iter().enumerate() {
1929 let st = &t.style;
1930 if title_look_is_default(st) {
1931 continue;
1932 }
1933 let hplace = match st.hplace {
1934 HPlace::Centre => "centre",
1935 HPlace::Left => "left",
1936 HPlace::Right => "right",
1937 };
1938 let align = match st.align {
1939 Align::Centre => "centre",
1940 Align::Left => "left",
1941 Align::Right => "right",
1942 };
1943 let weight = match st.weight {
1944 Weight::Regular => "regular",
1945 Weight::Bold => "bold",
1946 };
1947 let [r, g, b] = st.ink;
1948 let [br, bg, bb, ba] = st.box_color;
1949 out.extend_from_slice(format!("titlestyle {i} {hplace} {align} {weight} {r:02x}{g:02x}{b:02x} {br:02x}{bg:02x}{bb:02x}{ba:02x}\n").as_bytes());
1950 }
1951 // A title's entrance and exit, one line per title that has either.
1952 for (i, t) in titles.iter().enumerate() {
1953 if t.in_anim == TitleAnim::None && t.out_anim == TitleAnim::None {
1954 continue;
1955 }
1956 out.extend_from_slice(format!("titleanim {i} {} {} {}\n", t.in_anim.name(), t.out_anim.name(), t.anim_frames).as_bytes());
1957 }
1958 // A title's own keys, one line per title that has any, after its `titleanim` line.
1959 for (i, t) in titles.iter().enumerate() {
1960 if t.keys.is_empty() {
1961 continue;
1962 }
1963 out.extend_from_slice(format!("ttkeys {i}").as_bytes());
1964 for k in &t.keys {
1965 out.extend_from_slice(format!(" {}:{}:{},{},{},{}", k.at, k.ease.token(), k.x, k.y, k.scale, k.opacity).as_bytes());
1966 }
1967 out.push(b'\n');
1968 }
1969 out
1970}
1971
1972/// Whether a style has none of the v49 title looks: white, regular, centred, on the black box.
1973fn title_look_is_default(st: &TextStyle) -> bool {
1974 let d = TextStyle::default();
1975 st.hplace == d.hplace && st.align == d.align && st.weight == d.weight && st.ink == d.ink && st.box_color == d.box_color
1976}
1977
1978/// The `flags` lines: one per lane that has a switch set, in lane order. Only a
1979/// lane somebody has switched gets one, so a project with none is the bytes a
1980/// v23 one was bar the version line.
1981fn flag_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1982 let mut out = Vec::new();
1983 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
1984 for ((kind, _), f) in lanes.iter().zip(flags) {
1985 let (keyword, ord) = match kind {
1986 LaneKind::Video => {
1987 video += 1;
1988 ("video", video)
1989 }
1990 LaneKind::Audio => {
1991 audio += 1;
1992 ("audio", audio)
1993 }
1994 LaneKind::Subtitle => {
1995 sub += 1;
1996 ("sub", sub)
1997 }
1998 };
1999 let words: Vec<&str> = [
2000 (f.hidden, "hidden"),
2001 (f.muted, "muted"),
2002 (f.locked, "locked"),
2003 ]
2004 .into_iter()
2005 .filter_map(|(on, word)| on.then_some(word))
2006 .collect();
2007 if !words.is_empty() {
2008 out.extend_from_slice(
2009 format!("flags {keyword} {ord} {}\n", words.join(" ")).as_bytes(),
2010 );
2011 }
2012 }
2013 out
2014}
2015
2016#[allow(clippy::too_many_arguments)]
2017fn emit(
2018 dir: &Path,
2019 sources: &[Source],
2020 lanes: &[(LaneKind, Vec<Clip>)],
2021 gains: &[f32],
2022 subs: &[Vec<SubClip>],
2023 subtitles: &[SubtitleTrack],
2024 eq: &[EqParams],
2025 color: &[ColorParams],
2026 transform: &[TransformParams],
2027 resolution: (u32, u32),
2028 fps: Option<f64>,
2029 tone: crate::tonemap::Preset,
2030 proxy: bool,
2031 auto_proxy: bool,
2032 encoder: crate::export::EncoderSeat,
2033 limiter: Limiter,
2034 sample_rate: Option<u32>,
2035 playhead: u32,
2036) -> Vec<u8> {
2037 let mut out = Vec::new();
2038 // The file says which dialect it is by whether it needs the newest one:
2039 // a transform's opacity is the only thing v31 adds, so a project without
2040 // one is the bytes a v30 project always was, bar none, and an older reader
2041 // still opens it.
2042 // The newest dialect is only for a project that has placement keys
2043 // (`tkeys` lines, [`tkeys_lines`]); one with opacity alone is still v31.
2044 let needs_v33 = subtitles.iter().any(|t| !t.language.is_empty());
2045 let needs_v32 = lanes
2046 .iter()
2047 .any(|(_, clips)| clips.iter().any(|c| !c.transform_keys.is_empty()));
2048 let needs_v31 = transform.iter().any(|p| p.opacity != 1.0);
2049 out.extend_from_slice(if needs_v33 {
2050 MAGIC_V33
2051 } else if needs_v32 {
2052 MAGIC_V32
2053 } else if needs_v31 {
2054 MAGIC_V31
2055 } else {
2056 MAGIC_V30
2057 });
2058 out.push(b'\n');
2059 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
2060 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
2061 // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read
2062 // back as the very number, or every clip on it lands on another frame.
2063 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
2064 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
2065 }
2066 // Beside it, and by the same rule: a project nobody chose a sound rate for
2067 // is the mix the source's own probe always gave it, which is what leaving
2068 // this line out still means.
2069 if let Some(rate) = sample_rate.filter(|&r| (1_000..=384_000).contains(&r)) {
2070 out.extend_from_slice(format!("samplerate {rate}\n").as_bytes());
2071 }
2072 // Beside the rate, and written only when it is not the default: a project
2073 // holding no HDR media has nothing to say here, and saying nothing is what
2074 // a v10 file already said.
2075 if tone != crate::tonemap::Preset::default() {
2076 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
2077 }
2078 // Beside it and by the same rule: a project cut on the films themselves --
2079 // every project before there were stand-ins -- says nothing here.
2080 if proxy {
2081 out.extend_from_slice(b"proxy on\n");
2082 }
2083 // Beside it and by the same rule the other way up: making them by itself is
2084 // what every project before this line did, so only a project told to stop
2085 // has anything to say here.
2086 if !auto_proxy {
2087 out.extend_from_slice(b"autoproxy off\n");
2088 }
2089 // ...and which encoder writes the picture, by the same rule again: `auto`
2090 // is what every project before this line did, so only a project whose owner
2091 // picked a seat says anything here.
2092 if encoder != crate::export::EncoderSeat::default() {
2093 out.extend_from_slice(format!("encoder {}\n", encoder.name()).as_bytes());
2094 }
2095 // Written only when it is not the default, so a project nobody has limited
2096 // is the same bytes it was in v8 bar the version line.
2097 if limiter != Limiter::default() {
2098 out.extend_from_slice(
2099 format!(
2100 "limiter {:?} {}\n",
2101 limiter.ceiling_db,
2102 match limiter.on {
2103 true => "on",
2104 false => "off",
2105 }
2106 )
2107 .as_bytes(),
2108 );
2109 }
2110 for s in sources {
2111 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
2112 escape(&written_path(&s.path, dir), &mut out);
2113 out.push(b'\n');
2114 }
2115 // The subtitle tracks, by reference: which track of which file, and never
2116 // the cues (see the module docs). Beside the sources because that is what
2117 // they are -- a file this project reads from -- although nothing indexes
2118 // them and their order is only the order they were added in.
2119 for t in subtitles {
2120 let track = t.track.map_or("-".to_string(), |n| n.to_string());
2121 out.extend_from_slice(format!("subtitle {track} ").as_bytes());
2122 escape(&written_path(&t.path, dir), &mut out);
2123 out.push(b'\n');
2124 }
2125 // The language of each track that has one, as `sublang` lines after the
2126 // subtitle lines they name: a standalone file's is set by an import or a
2127 // retype, and an embedded track's is its container's until a retype
2128 // replaces it. Only a track with one is written, and the header only says
2129 // v33 when one is, so a project with none is written exactly as before.
2130 for (track, t) in subtitles.iter().enumerate() {
2131 if t.language.is_empty() {
2132 continue;
2133 }
2134 out.extend_from_slice(format!("sublang {track} ").as_bytes());
2135 escape_text(&t.language, &mut out);
2136 out.push(b'\n');
2137 }
2138 // Before the clips, for the reason the sources are: a clip names one by the
2139 // position of its line, so the line has to be there first.
2140 for params in eq {
2141 out.extend_from_slice(b"eq");
2142 for b in &params.bands {
2143 // `{:?}` rather than `{}`: it is the formatting that promises the
2144 // shortest string parsing back to this exact f32, and it never
2145 // prints a bare integer, which would read as another field's shape.
2146 let kind = match b.kind {
2147 BandKind::LowShelf => "ls",
2148 BandKind::Peak => "pk",
2149 BandKind::HighShelf => "hs",
2150 BandKind::LowCut => "lc",
2151 BandKind::HighCut => "hc",
2152 };
2153 out.extend_from_slice(
2154 format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
2155 );
2156 }
2157 out.push(b'\n');
2158 }
2159 // ...and the colour table, for the same reason and by the same rules.
2160 for p in color {
2161 out.extend_from_slice(
2162 format!(
2163 "color {:?}:{:?}:{:?}:{:?}\n",
2164 p.brightness, p.contrast, p.saturation, p.tint
2165 )
2166 .as_bytes(),
2167 );
2168 }
2169 // ...and the transform table, for the same reason and by the same rules.
2170 for p in transform {
2171 let mut line = format!(
2172 "transform {:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}",
2173 p.pos_x, p.pos_y, p.scale, p.rotate, p.crop_l, p.crop_r, p.crop_t, p.crop_b
2174 );
2175 // The ninth field only where it says something: an opacity of 1 is the
2176 // eight-field line every dialect since v20 wrote.
2177 if p.opacity != 1.0 {
2178 line.push_str(&format!(":{:?}", p.opacity));
2179 }
2180 line.push('\n');
2181 out.extend_from_slice(line.as_bytes());
2182 }
2183 // Lane by lane rather than interleaved by time: a lane reads as a list, the
2184 // parser gets its sortedness check for free from the order it is in, and
2185 // the lanes come back out in the order they are displayed in.
2186 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
2187 for (at, (kind, clips)) in lanes.iter().enumerate() {
2188 let (keyword, ord) = match kind {
2189 LaneKind::Video => {
2190 video += 1;
2191 ("video", video)
2192 }
2193 LaneKind::Audio => {
2194 audio += 1;
2195 ("audio", audio)
2196 }
2197 LaneKind::Subtitle => {
2198 subtitle += 1;
2199 ("sub", subtitle)
2200 }
2201 };
2202 // A subtitle lane holds no `Clip` at all ([`LaneKind::Subtitle`]): what
2203 // is on it is in `subs`, one list per lane and in step with this one,
2204 // and it is written here so the lane comes back in its place among the
2205 // others.
2206 if *kind == LaneKind::Subtitle {
2207 let placed = subs.get(at).map_or(&[][..], Vec::as_slice);
2208 if placed.is_empty() {
2209 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2210 }
2211 for s in placed {
2212 // The group field only when the caption is in one, for the
2213 // clip line's reason: a project nobody grouped a caption in is
2214 // the same bytes it was in v15.
2215 let link = s.link.map_or(String::new(), |l| format!(" {l}"));
2216 out.extend_from_slice(
2217 format!(
2218 "{keyword} {ord} {} {} {} {} {}{link}\n",
2219 s.start, s.frames, s.track, s.in_us, s.out_us
2220 )
2221 .as_bytes(),
2222 );
2223 }
2224 continue;
2225 }
2226 // A lane is declared by its clips; one holding nothing has to say so on
2227 // a line of its own, or the lane itself would not survive the round trip.
2228 if clips.is_empty() {
2229 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2230 }
2231 for c in clips {
2232 let link = c.link.map_or("-".to_string(), |l| l.to_string());
2233 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
2234 let color = c.color.map_or("-".to_string(), |e| e.to_string());
2235 let transform = c.transform.map_or("-".to_string(), |e| e.to_string());
2236 out.extend_from_slice(
2237 format!(
2238 "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {} {} {transform} {} {}\n",
2239 c.start,
2240 c.in_frame,
2241 c.out_frame,
2242 c.source,
2243 fit_name(c.fit),
2244 c.speed.permille(),
2245 c.fade_in,
2246 c.fade_out,
2247 c.transition_out,
2248 c.visualizer,
2249 c.viz_paint,
2250 )
2251 .as_bytes(),
2252 );
2253 }
2254 }
2255 // After the lanes, not before them: a gain line names a lane that has to be
2256 // there already, and a lane is declared by its own lines. Only the lanes
2257 // somebody has turned get one.
2258 let (mut video, mut audio) = (0, 0);
2259 for ((kind, _), &db) in lanes.iter().zip(gains) {
2260 let (keyword, ord) = match kind {
2261 LaneKind::Video => {
2262 video += 1;
2263 ("video", video)
2264 }
2265 LaneKind::Audio => {
2266 audio += 1;
2267 ("audio", audio)
2268 }
2269 // In the list -- the two are zipped, so it has to be -- and never
2270 // written: a subtitle lane has no volume at all
2271 // (`Project::set_lane_gain_db` refuses one), so its entry is the
2272 // `0.0` no lane writes a line for.
2273 LaneKind::Subtitle => continue,
2274 };
2275 if db != 0.0 {
2276 out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes());
2277 }
2278 }
2279 out
2280}
2281
2282fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
2283 // One trailing newline is the line terminator of the last line, not an
2284 // empty line -- any further one is, and is refused below.
2285 let body = data.strip_suffix(b"\n").unwrap_or(data);
2286 let mut lines = body.split(|&b| b == b'\n').enumerate();
2287 let (_, first) = lines.next().unwrap_or((0, &[]));
2288 let v1 = first == MAGIC_V1;
2289 // The dialects that wrote a source line without its stream field. Reading
2290 // one is the whole of what "an old project still opens" means here.
2291 let streamless = v1 || first == MAGIC_V2;
2292 // The one that carries a clip's volume envelope, as `gainkeys` lines...
2293 // The one that lets a lane be ducked under several keys, as several `duck`
2294 // lines naming one lane; a v29 reader refuses it by name.
2295 // The one that carries a transform's opacity, as a ninth field on a
2296 // `transform` line; a v30 reader refuses it by its field count.
2297 // The one that carries a clip's placement animation, as `tkeys` lines...
2298 // The one that carries a clip's stabilisation, as `stab` lines...
2299 // The one that carries a clip's pitch shift, as `pitch` lines...
2300 let v56 = first == MAGIC;
2301 let v55 = v56 || first == MAGIC_V55;
2302 let v54 = v55 || first == MAGIC_V54;
2303 let v53 = v54 || first == MAGIC_V53;
2304 let v52 = v53 || first == MAGIC_V52;
2305 let v51 = v52 || first == MAGIC_V51;
2306 let v50 = v51 || first == MAGIC_V50;
2307 let v49 = v50 || first == MAGIC_V49;
2308 let v48 = v49 || first == MAGIC_V48;
2309 let v47 = v48 || first == MAGIC_V47;
2310 let v46 = v47 || first == MAGIC_V46;
2311 let v45 = v46 || first == MAGIC_V45;
2312 let v44 = v45 || first == MAGIC_V44;
2313 let v43 = v44 || first == MAGIC_V43;
2314 let v42 = v43 || first == MAGIC_V42;
2315 let v41 = v42 || first == MAGIC_V41;
2316 let v40 = v41 || first == MAGIC_V40;
2317 let v39 = v40 || first == MAGIC_V39;
2318 let v38 = v39 || first == MAGIC_V38;
2319 let v37 = v38 || first == MAGIC_V37;
2320 let v36 = v37 || first == MAGIC_V36;
2321 let v35 = v36 || first == MAGIC_V35;
2322 let v34 = v35 || first == MAGIC_V34;
2323 let v33 = v34 || first == MAGIC_V33;
2324 let v32 = v33 || first == MAGIC_V32;
2325 let v31 = v32 || first == MAGIC_V31;
2326 let v30 = v31 || first == MAGIC_V30;
2327 let v29 = v30 || first == MAGIC_V29;
2328 let v28 = v29 || first == MAGIC_V28;
2329 // The one that carries a clip's own gain in dB, as `clipgain` lines...
2330 let v27 = v28 || first == MAGIC_V27;
2331 // The one that carries the title cards and text overlays...
2332 let v26 = v27 || first == MAGIC_V26;
2333 // The one that says which lanes are ducked under which...
2334 let v25 = v26 || first == MAGIC_V25;
2335 // The one that says which lanes are hidden, muted or locked...
2336 let v24 = v25 || first == MAGIC_V24;
2337 // The one that carries a strand colour of its own above the packed
2338 // visualizer paint (hue/sat, with the top bit as the flag)...
2339 let v23 = v24 || first == MAGIC_V23;
2340 // The one that carries packed visualizer paint (hue/sat/strands/glow)...
2341 let v22 = v23 || first == MAGIC_V22;
2342 // The one that carries per-clip visualizer flags...
2343 let v21 = v22 || first == MAGIC_V21;
2344 // The one that carries a per-clip transform (position/scale/rotate/crop)...
2345 let v20 = v21 || first == MAGIC_V20;
2346 // ...the one that carries a per-clip cross-dissolve into its successor...
2347 let v19 = v20 || first == MAGIC_V19;
2348 // ...the one that carries a per-clip fade envelope...
2349 let v18 = v19 || first == MAGIC_V18;
2350 // ...the one that carries an explicit sound rate...
2351 let v17 = v18 || first == MAGIC_V17;
2352 // ...the one whose captions may carry a group id...
2353 let v16 = v17 || first == MAGIC_V16;
2354 // ...the one that places the words it names...
2355 let v15 = v16 || first == MAGIC_V15;
2356 // ...the ones that say which encoder an export takes...
2357 let v14 = v15 || first == MAGIC_V14;
2358 // ...the ones that say whether the stand-ins are made by themselves...
2359 let v13 = v14 || first == MAGIC_V13;
2360 // ...the ones that say whether it is cut on stand-ins...
2361 let v12 = v13 || first == MAGIC_V12;
2362 // ...the ones that carry an HDR rendition...
2363 let v11 = v12 || first == MAGIC_V11;
2364 // ...the ones that carry subtitle tracks...
2365 let v10 = v11 || first == MAGIC_V10;
2366 // ...the ones that carry the mix -- lane volumes, the master limiter and
2367 // the rate the timeline was cut at...
2368 let v9 = v10 || first == MAGIC_V9;
2369 // ...the ones that carry a per-clip speed...
2370 let v8 = v9 || first == MAGIC_V8;
2371 // ...the ones that carry a project resolution and per-clip fit policies...
2372 let v7 = v8 || first == MAGIC_V7;
2373 // ...the ones that carry colour grades...
2374 let v6 = v7 || first == MAGIC_V6;
2375 // ...the ones that carry equalizer settings...
2376 let v5 = v6 || first == MAGIC_V5;
2377 // ...and the ones that number their lanes. Every older one held two.
2378 let numbered = v5 || first == MAGIC_V4;
2379 if !numbered && !streamless && first != MAGIC_V3 {
2380 return Err(match first.strip_prefix(b"edith ") {
2381 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
2382 None => "line 1: not an edith file".to_string(),
2383 }
2384 .into());
2385 }
2386
2387 let mut doc = Document {
2388 sources: Vec::new(),
2389 // v4 on declares its lanes as they come; every dialect before it held
2390 // exactly `V1` and `A1`, either of which could be empty.
2391 lanes: if numbered {
2392 Vec::new()
2393 } else {
2394 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
2395 },
2396 // Resized to the lanes as they arrive, and once more at the end, so a
2397 // caller may zip the two exactly as it zips the gains. Nothing before
2398 // v15 places a word anywhere: those projects have the palette and no
2399 // subtitle lane to put any of it on.
2400 subs: Vec::new(),
2401 // Nothing before v5 equalizes anything, and nothing before v6 grades.
2402 eq: Vec::new(),
2403 color: Vec::new(),
2404 // Nothing before v20 places any clip anywhere but its fit policy's own
2405 // spot: the identity transform is what leaving a clip's index out
2406 // still means.
2407 transform: Vec::new(),
2408 // Nothing before v7 has a resolution of its own: source 0's picture is
2409 // what those projects were, and `None` is how the loader is told so.
2410 resolution: None,
2411 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
2412 // no limiter, and the rate inferred from the scaffold as it always was.
2413 gains: Vec::new(),
2414 // Nothing before v24 could hide, mute or lock a lane: every lane is
2415 // showing, audible and unlocked, which is what leaving a line out means.
2416 flags: Vec::new(),
2417 // Nothing before v25 ducks a lane under another: every lane plays at
2418 // its own level, which is what leaving a line out means.
2419 ducks: Vec::new(),
2420 titles: Vec::new(),
2421 chapters: Vec::new(),
2422 markers: Vec::new(),
2423 caption_style: CaptionStyle::default(),
2424 voices: Vec::new(),
2425 names: Vec::new(),
2426 // Nothing before v10 shows a subtitle, and nothing before v11 was shown
2427 // in any rendition but the published one.
2428 subtitles: Vec::new(),
2429 sub_langs: Vec::new(),
2430 cue_edits: Vec::new(),
2431 cue_adds: Vec::new(),
2432 cue_words: Vec::new(),
2433 limiter: Limiter::default(),
2434 tone: crate::tonemap::Preset::default(),
2435 proxy: false,
2436 // ...and nothing before v13 could be told *not* to make one: an import
2437 // that wanted a stand-in got one, which is what leaving the line out
2438 // still means.
2439 auto_proxy: true,
2440 // ...and nothing before v14 could be told *which* encoder: an export
2441 // took the seat this machine had, which is what leaving the line out
2442 // still means.
2443 encoder: crate::export::EncoderSeat::default(),
2444 fps: None,
2445 // Nothing before v17 chose a sound rate: the source's own probe is
2446 // still what the mix is cut at, which is what `None` means everywhere
2447 // else it reaches (`PlaybackSession::open_project`).
2448 sample_rate: None,
2449 playhead: 0,
2450 seq_active: None,
2451 seq_order: Vec::new(),
2452 sequences: Vec::new(),
2453 mcams: Vec::new(),
2454 bins: Vec::new(),
2455 notes: String::new(),
2456 still_secs: None,
2457 };
2458 // The block of a parked sequence being read: its id, name and the lines so far.
2459 let mut block: Option<(u32, String, Vec<u8>)> = None;
2460 let mut playhead_seen = false;
2461 // Where the next v1 clip is placed: that dialect had no `start` field, the
2462 // clips simply queued up.
2463 let mut queued = 0u32;
2464 for (i, line) in lines {
2465 let n = i + 1;
2466 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
2467 Some(at) => (&line[..at], &line[at + 1..]),
2468 None => (line, &line[line.len()..]),
2469 };
2470 if let Some((id, name, buf)) = block.as_mut() {
2471 if line == b"endseq" {
2472 if doc.sequences.len() >= MAX_SEQUENCES {
2473 return Err(format!("line {n}: a project holds at most {MAX_SEQUENCES} sequences").into());
2474 }
2475 let sub = parse(buf, dir).map_err(|e| format!("sequence \"{name}\": {e}"))?;
2476 doc.sequences.push(SeqDoc { id: *id, name: std::mem::take(name), doc: sub });
2477 block = None;
2478 } else {
2479 buf.extend_from_slice(line);
2480 buf.push(b'\n');
2481 }
2482 continue;
2483 }
2484 match keyword {
2485 b"seqactive" if v45 => {
2486 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2487 let id = number(id, n)?;
2488 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2489 doc.seq_active = Some((id, name));
2490 }
2491 b"seqorder" if v45 => {
2492 for f in rest.split(|&b| b == b' ').filter(|f| !f.is_empty()) {
2493 if doc.seq_order.len() >= MAX_SEQUENCES {
2494 return Err(format!("line {n}: seqorder names more than {MAX_SEQUENCES} sequences").into());
2495 }
2496 doc.seq_order.push(number(f, n)?);
2497 }
2498 }
2499 b"seq" if v45 => {
2500 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2501 let id = number(id, n)?;
2502 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2503 block = Some((id, name, Vec::new()));
2504 }
2505 b"playhead" => {
2506 if playhead_seen || !doc.sources.is_empty() {
2507 return Err(
2508 format!("line {n}: playhead belongs once, before the sources").into(),
2509 );
2510 }
2511 doc.playhead = number(rest, n)?;
2512 playhead_seen = true;
2513 }
2514 b"resolution" if v7 => {
2515 if doc.resolution.is_some() || !doc.sources.is_empty() {
2516 return Err(
2517 format!("line {n}: resolution belongs once, before the sources").into(),
2518 );
2519 }
2520 let f = fields(rest, 2, "resolution", n)?;
2521 let (width, height) = (number(f[0], n)?, number(f[1], n)?);
2522 // The same bound the keystroke has (`crate::is_resolution`):
2523 // unbounded here, this line reached `open_black` and panicked
2524 // the open with a capacity overflow.
2525 if !crate::is_resolution(width, height) {
2526 return Err(format!("line {n}: {width}x{height} is not a picture").into());
2527 }
2528 doc.resolution = Some((width, height));
2529 }
2530 b"fps" if v9 => {
2531 if doc.fps.is_some() || !doc.sources.is_empty() {
2532 return Err(format!("line {n}: fps belongs once, before the sources").into());
2533 }
2534 let f = fields(rest, 1, "fps", n)?;
2535 let fps = std::str::from_utf8(f[0])
2536 .ok()
2537 .and_then(|s| s.parse::<f64>().ok())
2538 .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0)
2539 .ok_or_else(|| {
2540 format!(
2541 "line {n}: {:?} is not a frame rate",
2542 String::from_utf8_lossy(f[0])
2543 )
2544 })?;
2545 doc.fps = Some(fps);
2546 }
2547 b"samplerate" if v17 => {
2548 if doc.sample_rate.is_some() || !doc.sources.is_empty() {
2549 return Err(
2550 format!("line {n}: samplerate belongs once, before the sources").into(),
2551 );
2552 }
2553 let f = fields(rest, 1, "samplerate", n)?;
2554 let rate = number(f[0], n)?;
2555 if !(1_000..=384_000).contains(&rate) {
2556 return Err(format!("line {n}: {rate} Hz is not a sound rate").into());
2557 }
2558 doc.sample_rate = Some(rate);
2559 }
2560 b"tonemap" if v11 => {
2561 if !doc.sources.is_empty() {
2562 return Err(
2563 format!("line {n}: tonemap belongs once, before the sources").into(),
2564 );
2565 }
2566 let f = fields(rest, 1, "tonemap", n)?;
2567 doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| {
2568 format!(
2569 "line {n}: {:?} is not a tone map",
2570 String::from_utf8_lossy(f[0])
2571 )
2572 })?;
2573 }
2574 b"proxy" if v12 => {
2575 if !doc.sources.is_empty() {
2576 return Err(format!("line {n}: proxy belongs once, before the sources").into());
2577 }
2578 let f = fields(rest, 1, "proxy", n)?;
2579 doc.proxy = match f[0] {
2580 b"on" => true,
2581 b"off" => false,
2582 other => {
2583 return Err(format!(
2584 "line {n}: proxy is on or off, not {:?}",
2585 String::from_utf8_lossy(other)
2586 )
2587 .into());
2588 }
2589 };
2590 }
2591 b"autoproxy" if v13 => {
2592 if !doc.sources.is_empty() {
2593 return Err(
2594 format!("line {n}: autoproxy belongs once, before the sources").into(),
2595 );
2596 }
2597 let f = fields(rest, 1, "autoproxy", n)?;
2598 doc.auto_proxy = match f[0] {
2599 b"on" => true,
2600 b"off" => false,
2601 other => {
2602 return Err(format!(
2603 "line {n}: autoproxy is on or off, not {:?}",
2604 String::from_utf8_lossy(other)
2605 )
2606 .into());
2607 }
2608 };
2609 }
2610 b"encoder" if v14 => {
2611 if !doc.sources.is_empty() {
2612 return Err(
2613 format!("line {n}: encoder belongs once, before the sources").into(),
2614 );
2615 }
2616 let f = fields(rest, 1, "encoder", n)?;
2617 doc.encoder = crate::export::EncoderSeat::from_name(f[0]).ok_or_else(|| {
2618 format!(
2619 "line {n}: encoder is auto, hardware or software, not {:?}",
2620 String::from_utf8_lossy(f[0])
2621 )
2622 })?;
2623 }
2624 b"limiter" if v9 => {
2625 if !doc.sources.is_empty() {
2626 return Err(
2627 format!("line {n}: limiter belongs once, before the sources").into(),
2628 );
2629 }
2630 let f = fields(rest, 2, "limiter", n)?;
2631 let on = match f[1] {
2632 b"on" => true,
2633 b"off" => false,
2634 other => {
2635 return Err(format!(
2636 "line {n}: limiter is on or off, not {:?}",
2637 String::from_utf8_lossy(other)
2638 )
2639 .into());
2640 }
2641 };
2642 // Through the same clamp a nudge goes through: a hand-written
2643 // ceiling above full scale is a ceiling that limits nothing.
2644 doc.limiter = Limiter {
2645 on,
2646 ..Limiter::default()
2647 }
2648 .with_ceiling(float(f[0], n)?);
2649 }
2650 // After the lanes it names, which is where `emit` writes it: a lane
2651 // is declared by its own lines, and a gain declares nothing.
2652 b"gain" if v9 => {
2653 let f = fields(rest, 3, "gain", n)?;
2654 let kind = match f[0] {
2655 b"video" => LaneKind::Video,
2656 b"audio" => LaneKind::Audio,
2657 other => {
2658 return Err(format!(
2659 "line {n}: gain names {:?}, not a lane kind",
2660 String::from_utf8_lossy(other)
2661 )
2662 .into());
2663 }
2664 };
2665 let ord = number(f[1], n)?;
2666 let at = doc
2667 .lanes
2668 .iter()
2669 .enumerate()
2670 .filter(|(_, (k, _))| *k == kind)
2671 .nth(ord.saturating_sub(1) as usize)
2672 .map(|(at, _)| at)
2673 .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?;
2674 doc.gains.resize(doc.lanes.len(), 0.0);
2675 doc.gains[at] = float(f[2], n)?;
2676 }
2677 // After the lanes, for the reason a gain is: it names one. A line
2678 // carries the switches that are set, in any order and each once, and
2679 // a switch the kind of lane cannot have is refused by name.
2680 // After the lanes, for the reason a gain is: it names one, and the key
2681 // it names is checked once the whole file is read.
2682 b"duck" if v25 => {
2683 let f = fields(rest, 7, "duck", n)?;
2684 if f[0] != b"audio" {
2685 return Err(format!(
2686 "line {n}: duck names {:?}, not an audio lane",
2687 String::from_utf8_lossy(f[0])
2688 )
2689 .into());
2690 }
2691 let ord = number(f[1], n)?;
2692 let at = doc
2693 .lanes
2694 .iter()
2695 .enumerate()
2696 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2697 .nth(ord.saturating_sub(1) as usize)
2698 .map(|(at, _)| at)
2699 .ok_or_else(|| format!("line {n}: duck names a lane that is not there"))?;
2700 // 1-based in the file, as a gain's lane is; 0-based in the struct.
2701 let under = number(f[2], n)?;
2702 let duck = Duck {
2703 under: under.checked_sub(1).ok_or_else(|| {
2704 format!("line {n}: duck names audio lane 0, and lanes count from 1")
2705 })? as usize,
2706 depth_db: float(f[3], n)?,
2707 threshold_db: float(f[4], n)?,
2708 attack_ms: float(f[5], n)?,
2709 release_ms: float(f[6], n)?,
2710 };
2711 let in_range = (MIN_DEPTH_DB..=MAX_DEPTH_DB).contains(&duck.depth_db)
2712 && (MIN_THRESHOLD_DB..=MAX_THRESHOLD_DB).contains(&duck.threshold_db)
2713 && duck.attack_ms >= MIN_TIME_MS
2714 && duck.attack_ms <= MAX_ATTACK_MS
2715 && duck.release_ms >= MIN_TIME_MS
2716 && duck.release_ms <= MAX_RELEASE_MS;
2717 if !in_range {
2718 return Err(format!("line {n}: duck has a number out of its range").into());
2719 }
2720 doc.ducks.resize(doc.lanes.len(), Vec::new());
2721 // Several keys for one lane are a v30 dialect; before it a lane
2722 // had one duck, and a second line for it is a file that says
2723 // something its dialect cannot.
2724 if !v30 && !doc.ducks[at].is_empty() {
2725 return Err(format!("line {n}: duck names a lane twice").into());
2726 }
2727 if doc.ducks[at].iter().any(|d| d.under == duck.under) {
2728 return Err(format!("line {n}: duck names the same key twice").into());
2729 }
2730 doc.ducks[at].push(duck);
2731 }
2732 b"voice" if v41 => parse_voice(rest, n, &mut doc)?,
2733 b"effect" if v42 => parse_effect(rest, n, &mut doc)?,
2734 b"wheels" | b"curve" | b"lut" if v43 => parse_look(keyword, rest, n, dir, &mut doc)?,
2735 // After the lanes, which is where `clip_gain_lines` writes it: a line
2736 // names a clip, and a clip is declared by its lane's lines. Only audio
2737 // clips take one, the setter's own rule.
2738 b"lanepan" | b"clippan" if v50 => {
2739 let clip = keyword == b"clippan";
2740 let f = fields(rest, if clip { 4 } else { 3 }, if clip { "clippan" } else { "lanepan" }, n)?;
2741 if f[0] != b"audio" {
2742 return Err(format!("line {n}: pan names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2743 }
2744 let ord = number(f[1], n)?;
2745 let at = doc
2746 .lanes
2747 .iter()
2748 .enumerate()
2749 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2750 .nth(ord.saturating_sub(1) as usize)
2751 .map(|(at, _)| at)
2752 .ok_or_else(|| format!("line {n}: pan names a lane that is not there"))?;
2753 let pan = float(f[if clip { 3 } else { 2 }], n)?;
2754 if !(-1.0..=1.0).contains(&pan) {
2755 return Err(format!("line {n}: pan has a number out of its range").into());
2756 }
2757 if clip {
2758 let idx = number(f[2], n)? as usize;
2759 doc.lanes[at].1.get_mut(idx).ok_or_else(|| format!("line {n}: pan names clip {idx}, which the lane does not have"))?.pan = (pan * 100.0).round() as i8;
2760 } else {
2761 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
2762 doc.flags[at].pan = pan;
2763 }
2764 }
2765 // After the lanes, which is where `pitch_lines` writes it, as `clippan` is.
2766 b"pitch" if v55 => {
2767 let f = fields(rest, 4, "pitch", n)?;
2768 if f[0] != b"audio" {
2769 return Err(format!("line {n}: pitch names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2770 }
2771 let ord = number(f[1], n)?;
2772 let at = doc
2773 .lanes
2774 .iter()
2775 .enumerate()
2776 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2777 .nth(ord.saturating_sub(1) as usize)
2778 .map(|(at, _)| at)
2779 .ok_or_else(|| format!("line {n}: pitch names a lane that is not there"))?;
2780 let idx = number(f[2], n)? as usize;
2781 let semitones = std::str::from_utf8(f[3]).ok().and_then(|s| s.parse::<i8>().ok());
2782 let semitones = match semitones {
2783 Some(v) if (crate::project::MIN_CLIP_PITCH..=crate::project::MAX_CLIP_PITCH).contains(&v) => v,
2784 _ => return Err(format!("line {n}: pitch has a number out of its range").into()),
2785 };
2786 doc.lanes[at]
2787 .1
2788 .get_mut(idx)
2789 .ok_or_else(|| format!("line {n}: pitch names clip {idx}, which the lane does not have"))?
2790 .pitch = semitones;
2791 }
2792 b"clipgain" if v27 => {
2793 let f = fields(rest, 4, "clipgain", n)?;
2794 if f[0] != b"audio" {
2795 return Err(format!(
2796 "line {n}: clipgain names {:?}, not an audio lane",
2797 String::from_utf8_lossy(f[0])
2798 )
2799 .into());
2800 }
2801 let ord = number(f[1], n)?;
2802 let at = doc
2803 .lanes
2804 .iter()
2805 .enumerate()
2806 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2807 .nth(ord.saturating_sub(1) as usize)
2808 .map(|(at, _)| at)
2809 .ok_or_else(|| format!("line {n}: clipgain names a lane that is not there"))?;
2810 let idx = number(f[2], n)? as usize;
2811 let db = float(f[3], n)?;
2812 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&db) {
2813 return Err(format!("line {n}: clipgain has a number out of its range").into());
2814 }
2815 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2816 format!("line {n}: clipgain names clip {idx}, which the lane does not have")
2817 })?;
2818 clip.gain_db = db;
2819 }
2820 // After the lanes, which is where `tkey_lines` writes it: a placement
2821 // key is source-ordered and unique by source frame, at most
2822 // `MAX_TRANSFORM_KEYS` of them, each a finite placement with an opacity
2823 // in `0..=1`. Only a video clip can carry them.
2824 b"tkeys" if v32 => {
2825 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2826 if f.len() < 4 {
2827 return Err(format!("line {n}: tkeys wants a clip and a key").into());
2828 }
2829 let lane_kind = match f[0] {
2830 b"video" => LaneKind::Video,
2831 other => {
2832 return Err(format!(
2833 "line {n}: tkeys names {:?}, not a video lane",
2834 String::from_utf8_lossy(other)
2835 )
2836 .into())
2837 }
2838 };
2839 let ord = number(f[1], n)?;
2840 let at = doc
2841 .lanes
2842 .iter()
2843 .enumerate()
2844 .filter(|(_, (k, _))| *k == lane_kind)
2845 .nth(ord.saturating_sub(1) as usize)
2846 .map(|(at, _)| at)
2847 .ok_or_else(|| format!("line {n}: tkeys names a lane that is not there"))?;
2848 let idx = number(f[2], n)? as usize;
2849 let points = &f[3..];
2850 if points.len() > MAX_TRANSFORM_KEYS {
2851 return Err(
2852 format!("line {n}: tkeys has more than {MAX_TRANSFORM_KEYS} keys").into(),
2853 );
2854 }
2855 let mut keys: Vec<TransformKey> = Vec::with_capacity(points.len());
2856 for point in points {
2857 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
2858 if parts.len() != 3 {
2859 return Err(format!("line {n}: tkeys key wants at:ease:values").into());
2860 }
2861 let ease = KeyEase::from_token(parts[1])
2862 .filter(|e| v39 || matches!(e, KeyEase::Linear | KeyEase::Ease))
2863 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
2864 .ok_or_else(|| format!("line {n}: tkeys ease is lin, in, out, ease or hold"))?;
2865 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
2866 if v.len() != 9 {
2867 return Err(format!("line {n}: tkeys key wants 9 values").into());
2868 }
2869 let params = TransformParams {
2870 pos_x: float(v[0], n)?,
2871 pos_y: float(v[1], n)?,
2872 scale: float(v[2], n)?,
2873 rotate: float(v[3], n)?,
2874 crop_l: float(v[4], n)?,
2875 crop_r: float(v[5], n)?,
2876 crop_t: float(v[6], n)?,
2877 crop_b: float(v[7], n)?,
2878 opacity: float(v[8], n)?,
2879 };
2880 if !(0.0..=1.0).contains(&params.opacity) {
2881 return Err(format!("line {n}: tkeys opacity must be 0..=1").into());
2882 }
2883 let key = TransformKey {
2884 at: number(parts[0], n)?,
2885 params,
2886 ease,
2887 };
2888 if keys.last().is_some_and(|k| k.at >= key.at) {
2889 return Err(
2890 format!("line {n}: tkeys keys are not in source order").into()
2891 );
2892 }
2893 keys.push(key);
2894 }
2895 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2896 format!("line {n}: tkeys names clip {idx}, which the lane does not have")
2897 })?;
2898 clip.transform_keys = keys;
2899 }
2900 // After the lanes, which is where `opacity_key_lines` and `color_key_lines`
2901 // write them: a video clip's opacity (`0..=1`) and colour animation,
2902 // source-ordered and unique by source frame, at most `MAX_TRANSFORM_KEYS`
2903 // and `MAX_COLOR_KEYS` of them, each in range.
2904 // A stabilised video clip, named as an `okeys` line names its clip.
2905 b"deint" if v46 => {
2906 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2907 if f.len() != 4 || f[0] != b"video" {
2908 return Err(format!("line {n}: deint wants a video clip and a mode").into());
2909 }
2910 let ord = number(f[1], n)?;
2911 let at = doc
2912 .lanes
2913 .iter()
2914 .enumerate()
2915 .filter(|(_, (k, _))| *k == LaneKind::Video)
2916 .nth(ord.saturating_sub(1) as usize)
2917 .map(|(at, _)| at)
2918 .ok_or_else(|| format!("line {n}: deint names a lane that is not there"))?;
2919 let idx = number(f[2], n)? as usize;
2920 let mode = std::str::from_utf8(f[3])
2921 .ok()
2922 .and_then(Deinterlace::from_name)
2923 .ok_or_else(|| format!("line {n}: deint mode must be frame, field or off"))?;
2924 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2925 format!("line {n}: deint names clip {idx}, which the lane does not have")
2926 })?;
2927 clip.deinterlace = mode;
2928 }
2929 b"lanename" if v46 => {
2930 let mut parts = rest.splitn(3, |&b| b == b' ');
2931 let kind = match parts.next().unwrap_or_default() {
2932 b"video" => LaneKind::Video,
2933 b"audio" => LaneKind::Audio,
2934 b"sub" => LaneKind::Subtitle,
2935 other => {
2936 return Err(format!("line {n}: lanename names {:?}, not a lane kind", String::from_utf8_lossy(other)).into());
2937 }
2938 };
2939 let ord = number(parts.next().unwrap_or_default(), n)?;
2940 let at = doc
2941 .lanes
2942 .iter()
2943 .enumerate()
2944 .filter(|(_, (k, _))| *k == kind)
2945 .nth(ord.saturating_sub(1) as usize)
2946 .map(|(at, _)| at)
2947 .ok_or_else(|| format!("line {n}: lanename names a lane that is not there"))?;
2948 let name = unescape_text(parts.next().unwrap_or_default(), n)?;
2949 if name.is_empty() || name.chars().count() > crate::project::MAX_LANE_NAME_CHARS || name.chars().any(char::is_control) {
2950 return Err(format!("line {n}: a lane name is 1 to {} characters", crate::project::MAX_LANE_NAME_CHARS).into());
2951 }
2952 doc.names.resize(doc.lanes.len(), String::new());
2953 doc.names[at] = name;
2954 }
2955 b"stab" if v44 => {
2956 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2957 if f.len() != 5 || f[0] != b"video" {
2958 return Err(format!("line {n}: stab wants a video clip, a strength and a crop").into());
2959 }
2960 let ord = number(f[1], n)?;
2961 let at = doc
2962 .lanes
2963 .iter()
2964 .enumerate()
2965 .filter(|(_, (k, _))| *k == LaneKind::Video)
2966 .nth(ord.saturating_sub(1) as usize)
2967 .map(|(at, _)| at)
2968 .ok_or_else(|| format!("line {n}: stab names a lane that is not there"))?;
2969 let idx = number(f[2], n)? as usize;
2970 let strength = std::str::from_utf8(f[3])
2971 .ok()
2972 .and_then(|v| v.parse::<f32>().ok())
2973 .filter(|v| (0.0..=1.0).contains(v))
2974 .ok_or_else(|| format!("line {n}: stab strength must be a number from 0 to 1"))?;
2975 let crop = std::str::from_utf8(f[4])
2976 .ok()
2977 .and_then(crate::stabilise::Crop::from_name)
2978 .ok_or_else(|| format!("line {n}: stab crop must be zoom or full"))?;
2979 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2980 format!("line {n}: stab names clip {idx}, which the lane does not have")
2981 })?;
2982 clip.stabilise = Some(crate::stabilise::Stabilise::new(strength, crop));
2983 }
2984 // A v53 mask's keys: five values, the mask's invert stays at its static value.
2985 b"mkeys" if v53 => {
2986 use crate::effects::EffectKind;
2987 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2988 if f.len() < 5 || f[0] != b"video" {
2989 return Err(format!("line {n}: mkeys wants a video clip, a slot and a key").into());
2990 }
2991 let ord = number(f[1], n)?;
2992 let at = doc
2993 .lanes
2994 .iter()
2995 .enumerate()
2996 .filter(|(_, (k, _))| *k == LaneKind::Video)
2997 .nth(ord.saturating_sub(1) as usize)
2998 .map(|(at, _)| at)
2999 .ok_or_else(|| format!("line {n}: mkeys names a lane that is not there"))?;
3000 let idx = number(f[2], n)? as usize;
3001 let slot = number(f[3], n)? as usize;
3002 let clip = doc.lanes[at]
3003 .1
3004 .get_mut(idx)
3005 .ok_or_else(|| format!("line {n}: mkeys names clip {idx}, which the lane does not have"))?;
3006 let effect = clip
3007 .effects
3008 .get_mut(slot)
3009 .filter(|e| matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask))
3010 .ok_or_else(|| format!("line {n}: mkeys names an effect that is not a mask"))?;
3011 let invert = effect.values[5];
3012 let mut keys = read_effect_keys("mkeys", &f[4..], &EffectKind::RectMask.params()[..5], n, v56)?;
3013 for k in &mut keys {
3014 k.values[5] = invert;
3015 }
3016 effect.keys = keys;
3017 }
3018 b"ekeys" if v56 => {
3019 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3020 if f.len() < 4 || f[0] != b"video" {
3021 return Err(format!("line {n}: ekeys wants a video clip, a slot and a key").into());
3022 }
3023 let ord = number(f[1], n)?;
3024 let at = doc
3025 .lanes
3026 .iter()
3027 .enumerate()
3028 .filter(|(_, (k, _))| *k == LaneKind::Video)
3029 .nth(ord.saturating_sub(1) as usize)
3030 .map(|(at, _)| at)
3031 .ok_or_else(|| format!("line {n}: ekeys names a lane that is not there"))?;
3032 let idx = number(f[2], n)? as usize;
3033 let slot = number(f[3], n)? as usize;
3034 let clip = doc.lanes[at]
3035 .1
3036 .get_mut(idx)
3037 .ok_or_else(|| format!("line {n}: ekeys names clip {idx}, which the lane does not have"))?;
3038 let effect = clip
3039 .effects
3040 .get_mut(slot)
3041 .ok_or_else(|| format!("line {n}: ekeys names an effect the clip does not have"))?;
3042 let specs = effect.kind.params();
3043 let mut keys = read_effect_keys("ekeys", &f[4..], specs, n, v56)?;
3044 // A parameter that cannot be keyed (a switch or a choice) keeps its static value.
3045 for k in &mut keys {
3046 for (i, _) in specs.iter().enumerate().filter(|(_, s)| !s.keyable()) {
3047 k.values[i] = effect.values[i];
3048 }
3049 }
3050 effect.keys = keys;
3051 }
3052 b"okeys" | b"ckeys" if v39 => {
3053 let colour = keyword == b"ckeys";
3054 let name = if colour { "ckeys" } else { "okeys" };
3055 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3056 if f.len() < 4 || f[0] != b"video" {
3057 return Err(format!("line {n}: {name} wants a video clip and a key").into());
3058 }
3059 let ord = number(f[1], n)?;
3060 let at = doc
3061 .lanes
3062 .iter()
3063 .enumerate()
3064 .filter(|(_, (k, _))| *k == LaneKind::Video)
3065 .nth(ord.saturating_sub(1) as usize)
3066 .map(|(at, _)| at)
3067 .ok_or_else(|| format!("line {n}: {name} names a lane that is not there"))?;
3068 let idx = number(f[2], n)? as usize;
3069 let points = &f[3..];
3070 let cap = if colour { MAX_COLOR_KEYS } else { MAX_TRANSFORM_KEYS };
3071 if points.len() > cap {
3072 return Err(format!("line {n}: {name} has more than {cap} keys").into());
3073 }
3074 let mut okeys: Vec<OpacityKey> = Vec::new();
3075 let mut ckeys: Vec<ColorKey> = Vec::new();
3076 for point in points {
3077 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3078 if parts.len() != 3 {
3079 return Err(format!("line {n}: {name} key wants at:ease:values").into());
3080 }
3081 let at_frame = number(parts[0], n)?;
3082 let ease = KeyEase::from_token(parts[1])
3083 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
3084 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease or hold"))?;
3085 let last = if colour { ckeys.last().map(|k| k.at) } else { okeys.last().map(|k| k.at) };
3086 if last.is_some_and(|l| l >= at_frame) {
3087 return Err(format!("line {n}: {name} keys are not in source order").into());
3088 }
3089 if colour {
3090 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3091 if v.len() != 4 {
3092 return Err(format!("line {n}: ckeys key wants 4 values").into());
3093 }
3094 let params = ColorParams {
3095 brightness: float(v[0], n)?,
3096 contrast: float(v[1], n)?,
3097 saturation: float(v[2], n)?,
3098 tint: float(v[3], n)?,
3099 ..Default::default()
3100 };
3101 if !((-1.0..=1.0).contains(&params.brightness)
3102 && (0.0..=2.0).contains(&params.contrast)
3103 && (0.0..=2.0).contains(&params.saturation)
3104 && (-1.0..=1.0).contains(&params.tint))
3105 {
3106 return Err(format!("line {n}: ckeys has a value out of its range").into());
3107 }
3108 ckeys.push(ColorKey { at: at_frame, params, ease });
3109 } else {
3110 let opacity = float(parts[2], n)?;
3111 if !(0.0..=1.0).contains(&opacity) {
3112 return Err(format!("line {n}: okeys opacity must be 0..=1").into());
3113 }
3114 okeys.push(OpacityKey { at: at_frame, opacity, ease });
3115 }
3116 }
3117 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3118 format!("line {n}: {name} names clip {idx}, which the lane does not have")
3119 })?;
3120 if colour {
3121 clip.color_keys = ckeys;
3122 } else {
3123 clip.opacity_keys = okeys;
3124 }
3125 }
3126 // After the lanes, which is where `gain_key_lines` writes it: a line
3127 // names a clip, and a clip is declared by its lane's lines. Its points
3128 // are source-ordered and unique by source frame, as the setters keep
3129 // them, and at most `MAX_GAIN_KEYS` of them, each in range.
3130 b"gainkeys" if v28 => {
3131 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3132 if f.len() < 4 {
3133 return Err(format!("line {n}: gainkeys wants a clip and a point").into());
3134 }
3135 let kind = match f[0] {
3136 b"audio" => LaneKind::Audio,
3137 b"video" => LaneKind::Video,
3138 other => {
3139 return Err(format!(
3140 "line {n}: gainkeys names {:?}, not a lane kind",
3141 String::from_utf8_lossy(other)
3142 )
3143 .into());
3144 }
3145 };
3146 let ord = number(f[1], n)?;
3147 let at = doc
3148 .lanes
3149 .iter()
3150 .enumerate()
3151 .filter(|(_, (k, _))| *k == kind)
3152 .nth(ord.saturating_sub(1) as usize)
3153 .map(|(at, _)| at)
3154 .ok_or_else(|| format!("line {n}: gainkeys names a lane that is not there"))?;
3155 let idx = number(f[2], n)? as usize;
3156 let points = &f[3..];
3157 if points.len() > MAX_GAIN_KEYS {
3158 return Err(
3159 format!("line {n}: gainkeys has more than {MAX_GAIN_KEYS} points").into(),
3160 );
3161 }
3162 let mut keys = Vec::with_capacity(points.len());
3163 for point in points {
3164 let colon = point
3165 .iter()
3166 .position(|&b| b == b':')
3167 .ok_or_else(|| format!("line {n}: gainkeys point wants at:db"))?;
3168 let (a, d) = (&point[..colon], &point[colon + 1..]);
3169 // A v39 point may end in the ease of the segment that leaves it.
3170 let (d, ease) = match d.iter().position(|&b| b == b':') {
3171 Some(c) if v39 => (
3172 &d[..c],
3173 KeyEase::from_token(&d[c + 1..])
3174 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
3175 .ok_or_else(|| format!("line {n}: gainkeys ease is lin, in, out, ease or hold"))?,
3176 ),
3177 _ => (d, KeyEase::Linear),
3178 };
3179 let key = GainKey {
3180 at: number(a, n)?,
3181 db: float(d, n)?,
3182 ease,
3183 };
3184 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&key.db) {
3185 return Err(format!("line {n}: gainkeys has a dB out of its range").into());
3186 }
3187 if keys.last().is_some_and(|k: &GainKey| k.at >= key.at) {
3188 return Err(
3189 format!("line {n}: gainkeys points are not in source order").into()
3190 );
3191 }
3192 keys.push(key);
3193 }
3194 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3195 format!("line {n}: gainkeys names clip {idx}, which the lane does not have")
3196 })?;
3197 clip.gain_keys = keys;
3198 }
3199 // After the lanes and the subtitle palette: a title names neither,
3200 // and its text is the rest of the line, so it is the ninth field.
3201 b"title" if v26 => {
3202 let f: Vec<&[u8]> = rest.splitn(9, |&b| b == b' ').collect();
3203 if f.len() != 9 {
3204 return Err(format!("line {n}: title wants 9 fields, found {}", f.len()).into());
3205 }
3206 let outline = match f[5] {
3207 b"none" => Outline::None,
3208 b"thin" => Outline::Thin,
3209 b"thick" => Outline::Thick,
3210 other => {
3211 return Err(format!(
3212 "line {n}: title outline {:?} is none, thin or thick",
3213 String::from_utf8_lossy(other)
3214 )
3215 .into());
3216 }
3217 };
3218 let boxed = match f[6] {
3219 b"0" => false,
3220 b"1" => true,
3221 other => {
3222 return Err(format!(
3223 "line {n}: title boxed {:?} is 0 or 1",
3224 String::from_utf8_lossy(other)
3225 )
3226 .into());
3227 }
3228 };
3229 let place = match f[7] {
3230 b"bottom" => Place::Bottom,
3231 b"top" => Place::Top,
3232 b"centre" => Place::Centre,
3233 other => {
3234 return Err(format!(
3235 "line {n}: title place {:?} is bottom, top or centre",
3236 String::from_utf8_lossy(other)
3237 )
3238 .into());
3239 }
3240 };
3241 let title = Title {
3242 start: number(f[0], n)?,
3243 frames: number(f[1], n)?,
3244 text: unescape_text(f[8], n)?,
3245 style: TextStyle {
3246 size: number(f[4], n)?,
3247 outline,
3248 boxed,
3249 place,
3250 ..TextStyle::default()
3251 },
3252 fade_in: number(f[2], n)?,
3253 fade_out: number(f[3], n)?,
3254 in_anim: TitleAnim::None,
3255 out_anim: TitleAnim::None,
3256 anim_frames: 0,
3257 keys: Vec::new(),
3258 };
3259 check_title(&title).map_err(|e| format!("line {n}: {e}"))?;
3260 doc.titles.push(title);
3261 }
3262 // A chapter is a frame and a name: the name is the rest of the line, escaped
3263 // as a `cue` line's is. Written in frame order, one per frame.
3264 // A clip's speed ramp, as `speedkeys` lines, after the lanes they name.
3265 // Its keys are clip-relative and sorted, at most `MAX_SPEED_KEYS` of them, each
3266 // speed in range; the clip's footprint grows with the ramp, so the lane is
3267 // checked again here, where the ramp lands.
3268 b"speedkeys" if v35 => {
3269 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3270 if f.len() < 4 {
3271 return Err(format!("line {n}: speedkeys wants a clip and a point").into());
3272 }
3273 let kind = match f[0] {
3274 b"audio" => LaneKind::Audio,
3275 b"video" => LaneKind::Video,
3276 other => {
3277 return Err(format!(
3278 "line {n}: speedkeys names {:?}, not a lane kind",
3279 String::from_utf8_lossy(other)
3280 )
3281 .into());
3282 }
3283 };
3284 let ord = number(f[1], n)?;
3285 let at = doc
3286 .lanes
3287 .iter()
3288 .enumerate()
3289 .filter(|(_, (k, _))| *k == kind)
3290 .nth(ord.saturating_sub(1) as usize)
3291 .map(|(at, _)| at)
3292 .ok_or_else(|| format!("line {n}: speedkeys names a lane that is not there"))?;
3293 let idx = number(f[2], n)? as usize;
3294 let points = &f[3..];
3295 if points.len() > MAX_SPEED_KEYS {
3296 return Err(format!("line {n}: speedkeys has more than {MAX_SPEED_KEYS} points").into());
3297 }
3298 let mut keys = Vec::with_capacity(points.len());
3299 for point in points {
3300 let colon = point
3301 .iter()
3302 .position(|&b| b == b':')
3303 .ok_or_else(|| format!("line {n}: speedkeys point wants at:permille"))?;
3304 let (a, p) = (&point[..colon], &point[colon + 1..]);
3305 let permille = number(p, n)?;
3306 if permille < u32::from(Speed::MIN.permille())
3307 || permille > u32::from(Speed::MAX.permille())
3308 {
3309 return Err(format!("line {n}: speedkeys speed {permille} is out of range").into());
3310 }
3311 let key = SpeedKey {
3312 at: number(a, n)?,
3313 speed: Speed::from_permille(permille as u16),
3314 };
3315 if keys.last().is_some_and(|k: &SpeedKey| k.at >= key.at) {
3316 return Err(format!("line {n}: speedkeys points are not in frame order").into());
3317 }
3318 keys.push(key);
3319 }
3320 let lane = &mut doc.lanes[at].1;
3321 let clip = lane.get_mut(idx).ok_or_else(|| {
3322 format!("line {n}: speedkeys names clip {idx}, which the lane does not have")
3323 })?;
3324 clip.speed_keys = keys;
3325 let end = clip.start.checked_add(clip.frames()).ok_or_else(|| {
3326 format!("line {n}: speed ramp runs past the last frame there is")
3327 })?;
3328 if lane.get(idx + 1).is_some_and(|next| next.start < end) {
3329 return Err(format!("line {n}: speed ramp runs into the next clip on its lane").into());
3330 }
3331 }
3332 // How a clip's transition is drawn, after the lanes it names.
3333 b"transition" if v37 => {
3334 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3335 if f.len() != 4 {
3336 return Err(format!("line {n}: transition wants a clip and a kind").into());
3337 }
3338 let kind = match f[0] {
3339 b"audio" => LaneKind::Audio,
3340 b"video" => LaneKind::Video,
3341 other => {
3342 return Err(format!(
3343 "line {n}: transition names {:?}, not a lane kind",
3344 String::from_utf8_lossy(other)
3345 )
3346 .into());
3347 }
3348 };
3349 let ord = number(f[1], n)?;
3350 let at = doc
3351 .lanes
3352 .iter()
3353 .enumerate()
3354 .filter(|(_, (k, _))| *k == kind)
3355 .nth(ord.saturating_sub(1) as usize)
3356 .map(|(at, _)| at)
3357 .ok_or_else(|| format!("line {n}: transition names a lane that is not there"))?;
3358 let idx = number(f[2], n)? as usize;
3359 let name = String::from_utf8_lossy(f[3]);
3360 let kind = TransitionKind::parse(&name)
3361 .ok_or_else(|| format!("line {n}: transition kind {name:?} is not one"))?;
3362 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3363 format!("line {n}: transition names clip {idx}, which the lane does not have")
3364 })?;
3365 clip.transition_kind = kind;
3366 }
3367 // A reversed clip: named like a `speedkeys` line names its clip. The
3368 // window, speed and ramp are the clip's own lines; this is the direction.
3369 b"reverse" if v38 => {
3370 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3371 if f.len() != 3 {
3372 return Err(format!("line {n}: reverse wants a lane and a clip").into());
3373 }
3374 let kind = match f[0] {
3375 b"audio" => LaneKind::Audio,
3376 b"video" => LaneKind::Video,
3377 other => {
3378 return Err(format!(
3379 "line {n}: reverse names {:?}, not a lane kind",
3380 String::from_utf8_lossy(other)
3381 )
3382 .into());
3383 }
3384 };
3385 let ord = number(f[1], n)?;
3386 let at = doc
3387 .lanes
3388 .iter()
3389 .enumerate()
3390 .filter(|(_, (k, _))| *k == kind)
3391 .nth(ord.saturating_sub(1) as usize)
3392 .map(|(at, _)| at)
3393 .ok_or_else(|| format!("line {n}: reverse names a lane that is not there"))?;
3394 let idx = number(f[2], n)? as usize;
3395 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3396 format!("line {n}: reverse names clip {idx}, which the lane does not have")
3397 })?;
3398 clip.reversed = true;
3399 }
3400 b"angle" if v47 => {
3401 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3402 if f.len() != 5 {
3403 return Err(format!("line {n}: angle wants a lane, a clip, a picture angle and a sound angle").into());
3404 }
3405 let kind = match f[0] {
3406 b"audio" => LaneKind::Audio,
3407 b"video" => LaneKind::Video,
3408 _ => return Err(format!("line {n}: angle names a lane kind that is not video or audio").into()),
3409 };
3410 let ord = number(f[1], n)?;
3411 let at = doc
3412 .lanes
3413 .iter()
3414 .enumerate()
3415 .filter(|(_, (k, _))| *k == kind)
3416 .nth(ord.saturating_sub(1) as usize)
3417 .map(|(at, _)| at)
3418 .ok_or_else(|| format!("line {n}: angle names a lane that is not there"))?;
3419 let idx = number(f[2], n)? as usize;
3420 let one_based = |f: &[u8]| -> crate::Result<u8> {
3421 let v = number(f, n)?;
3422 u8::try_from(v.wrapping_sub(1))
3423 .ok()
3424 .filter(|a| usize::from(*a) < crate::project::MAX_ANGLES)
3425 .ok_or_else(|| format!("line {n}: an angle is a number from 1 to {}", crate::project::MAX_ANGLES).into())
3426 };
3427 let video = one_based(f[3])?;
3428 let audio = if f[4] == b"-" { None } else { Some(one_based(f[4])?) };
3429 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3430 format!("line {n}: angle names clip {idx}, which the lane does not have")
3431 })?;
3432 clip.angle = crate::project::Angle { video, audio };
3433 }
3434 // A title's look: which title (by its position in the list), where its block sits,
3435 // how its lines line up, its weight, its colour and its box colour.
3436 b"titlestyle" if v49 => {
3437 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3438 if f.len() != 6 {
3439 return Err(format!("line {n}: titlestyle wants a title, a position, an alignment, a weight and two colours").into());
3440 }
3441 let idx = number(f[0], n)? as usize;
3442 let side = |b: &[u8], what: &str| -> crate::Result<u8> {
3443 match b {
3444 b"centre" => Ok(0),
3445 b"left" => Ok(1),
3446 b"right" => Ok(2),
3447 other => Err(format!("line {n}: title {what} {:?} is centre, left or right", String::from_utf8_lossy(other)).into()),
3448 }
3449 };
3450 let hplace = match side(f[1], "position")? {
3451 1 => HPlace::Left,
3452 2 => HPlace::Right,
3453 _ => HPlace::Centre,
3454 };
3455 let align = match side(f[2], "alignment")? {
3456 1 => Align::Left,
3457 2 => Align::Right,
3458 _ => Align::Centre,
3459 };
3460 let weight = match f[3] {
3461 b"regular" => Weight::Regular,
3462 b"bold" => Weight::Bold,
3463 other => return Err(format!("line {n}: title weight {:?} is regular or bold", String::from_utf8_lossy(other)).into()),
3464 };
3465 let hex = |b: &[u8], len: usize| -> crate::Result<Vec<u8>> {
3466 let ok = b.len() == len * 2 && b.iter().all(u8::is_ascii_hexdigit);
3467 if !ok {
3468 return Err(format!("line {n}: a title colour is {} hex digits", len * 2).into());
3469 }
3470 Ok((0..len).map(|i| u8::from_str_radix(std::str::from_utf8(&b[i * 2..i * 2 + 2]).unwrap_or("0"), 16).unwrap_or(0)).collect())
3471 };
3472 let c = hex(f[4], 3)?;
3473 let bc = hex(f[5], 4)?;
3474 let title = doc
3475 .titles
3476 .get_mut(idx)
3477 .ok_or_else(|| format!("line {n}: titlestyle names title {idx}, which the file does not have"))?;
3478 title.style.hplace = hplace;
3479 title.style.align = align;
3480 title.style.weight = weight;
3481 title.style.ink = [c[0], c[1], c[2]];
3482 title.style.box_color = [bc[0], bc[1], bc[2], bc[3]];
3483 }
3484 // A title's entrance and exit: which title (by its place in the list), the two animations
3485 // and how many frames each takes.
3486 b"titleanim" if v54 => {
3487 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3488 if f.len() != 4 {
3489 return Err(format!("line {n}: titleanim wants a title, an entrance, an exit and a length").into());
3490 }
3491 let idx = number(f[0], n)? as usize;
3492 let anim = |b: &[u8]| {
3493 let name = String::from_utf8_lossy(b).into_owned();
3494 TitleAnim::from_name(&name).ok_or_else(|| format!("line {n}: title animation {name:?} is not one of the known ones"))
3495 };
3496 let (in_anim, out_anim) = (anim(f[1])?, anim(f[2])?);
3497 let anim_frames = number(f[3], n)?;
3498 let title = doc
3499 .titles
3500 .get_mut(idx)
3501 .ok_or_else(|| format!("line {n}: titleanim names title {idx}, which the file does not have"))?;
3502 title.in_anim = in_anim;
3503 title.out_anim = out_anim;
3504 title.anim_frames = anim_frames;
3505 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3506 }
3507 // A title's own keys (v56): the title by its place in the list, then each key as
3508 // `at:ease:x,y,scale,opacity`, in frame order. `check_title` holds the ranges and order.
3509 b"ttkeys" if v56 => {
3510 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3511 if f.is_empty() {
3512 return Err(format!("line {n}: ttkeys wants a title and its keys").into());
3513 }
3514 let idx = number(f[0], n)? as usize;
3515 let mut keys = Vec::with_capacity(f.len() - 1);
3516 for point in &f[1..] {
3517 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3518 if parts.len() != 3 {
3519 return Err(format!("line {n}: ttkeys key wants at:ease:x,y,scale,opacity").into());
3520 }
3521 let at = number(parts[0], n)?;
3522 let ease = KeyEase::from_token(parts[1])
3523 .ok_or_else(|| format!("line {n}: ttkeys ease is lin, in, out, ease, hold or a bezier curve"))?;
3524 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3525 if v.len() != 4 {
3526 return Err(format!("line {n}: ttkeys key wants 4 values").into());
3527 }
3528 let (x, y, scale, opacity) = (float(v[0], n)?, float(v[1], n)?, float(v[2], n)?, float(v[3], n)?);
3529 keys.push(TitleKey { at, x, y, scale, opacity, ease });
3530 }
3531 let title = doc
3532 .titles
3533 .get_mut(idx)
3534 .ok_or_else(|| format!("line {n}: ttkeys names title {idx}, which the file does not have"))?;
3535 title.keys = keys;
3536 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3537 }
3538 b"mark" if v48 => {
3539 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3540 if f.len() != 5 {
3541 return Err(format!("line {n}: mark wants a lane, a clip, a label and on or off").into());
3542 }
3543 let kind = match f[0] {
3544 b"audio" => LaneKind::Audio,
3545 b"video" => LaneKind::Video,
3546 _ => return Err(format!("line {n}: mark names a lane kind that is not video or audio").into()),
3547 };
3548 let ord = number(f[1], n)?;
3549 let at = doc
3550 .lanes
3551 .iter()
3552 .enumerate()
3553 .filter(|(_, (k, _))| *k == kind)
3554 .nth(ord.saturating_sub(1) as usize)
3555 .map(|(at, _)| at)
3556 .ok_or_else(|| format!("line {n}: mark names a lane that is not there"))?;
3557 let idx = number(f[2], n)? as usize;
3558 let label = u8::try_from(number(f[3], n)?)
3559 .ok()
3560 .filter(|l| *l <= crate::project::LABEL_COUNT)
3561 .ok_or_else(|| format!("line {n}: a label is a number from 0 to {}", crate::project::LABEL_COUNT))?;
3562 let off = match f[4] {
3563 b"on" => false,
3564 b"off" => true,
3565 _ => return Err(format!("line {n}: mark ends with on or off").into()),
3566 };
3567 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3568 format!("line {n}: mark names clip {idx}, which the lane does not have")
3569 })?;
3570 clip.mark = crate::project::ClipMark { label, off };
3571 }
3572 // The library (v51): `bin <id> <parent> <name>`, then `srcbin <source> <bin>` and
3573 // `srcfav <source>` for the sources that are filed or starred.
3574 // The project notes (v52): one `notes` line, its text escaped as a cue's is, so a
3575 // note of several lines is one line in the file.
3576 b"notes" if v52 => {
3577 if !doc.notes.is_empty() {
3578 return Err(format!("line {n}: notes is given twice").into());
3579 }
3580 doc.notes = unescape_text(rest, n)?;
3581 }
3582 // The length a still is placed at (v52), in seconds, within the range the editor allows.
3583 b"still" if v52 => {
3584 let f = fields(rest, 1, "still", n)?;
3585 let secs: f64 = std::str::from_utf8(f[0]).ok().and_then(|t| t.parse().ok()).ok_or_else(|| format!("line {n}: still wants a length in seconds"))?;
3586 if !(STILL_MIN_SECS..=STILL_MAX_SECS).contains(&secs) {
3587 return Err(format!("line {n}: a still is {STILL_MIN_SECS} to {STILL_MAX_SECS} s long, not {secs}").into());
3588 }
3589 doc.still_secs = Some(secs);
3590 }
3591 b"bin" if v51 => {
3592 let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect();
3593 if f.len() != 3 {
3594 return Err(format!("line {n}: bin wants an id, a parent and a name").into());
3595 }
3596 let id = number(f[0], n)?;
3597 let parent = number(f[1], n)?;
3598 let name = unescape_text(f[2], n)?;
3599 if id == 0 || doc.bins.iter().any(|b| b.id == id) {
3600 return Err(format!("line {n}: bin {id} is not a new id").into());
3601 }
3602 if parent != 0 && !doc.bins.iter().any(|b| b.id == parent && b.parent == 0) {
3603 return Err(format!("line {n}: bin {id} is inside bin {parent}, which is not a top-level bin before it").into());
3604 }
3605 let name = crate::project::clean_bin_name(&name).map_err(|e| format!("line {n}: {e}"))?;
3606 if doc.bins.iter().any(|b| b.parent == parent && b.name.eq_ignore_ascii_case(&name)) {
3607 return Err(format!("line {n}: two bins named {name} in one place").into());
3608 }
3609 if doc.bins.len() >= crate::project::MAX_BINS {
3610 return Err(format!("line {n}: a project holds at most {} bins", crate::project::MAX_BINS).into());
3611 }
3612 doc.bins.push(crate::project::Bin { id, parent, name });
3613 }
3614 b"srcbin" if v51 => {
3615 let f = fields(rest, 2, "srcbin", n)?;
3616 let (src, bin) = (number(f[0], n)? as usize, number(f[1], n)?);
3617 if !doc.bins.iter().any(|b| b.id == bin) {
3618 return Err(format!("line {n}: srcbin names bin {bin}, which is not defined before it").into());
3619 }
3620 doc.sources
3621 .get_mut(src)
3622 .ok_or_else(|| format!("line {n}: srcbin names source {src}, which the file does not have"))?
3623 .bin = bin;
3624 }
3625 b"srcfav" if v51 => {
3626 let f = fields(rest, 1, "srcfav", n)?;
3627 let src = number(f[0], n)? as usize;
3628 doc.sources
3629 .get_mut(src)
3630 .ok_or_else(|| format!("line {n}: srcfav names source {src}, which the file does not have"))?
3631 .fav = true;
3632 }
3633 b"mcam" if v47 => {
3634 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
3635 let id = number(id, n)?;
3636 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
3637 doc.mcams.push((id, name));
3638 }
3639 b"chapter" if v34 => {
3640 let mut fields = rest.splitn(2, |&b| b == b' ');
3641 let frame = number(fields.next().unwrap_or_default(), n)?;
3642 let title = unescape_text(fields.next().unwrap_or_default(), n)?;
3643 let chapter = Chapter { frame, title };
3644 check_chapter(&chapter).map_err(|e| format!("line {n}: {e}"))?;
3645 if doc.chapters.last().is_some_and(|c| c.frame >= frame) {
3646 return Err(format!("line {n}: chapter at frame {frame} is not after the one before it").into());
3647 }
3648 if doc.chapters.len() >= MAX_LIST_ENTRIES {
3649 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} chapters").into());
3650 }
3651 doc.chapters.push(chapter);
3652 }
3653 b"marker" if v36 => {
3654 let f: Vec<&[u8]> = rest.splitn(4, |&b| b == b' ').collect();
3655 if f.len() < 4 {
3656 return Err(format!("line {n}: marker wants a frame, a length, a colour and a name").into());
3657 }
3658 let color = std::str::from_utf8(f[2])
3659 .ok()
3660 .and_then(MarkerColor::from_name)
3661 .ok_or_else(|| format!("line {n}: marker names {:?}, not a colour", String::from_utf8_lossy(f[2])))?;
3662 let marker = Marker {
3663 frame: number(f[0], n)?,
3664 length: number(f[1], n)?,
3665 name: unescape_text(f[3], n)?,
3666 note: String::new(),
3667 color,
3668 };
3669 check_marker(&marker).map_err(|e| format!("line {n}: {e}"))?;
3670 if doc.markers.last().is_some_and(|m| m.frame > marker.frame) {
3671 return Err(format!("line {n}: marker at frame {} is before the one above it", marker.frame).into());
3672 }
3673 if doc.markers.len() >= MAX_LIST_ENTRIES {
3674 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} markers").into());
3675 }
3676 doc.markers.push(marker);
3677 }
3678 b"cuewords" if v40 => {
3679 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3680 if f.len() < 5 || !(f.len() - 2).is_multiple_of(3) {
3681 return Err(format!("line {n}: cuewords wants a track, a cue and whole (start, end, word) triples").into());
3682 }
3683 if (f.len() - 2) / 3 > MAX_CUE_WORDS {
3684 return Err(format!("line {n}: cuewords carries more than {MAX_CUE_WORDS} words").into());
3685 }
3686 let track = number(f[0], n)? as usize;
3687 if track >= doc.subtitles.len() {
3688 return Err(format!("line {n}: cuewords names subtitle track {track} of {}", doc.subtitles.len()).into());
3689 }
3690 let mut words = Vec::new();
3691 for w in f[2..].chunks(3) {
3692 let time = |b: &[u8]| -> crate::Result<i64> {
3693 std::str::from_utf8(b)
3694 .ok()
3695 .and_then(|t| t.parse::<i64>().ok())
3696 .ok_or_else(|| format!("line {n}: cuewords time is not a number").into())
3697 };
3698 words.push((time(w[0])?, time(w[1])?, unescape_text(w[2], n)?));
3699 }
3700 doc.cue_words.push((track, number(f[1], n)? as usize, words));
3701 }
3702 b"capstyle" if v40 => {
3703 let f: Vec<&str> = fields(rest, 5, "capstyle", n)?
3704 .into_iter()
3705 .map(|b| std::str::from_utf8(b).unwrap_or(""))
3706 .collect();
3707 let anim = CaptionAnim::from_name(f[0])
3708 .ok_or_else(|| format!("line {n}: capstyle names {:?}, not an animation", f[0]))?;
3709 let hex = f[1];
3710 let rgb = (hex.len() == 6)
3711 .then(|| u32::from_str_radix(hex, 16).ok())
3712 .flatten()
3713 .ok_or_else(|| format!("line {n}: capstyle colour {hex:?} is not six hex digits"))?;
3714 let flag = |s: &str| match s {
3715 "0" => Ok(false),
3716 "1" => Ok(true),
3717 other => Err(format!("line {n}: capstyle flag {other:?} is not 0 or 1")),
3718 };
3719 let words_per_line: u8 = f[4]
3720 .parse()
3721 .ok()
3722 .filter(|&w| w <= MAX_WORDS_PER_LINE)
3723 .ok_or_else(|| format!("line {n}: capstyle words per line {:?} is not 0 to {MAX_WORDS_PER_LINE}", f[4]))?;
3724 doc.caption_style = CaptionStyle {
3725 anim,
3726 highlight: [(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8],
3727 hl_box: flag(f[2])?,
3728 uppercase: flag(f[3])?,
3729 words_per_line,
3730 };
3731 }
3732 b"marknote" if v36 => {
3733 let mut fields = rest.splitn(2, |&b| b == b' ');
3734 let idx = number(fields.next().unwrap_or_default(), n)? as usize;
3735 let note = unescape_text(fields.next().unwrap_or_default(), n)?;
3736 let marker = doc
3737 .markers
3738 .get_mut(idx)
3739 .ok_or_else(|| format!("line {n}: marknote names marker {idx}, which the file does not have"))?;
3740 marker.note = note;
3741 check_marker(marker).map_err(|e| format!("line {n}: {e}"))?;
3742 }
3743 b"flags" if v24 => {
3744 let mut words = rest.split(|&b| b == b' ');
3745 let kind = match words.next().unwrap_or_default() {
3746 b"video" => LaneKind::Video,
3747 b"audio" => LaneKind::Audio,
3748 b"sub" => LaneKind::Subtitle,
3749 other => {
3750 return Err(format!(
3751 "line {n}: flags names {:?}, not a lane kind",
3752 String::from_utf8_lossy(other)
3753 )
3754 .into());
3755 }
3756 };
3757 let ord = number(words.next().unwrap_or_default(), n)?;
3758 let at = doc
3759 .lanes
3760 .iter()
3761 .enumerate()
3762 .filter(|(_, (k, _))| *k == kind)
3763 .nth(ord.saturating_sub(1) as usize)
3764 .map(|(at, _)| at)
3765 .ok_or_else(|| format!("line {n}: flags names a lane that is not there"))?;
3766 let mut set = LaneFlags::default();
3767 let mut any = false;
3768 for word in words {
3769 let (slot, name) = match word {
3770 b"hidden" if kind != LaneKind::Audio => (&mut set.hidden, "hidden"),
3771 b"muted" if kind == LaneKind::Audio => (&mut set.muted, "muted"),
3772 b"locked" => (&mut set.locked, "locked"),
3773 other => {
3774 return Err(format!(
3775 "line {n}: flags {:?} cannot be set on that lane",
3776 String::from_utf8_lossy(other)
3777 )
3778 .into());
3779 }
3780 };
3781 if std::mem::replace(slot, true) {
3782 return Err(format!("line {n}: flags names {name} twice").into());
3783 }
3784 any = true;
3785 }
3786 if !any {
3787 return Err(format!("line {n}: flags names no switch").into());
3788 }
3789 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
3790 set.pan = doc.flags[at].pan;
3791 doc.flags[at] = set;
3792 }
3793 // Beside the source lines and read the same way: fields first, the
3794 // path last, because a path runs to the end of the line.
3795 b"subtitle" if v10 => {
3796 let at = rest
3797 .iter()
3798 .position(|&b| b == b' ')
3799 .ok_or_else(|| format!("line {n}: subtitle without a path"))?;
3800 let track = match &rest[..at] {
3801 b"-" => None,
3802 field => Some(u64::from(number(field, n)?)),
3803 };
3804 let path = unescape(&rest[at + 1..], n)?;
3805 if path.as_os_str().is_empty() {
3806 return Err(format!("line {n}: subtitle without a path").into());
3807 }
3808 doc.subtitles.push((
3809 // Relative to the project file, as a source path is.
3810 if path.is_absolute() {
3811 path
3812 } else {
3813 dir.join(path)
3814 },
3815 track,
3816 ));
3817 }
3818 // After the subtitle lines, which declare the tracks it names. The
3819 // text is the rest of the line, so it may hold spaces: the track and
3820 // the cue are the two fields before it.
3821 b"cue" if v24 => {
3822 let mut fields = rest.splitn(3, |&b| b == b' ');
3823 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3824 let cue = number(
3825 fields
3826 .next()
3827 .ok_or_else(|| format!("line {n}: cue without a cue index"))?,
3828 n,
3829 )? as usize;
3830 let text = fields
3831 .next()
3832 .ok_or_else(|| format!("line {n}: cue without its text"))?;
3833 if track >= doc.subtitles.len() {
3834 return Err(format!(
3835 "line {n}: cue names subtitle track {track} of {}",
3836 doc.subtitles.len()
3837 )
3838 .into());
3839 }
3840 doc.cue_edits.push((track, cue, unescape_text(text, n)?));
3841 }
3842 // After the subtitle lines, which declare the tracks it names: the
3843 // track, then the language as the rest of the line, escaped as a cue's
3844 // text is. A language is one field to a reader, not a list of words.
3845 b"sublang" if v33 => {
3846 let mut fields = rest.splitn(2, |&b| b == b' ');
3847 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3848 let lang = fields
3849 .next()
3850 .ok_or_else(|| format!("line {n}: sublang without a language"))?;
3851 if track >= doc.subtitles.len() {
3852 return Err(format!(
3853 "line {n}: sublang names subtitle track {track} of {}",
3854 doc.subtitles.len()
3855 )
3856 .into());
3857 }
3858 let lang = unescape_text(lang, n)?;
3859 if lang.is_empty() {
3860 return Err(format!("line {n}: sublang without a language").into());
3861 }
3862 doc.sub_langs.push((track, lang));
3863 }
3864 // After the subtitle lines, which declare the tracks it names, and
3865 // the `cue` lines, so an added cue lands after the file's own cues.
3866 // The text is the rest of the line, as a `cue` line's is.
3867 b"cueadd" if v29 => {
3868 let mut fields = rest.splitn(4, |&b| b == b' ');
3869 let mut field = |what: &str| fields.next().ok_or_else(|| format!("line {n}: cueadd without {what}"));
3870 let track = number(field("a track")?, n)? as usize;
3871 let start_us = number64(field("a start")?, n)? as i64;
3872 let end_us = number64(field("an end")?, n)? as i64;
3873 let text = field("its text")?;
3874 if track >= doc.subtitles.len() {
3875 return Err(format!(
3876 "line {n}: cueadd names subtitle track {track} of {}",
3877 doc.subtitles.len()
3878 )
3879 .into());
3880 }
3881 if end_us <= start_us {
3882 return Err(format!("line {n}: cueadd ends at {end_us} µs, not after its start {start_us} µs").into());
3883 }
3884 doc.cue_adds.push(crate::project::AddedCue {
3885 track,
3886 start_us,
3887 end_us,
3888 text: unescape_text(text, n)?,
3889 });
3890 }
3891 b"source" => {
3892 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3893 return Err(format!("line {n}: source after a clip").into());
3894 }
3895 // The stream comes first and the path is everything after it,
3896 // spaces and all; an older dialect wrote no stream and meant 0.
3897 let (audio_stream, rest) = if streamless {
3898 (0, rest)
3899 } else {
3900 // No space at all still has to reach `number`, so a v2 line
3901 // in a v3 file is refused as the missing field it is rather
3902 // than as a missing path.
3903 let at = rest.iter().position(|&b| b == b' ');
3904 (
3905 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
3906 &rest[at.map_or(rest.len(), |at| at + 1)..],
3907 )
3908 };
3909 if rest.is_empty() {
3910 return Err(format!("line {n}: source without a path").into());
3911 }
3912 let path = unescape(rest, n)?;
3913 // Relative means "next to the project file", which is what
3914 // makes a whole folder relocatable.
3915 doc.sources.push(Source {
3916 path: if path.is_absolute() {
3917 path
3918 } else {
3919 dir.join(path)
3920 },
3921 audio_stream,
3922 ..Default::default()
3923 });
3924 }
3925 b"eq" if v5 => {
3926 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3927 return Err(format!("line {n}: eq after a clip").into());
3928 }
3929 // A bare `eq` is the empty cascade -- a setting that moves
3930 // nothing, which is not the same thing as no setting at all.
3931 if rest.split(|&b| b == b' ').count() > MAX_EQ_BANDS {
3932 return Err(format!("line {n}: an equalizer holds at most {MAX_EQ_BANDS} bands").into());
3933 }
3934 let bands = match rest.is_empty() {
3935 true => Vec::new(),
3936 false => rest
3937 .split(|&b| b == b' ')
3938 .map(|field| band(field, n))
3939 .collect::<crate::Result<Vec<Band>>>()?,
3940 };
3941 doc.eq.push(EqParams { bands });
3942 }
3943 b"color" if v6 => {
3944 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3945 return Err(format!("line {n}: color after a clip").into());
3946 }
3947 let f = fields(rest, 1, "color", n)?;
3948 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
3949 if parts.len() != 4 {
3950 return Err(
3951 format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
3952 );
3953 }
3954 doc.color.push(ColorParams {
3955 brightness: float(parts[0], n)?,
3956 contrast: float(parts[1], n)?,
3957 saturation: float(parts[2], n)?,
3958 tint: float(parts[3], n)?,
3959 ..Default::default()
3960 });
3961 }
3962 b"transform" if v20 => {
3963 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3964 return Err(format!("line {n}: transform after a clip").into());
3965 }
3966 let f = fields(rest, 1, "transform", n)?;
3967 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
3968 // v31 may add the opacity as a ninth field; an earlier dialect
3969 // has eight, and a ninth there is a line it never wrote.
3970 let want = if v31 { 8..=9 } else { 8..=8 };
3971 if !want.contains(&parts.len()) {
3972 return Err(format!(
3973 "line {n}: transform wants 8 fields, found {}",
3974 parts.len()
3975 )
3976 .into());
3977 }
3978 let opacity = match parts.get(8) {
3979 Some(p) => float(p, n)?,
3980 None => 1.0,
3981 };
3982 if !(0.0..=1.0).contains(&opacity) {
3983 return Err(format!("line {n}: transform opacity must be 0..=1").into());
3984 }
3985 doc.transform.push(TransformParams {
3986 pos_x: float(parts[0], n)?,
3987 pos_y: float(parts[1], n)?,
3988 scale: float(parts[2], n)?,
3989 rotate: float(parts[3], n)?,
3990 crop_l: float(parts[4], n)?,
3991 crop_r: float(parts[5], n)?,
3992 crop_t: float(parts[6], n)?,
3993 crop_b: float(parts[7], n)?,
3994 opacity,
3995 });
3996 }
3997 // v1: one lane, no placement, no groups. Every clip becomes one
3998 // grouped video+audio pair laid where the queue reached, which is
3999 // what the file always meant.
4000 b"clip" if v1 => {
4001 let f = fields(rest, 3, "clip", n)?;
4002 let clip = check(
4003 Clip {
4004 speed_keys: Vec::new(),
4005 reversed: false,
4006 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4007 angle: Default::default(),
4008 fade_in: 0,
4009 fade_out: 0,
4010 transition_out: 0,
4011 transition_kind: Default::default(),
4012 visualizer: 0,
4013 viz_paint: 0,
4014 gain_db: 0.0,
4015 gain_keys: Vec::new(),
4016 pan: 0,
4017 transform_keys: Vec::new(),
4018 opacity_keys: Vec::new(),
4019 color_keys: Vec::new(),
4020 effects: Vec::new(),
4021 start: queued,
4022 in_frame: number(f[0], n)?,
4023 out_frame: number(f[1], n)?,
4024 source: number(f[2], n)? as usize,
4025 link: Some(doc.lanes[0].1.len() as u32),
4026 eq: None,
4027 color: None,
4028 transform: None,
4029 fit: FitPolicy::default(),
4030 speed: Speed::NORMAL,
4031 pitch: 0,
4032 },
4033 &doc,
4034 n,
4035 )?;
4036 queued = clip.end();
4037 doc.lanes[0].1.push(clip.clone());
4038 doc.lanes[1].1.push(clip);
4039 }
4040 // A lane line like the two below it, in its place among them, and
4041 // read into `subs` rather than into the clips: the lane holds
4042 // words, and no media path may ever meet one
4043 // ([`crate::project::LaneKind::Subtitle`]).
4044 b"sub" if v15 => {
4045 let at = rest.iter().position(|&b| b == b' ');
4046 let ord = number(&rest[..at.unwrap_or(rest.len())], n)?;
4047 let rest = &rest[at.map_or(rest.len(), |at| at + 1)..];
4048 let at = lane_of(&mut doc.lanes, LaneKind::Subtitle, ord, n)?;
4049 doc.subs.resize(doc.lanes.len(), Vec::new());
4050 // The bare line is the empty lane's whole existence, exactly as
4051 // it is for a video one.
4052 if rest.is_empty() {
4053 continue;
4054 }
4055 // v16 on may carry a sixth field -- the caption's group id, the
4056 // same spelling a clip's link takes (`-` for none). A v15 line
4057 // stops at five, and a sixth field in one is a file this parser
4058 // never wrote.
4059 let all: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4060 let ok = all.len() == 5 || (v16 && all.len() == 6);
4061 if !ok {
4062 return Err(format!(
4063 "line {n}: sub wants {} fields, found {}",
4064 if v16 { "5 or 6" } else { "5" },
4065 all.len()
4066 )
4067 .into());
4068 }
4069 let link = match all.get(5) {
4070 None => None,
4071 Some(f) if *f == b"-" => None,
4072 Some(f) => Some(number(f, n)?),
4073 };
4074 let f = &all;
4075 let sub = SubClip {
4076 start: number(f[0], n)?,
4077 frames: number(f[1], n)?,
4078 track: number(f[2], n)? as usize,
4079 in_us: micros(f[3], n)?,
4080 out_us: micros(f[4], n)?,
4081 link,
4082 };
4083 // The never-empty invariant at both clocks, which is what
4084 // [`crate::Project::place_sub`] refuses on the live timeline.
4085 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
4086 return Err(format!(
4087 "line {n}: caption at {} is empty: {} frames of [{}, {})",
4088 sub.start, sub.frames, sub.in_us, sub.out_us
4089 )
4090 .into());
4091 }
4092 // The width of that window, which the check above cannot see:
4093 // it asks whether the window is *open*, never how wide it is,
4094 // and a `sub` line is the one number in this format a hand (or
4095 // a hostile actor) can set to `i64::MAX` and have accepted.
4096 // Every cut, split, ripple and group trim re-derives the two
4097 // halves of the window by proportion
4098 // ([`crate::project::SubClip::window_at`]), a multiply that
4099 // overflowed on the first frame inside the caption -- a panic
4100 // on the UI thread the first time a hand ripple-deleted across
4101 // it, and in a release build a silently wrapped clock. The
4102 // same bound [`crate::is_resolution`] holds a `resolution`
4103 // line to, and for the same reason: refused by name at the
4104 // door rather than clamped into something nobody wrote.
4105 if sub.out_us - sub.in_us > crate::project::MAX_WINDOW_US {
4106 return Err(format!(
4107 "line {n}: caption at {} is a {}us window, past the {}us a caption can hold",
4108 sub.start,
4109 sub.out_us - sub.in_us,
4110 crate::project::MAX_WINDOW_US
4111 )
4112 .into());
4113 }
4114 // The palette bound, which is a clip's source bound for words:
4115 // the `subtitle` lines are written before these and a caption
4116 // names one of them by position.
4117 if sub.track >= doc.subtitles.len() {
4118 return Err(format!(
4119 "line {n}: caption names subtitle track {} of {}",
4120 sub.track,
4121 doc.subtitles.len()
4122 )
4123 .into());
4124 }
4125 if sub.start.checked_add(sub.frames).is_none() {
4126 return Err(format!(
4127 "line {n}: caption at {} runs past the last frame there is",
4128 sub.start
4129 )
4130 .into());
4131 }
4132 let lane = &mut doc.subs[at];
4133 if lane.last().is_some_and(|prev| prev.end() > sub.start) {
4134 return Err(format!(
4135 "line {n}: caption at {} overlaps the one before it, or comes before it",
4136 sub.start
4137 )
4138 .into());
4139 }
4140 lane.push(sub);
4141 }
4142 b"video" | b"audio" if !v1 => {
4143 let kind = match keyword {
4144 b"video" => LaneKind::Video,
4145 _ => LaneKind::Audio,
4146 };
4147 // v4 on names the lane, and a line naming nothing else is an
4148 // empty lane's whole existence. Older dialects had one lane per
4149 // kind.
4150 let (ord, rest) = if numbered {
4151 let at = rest.iter().position(|&b| b == b' ');
4152 (
4153 number(&rest[..at.unwrap_or(rest.len())], n)?,
4154 &rest[at.map_or(rest.len(), |at| at + 1)..],
4155 )
4156 } else {
4157 (1, rest)
4158 };
4159 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
4160 if numbered && rest.is_empty() {
4161 continue;
4162 }
4163 // v20 grew the transform field, v18 the two fade fields, v19
4164 // the transition one, v8 the speed one, v7 the fit one, v6
4165 // the colour one and v5 the eq one; every older dialect ends
4166 // at the link.
4167 let want = 5
4168 + usize::from(v5)
4169 + usize::from(v6)
4170 + usize::from(v7)
4171 + usize::from(v8)
4172 + 2 * usize::from(v18)
4173 + usize::from(v19)
4174 + usize::from(v20)
4175 + usize::from(v21)
4176 + usize::from(v22);
4177 let f = fields(rest, want, "clip", n)?;
4178 let in_frame = number(f[1], n)?;
4179 let out_frame = number(f[2], n)?;
4180 let speed = speed_of(f.get(8).copied(), n)?;
4181 // Clamped to the clip's own timeline length,
4182 // [`Project::set_fade_in`]'s rule: a crafted or hand-edited
4183 // file asking for more ramp than the clip has frames gets the
4184 // clip's whole length rather than a refusal.
4185 // A v35 clip's ramp comes on a later line and may lengthen it, so its
4186 // fades are clamped once the ramps are in (after the last line).
4187 let frames = if v35 {
4188 u32::MAX
4189 } else {
4190 speed.frames(out_frame.saturating_sub(in_frame))
4191 };
4192 let clip = check(
4193 Clip {
4194 speed_keys: Vec::new(),
4195 reversed: false,
4196 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4197 angle: Default::default(),
4198 fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames),
4199 fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames),
4200 transition_out: number(f.get(11).copied().unwrap_or(b"0"), n)?.min(frames),
4201 transition_kind: Default::default(),
4202 visualizer: flags_byte(f.get(13).copied().unwrap_or(b"0"), n)?,
4203 viz_paint: number64(f.get(14).copied().unwrap_or(b"0"), n)?,
4204 gain_db: 0.0,
4205 gain_keys: Vec::new(),
4206 pan: 0,
4207 transform_keys: Vec::new(),
4208 opacity_keys: Vec::new(),
4209 color_keys: Vec::new(),
4210 effects: Vec::new(),
4211 start: number(f[0], n)?,
4212 in_frame,
4213 out_frame,
4214 source: number(f[3], n)? as usize,
4215 link: match f[4] {
4216 b"-" => None,
4217 field => Some(number(field, n)?),
4218 },
4219 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
4220 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
4221 transform: table_index(
4222 f.get(12).copied(),
4223 doc.transform.len(),
4224 "transform",
4225 n,
4226 )?,
4227 fit: fit_policy(f.get(7).copied(), n)?,
4228 speed,
4229 pitch: 0,
4230 },
4231 &doc,
4232 n,
4233 )?;
4234 let lane = &mut doc.lanes[at].1;
4235 // The sorted, non-overlapping placement invariant, checked at
4236 // the only door untrusted clips come in through.
4237 // A v35 file's `speedkeys` lines follow the clips, so a ramped clip still
4238 // has its constant footprint here, which a shorter ramp undercuts: only
4239 // the order is checked at this door, and the footprints after the last line.
4240 let behind = |prev: &Clip| {
4241 if v35 {
4242 prev.start >= clip.start
4243 } else {
4244 prev.end() > clip.start
4245 }
4246 };
4247 if lane.last().is_some_and(behind) {
4248 return Err(format!(
4249 "line {n}: clip at {} overlaps the one before it, or comes before it",
4250 clip.start
4251 )
4252 .into());
4253 }
4254 lane.push(clip);
4255 }
4256 // Empty lines land here too: nothing in this format is optional
4257 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
4258 // is a file mixing dialects, and is refused the same way.
4259 _ => {
4260 return Err(format!(
4261 "line {n}: unknown keyword {:?}",
4262 String::from_utf8_lossy(keyword)
4263 )
4264 .into());
4265 }
4266 }
4267 }
4268 // The ramps are in now: every clip ends before the next one starts.
4269 if v35 {
4270 for (_, clips) in &mut doc.lanes {
4271 for c in clips.iter_mut() {
4272 let frames = c.frames();
4273 c.fade_in = c.fade_in.min(frames);
4274 c.fade_out = c.fade_out.min(frames);
4275 c.transition_out = c.transition_out.min(frames);
4276 }
4277 if let Some(w) = clips.windows(2).find(|w| w[0].end() > w[1].start) {
4278 return Err(format!("clip at {} overlaps the one before it", w[1].start).into());
4279 }
4280 }
4281 }
4282 if block.is_some() {
4283 return Err("a sequence block never ends: the file is cut short".into());
4284 }
4285 // One per lane whatever the file said, so a caller may zip the two -- and
4286 // the same for the placements, whose lanes are the very same list.
4287 doc.gains.resize(doc.lanes.len(), 0.0);
4288 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
4289 doc.ducks.resize(doc.lanes.len(), Vec::new());
4290 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4291 doc.names.resize(doc.lanes.len(), String::new());
4292 doc.subs.resize(doc.lanes.len(), Vec::new());
4293 // A key is another audio lane of this file, named by its position among
4294 // them, and never the lane it ducks: a file that says otherwise would ask
4295 // the mixer to duck under nothing.
4296 let audio_lanes = doc
4297 .lanes
4298 .iter()
4299 .filter(|(k, _)| *k == LaneKind::Audio)
4300 .count();
4301 for (i, lane_ducks) in doc.ducks.iter().enumerate() {
4302 let own_ord = doc.lanes[..i]
4303 .iter()
4304 .filter(|(k, _)| *k == LaneKind::Audio)
4305 .count();
4306 for duck in lane_ducks {
4307 if duck.under >= audio_lanes || duck.under == own_ord {
4308 return Err(format!(
4309 "duck names audio lane {}, which is not another audio lane of this project",
4310 duck.under + 1
4311 )
4312 .into());
4313 }
4314 }
4315 }
4316 // A file whose lanes are all empty *is* a project -- the emptied timeline,
4317 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
4318 // refuses that one, by the name it has there.
4319 Ok(doc)
4320}
4321
4322/// Where the lane a v4 line names sits, appending it if this is its first line.
4323/// Lanes arrive in display order, so a number that skips one of its kind is a
4324/// lane that was never declared, and is refused by the name it would have had.
4325fn lane_of(
4326 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
4327 kind: LaneKind,
4328 ord: u32,
4329 line: usize,
4330) -> crate::Result<usize> {
4331 let mut seen = 0;
4332 for (at, (k, _)) in lanes.iter().enumerate() {
4333 if *k == kind {
4334 seen += 1;
4335 if seen == ord {
4336 return Ok(at);
4337 }
4338 }
4339 }
4340 if ord != seen + 1 {
4341 return Err(match ord.checked_sub(1) {
4342 Some(prev) => format!(
4343 "line {line}: lane {} comes before {}",
4344 Lane::new(kind, prev as usize).label(),
4345 Lane::new(kind, seen as usize).label()
4346 ),
4347 None => format!("line {line}: lane numbers start at 1"),
4348 }
4349 .into());
4350 }
4351 lanes.push((kind, Vec::new()));
4352 Ok(lanes.len() - 1)
4353}
4354
4355/// Splits a line's fields, refusing the wrong count by name.
4356fn fields<'a>(
4357 rest: &'a [u8],
4358 want: usize,
4359 what: &str,
4360 line: usize,
4361) -> crate::Result<Vec<&'a [u8]>> {
4362 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4363 if fields.len() != want {
4364 return Err(format!(
4365 "line {line}: {what} wants {want} fields, found {}",
4366 fields.len()
4367 )
4368 .into());
4369 }
4370 Ok(fields)
4371}
4372
4373/// The per-clip structure checks both dialects share.
4374fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
4375 if clip.out_frame <= clip.in_frame {
4376 return Err(format!(
4377 "line {line}: clip [{}, {}) is empty",
4378 clip.in_frame, clip.out_frame
4379 )
4380 .into());
4381 }
4382 if clip.source >= doc.sources.len() && !crate::project::is_sequence_source(clip.source) {
4383 return Err(format!(
4384 "line {line}: clip names source {} of {}",
4385 clip.source,
4386 doc.sources.len()
4387 )
4388 .into());
4389 }
4390 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
4391 // adds `start + len` as plain `u32`, which panics in debug and wraps in
4392 // release on a crafted file. Bound it here, at the door.
4393 if clip.start.checked_add(clip.frames()).is_none() {
4394 return Err(format!(
4395 "line {line}: clip at {} runs past the last frame there is",
4396 clip.start
4397 )
4398 .into());
4399 }
4400 Ok(clip)
4401}
4402
4403/// A clip's `<speed>` field: thousandths of real time, as
4404/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A
4405/// dialect with no such field (everything before v8) means real time, which is
4406/// what such a project always played at. A number outside the range the editor
4407/// can set is *refused* rather than clamped: a project file is generated, so
4408/// that is a corrupt line and not a dialect.
4409fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result<Speed> {
4410 let Some(field) = field else {
4411 return Ok(Speed::NORMAL);
4412 };
4413 let permille = number(field, line)?;
4414 let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16);
4415 if u32::from(speed.permille()) != permille {
4416 return Err(format!(
4417 "line {line}: speed {permille} is outside {}-{} thousandths",
4418 Speed::MIN.permille(),
4419 Speed::MAX.permille()
4420 )
4421 .into());
4422 }
4423 Ok(speed)
4424}
4425
4426/// How a fit policy is spelled in the file. One word each, so a clip line stays
4427/// readable, and the same word the parser takes back.
4428fn fit_name(fit: FitPolicy) -> &'static str {
4429 match fit {
4430 FitPolicy::Fit => "fit",
4431 FitPolicy::Fill => "fill",
4432 FitPolicy::Stretch => "stretch",
4433 FitPolicy::Center => "center",
4434 }
4435}
4436
4437/// A clip's `<fit>` field. A dialect that has no such field at all means the
4438/// default -- those projects held one resolution, so no clip of theirs was ever
4439/// placed on anything.
4440fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
4441 let Some(field) = field else {
4442 return Ok(FitPolicy::default());
4443 };
4444 match field {
4445 b"fit" => Ok(FitPolicy::Fit),
4446 b"fill" => Ok(FitPolicy::Fill),
4447 b"stretch" => Ok(FitPolicy::Stretch),
4448 b"center" => Ok(FitPolicy::Center),
4449 other => Err(format!(
4450 "line {line}: {:?} is not a fit policy",
4451 String::from_utf8_lossy(other)
4452 )
4453 .into()),
4454 }
4455}
4456
4457/// An `effect` line (v42): see [`effect_lines`]. The kind must be one, the switch `0` or
4458/// `1`, every value in its range and a clip's stack no longer than
4459/// [`crate::effects::MAX_EFFECTS`].
4460fn parse_effect(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4461 use crate::effects::{Effect, EffectKind, MAX_EFFECTS, MAX_PARAMS};
4462 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4463 if f.len() < 5 || f[0] != b"video" {
4464 return Err(format!("line {n}: effect wants a video clip, a kind and a switch").into());
4465 }
4466 let ord = number(f[1], n)?;
4467 let at = doc
4468 .lanes
4469 .iter()
4470 .enumerate()
4471 .filter(|(_, (k, _))| *k == LaneKind::Video)
4472 .nth(ord.saturating_sub(1) as usize)
4473 .map(|(at, _)| at)
4474 .ok_or_else(|| format!("line {n}: effect names a lane that is not there"))?;
4475 let idx = number(f[2], n)? as usize;
4476 let name = String::from_utf8_lossy(f[3]);
4477 let kind = EffectKind::from_name(&name).ok_or_else(|| format!("line {n}: effect {name:?} is not one"))?;
4478 let on = match f[4] {
4479 b"1" => true,
4480 b"0" => false,
4481 _ => return Err(format!("line {n}: effect switch is not 0 or 1").into()),
4482 };
4483 let specs = kind.params();
4484 if f.len() - 5 != specs.len() {
4485 return Err(format!("line {n}: effect {name} wants {} values, found {}", specs.len(), f.len() - 5).into());
4486 }
4487 let mut values = [0.0; MAX_PARAMS];
4488 for ((v, field), spec) in values.iter_mut().zip(&f[5..]).zip(specs) {
4489 *v = float(field, n)?;
4490 if !(spec.min..=spec.max).contains(v) {
4491 return Err(format!("line {n}: effect {name} {} is out of its range", spec.name).into());
4492 }
4493 }
4494 let clip = doc.lanes[at]
4495 .1
4496 .get_mut(idx)
4497 .ok_or_else(|| format!("line {n}: effect names clip {idx}, which the lane does not have"))?;
4498 if clip.effects.len() >= MAX_EFFECTS {
4499 return Err(format!("line {n}: a clip holds at most {MAX_EFFECTS} effects").into());
4500 }
4501 clip.effects.push(Effect { kind, on, values, keys: Vec::new() });
4502 Ok(())
4503}
4504
4505/// A `voice` line (v41): see [`voice_lines`]. Every number is range-checked the way the
4506/// setter clamps it, and a noise reduction that is on must carry its profile.
4507fn parse_voice(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4508 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4509 if f.len() < 3 {
4510 return Err(format!("line {n}: voice wants a lane, a number and a processor").into());
4511 }
4512 if f[0] != b"audio" {
4513 return Err(format!("line {n}: voice names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
4514 }
4515 let ord = number(f[1], n)?;
4516 let at = doc
4517 .lanes
4518 .iter()
4519 .enumerate()
4520 .filter(|(_, (k, _))| *k == LaneKind::Audio)
4521 .nth(ord.saturating_sub(1) as usize)
4522 .map(|(at, _)| at)
4523 .ok_or_else(|| format!("line {n}: voice names a lane that is not there"))?;
4524 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4525 let flag = |field: &[u8]| match field {
4526 b"0" => Ok(false),
4527 b"1" => Ok(true),
4528 _ => Err(format!("line {n}: {:?} is not 0 or 1", String::from_utf8_lossy(field))),
4529 };
4530 let want = |count: usize, what: &str| {
4531 if f.len() == count + 3 {
4532 Ok(())
4533 } else {
4534 Err(format!("line {n}: voice {what} wants {count} fields, found {}", f.len() - 3))
4535 }
4536 };
4537 let range = || format!("line {n}: voice has a number out of its range");
4538 let voice = &mut doc.voices[at];
4539 match f[2] {
4540 b"gate" => {
4541 want(6, "gate")?;
4542 let g = Gate {
4543 on: flag(f[3])?,
4544 threshold_db: float(f[4], n)?,
4545 attack_ms: float(f[5], n)?,
4546 release_ms: float(f[6], n)?,
4547 hold_ms: float(f[7], n)?,
4548 range_db: float(f[8], n)?,
4549 };
4550 if g.clamped() != Some(g) {
4551 return Err(range().into());
4552 }
4553 voice.gate = g;
4554 }
4555 b"nr" => {
4556 want(4, "nr")?;
4557 let profile = match f[6] {
4558 b"-" => Vec::new(),
4559 list => list.split(|&b| b == b',').map(|v| float(v, n)).collect::<crate::Result<Vec<f32>>>()?,
4560 };
4561 let nr = NoiseReduction { on: flag(f[3])?, strength: float(f[4], n)?, floor_db: float(f[5], n)?, profile };
4562 if nr.clamped().as_ref() != Some(&nr) {
4563 return Err(range().into());
4564 }
4565 if nr.on && nr.profile.is_empty() {
4566 return Err(format!("line {n}: voice nr is on but has no noise profile").into());
4567 }
4568 voice.nr = nr;
4569 }
4570 b"comp" => {
4571 want(8, "comp")?;
4572 let c = Compressor {
4573 on: flag(f[3])?,
4574 threshold_db: float(f[4], n)?,
4575 ratio: float(f[5], n)?,
4576 attack_ms: float(f[6], n)?,
4577 release_ms: float(f[7], n)?,
4578 knee_db: float(f[8], n)?,
4579 makeup_db: float(f[9], n)?,
4580 auto_makeup: flag(f[10])?,
4581 };
4582 if c.clamped() != Some(c) {
4583 return Err(range().into());
4584 }
4585 voice.comp = c;
4586 }
4587 b"deess" => {
4588 want(5, "deess")?;
4589 let d = DeEsser {
4590 on: flag(f[3])?,
4591 threshold_db: float(f[4], n)?,
4592 amount: float(f[5], n)?,
4593 lo_hz: float(f[6], n)?,
4594 hi_hz: float(f[7], n)?,
4595 };
4596 if d.clamped() != Some(d) {
4597 return Err(range().into());
4598 }
4599 voice.deess = d;
4600 }
4601 other => {
4602 return Err(format!("line {n}: voice names {:?}, not a processor", String::from_utf8_lossy(other)).into());
4603 }
4604 }
4605 Ok(())
4606}
4607
4608/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
4609/// at all), or a line of a table that is already declared. Refused by the name
4610/// of what it points at, so the message reads as the file does.
4611fn table_index(
4612 field: Option<&[u8]>,
4613 len: usize,
4614 what: &str,
4615 line: usize,
4616) -> crate::Result<Option<u16>> {
4617 let field = match field {
4618 None | Some(b"-") => return Ok(None),
4619 Some(field) => field,
4620 };
4621 let i = number(field, line)?;
4622 if i as usize >= len || i > u32::from(u16::MAX) {
4623 return Err(format!("line {line}: clip names {what} {i} of {len}").into());
4624 }
4625 Ok(Some(i as u16))
4626}
4627
4628/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
4629fn band(field: &[u8], line: usize) -> crate::Result<Band> {
4630 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
4631 if parts.len() != 4 {
4632 return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
4633 }
4634 Ok(Band {
4635 freq_hz: float(parts[0], line)?,
4636 gain_db: float(parts[1], line)?,
4637 q: float(parts[2], line)?,
4638 kind: match parts[3] {
4639 b"ls" => BandKind::LowShelf,
4640 b"pk" => BandKind::Peak,
4641 b"hs" => BandKind::HighShelf,
4642 b"lc" => BandKind::LowCut,
4643 b"hc" => BandKind::HighCut,
4644 other => {
4645 return Err(format!(
4646 "line {line}: {:?} is not a band shape",
4647 String::from_utf8_lossy(other)
4648 )
4649 .into());
4650 }
4651 },
4652 })
4653}
4654
4655/// The `at:ease:values` points of an `mkeys` or `ekeys` line (`name`), in source order.
4656/// Each point holds one value per spec in `specs`, each within that spec's range, and the
4657/// rest of the key is zero. A custom bezier ease is read only from v56 on, and at most
4658/// [`MAX_TRANSFORM_KEYS`] points are read.
4659fn read_effect_keys(
4660 name: &str,
4661 points: &[&[u8]],
4662 specs: &[crate::effects::ParamSpec],
4663 n: usize,
4664 v56: bool,
4665) -> crate::Result<Vec<crate::effects::EffectKey>> {
4666 if points.len() > MAX_TRANSFORM_KEYS {
4667 return Err(format!("line {n}: {name} has more than {MAX_TRANSFORM_KEYS} keys").into());
4668 }
4669 let mut keys: Vec<crate::effects::EffectKey> = Vec::new();
4670 for point in points {
4671 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
4672 if parts.len() != 3 {
4673 return Err(format!("line {n}: {name} key wants at:ease:values").into());
4674 }
4675 let at = number(parts[0], n)?;
4676 let ease = KeyEase::from_token(parts[1])
4677 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
4678 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease, hold or a bezier curve"))?;
4679 if keys.last().is_some_and(|k| k.at >= at) {
4680 return Err(format!("line {n}: {name} keys are not in source order").into());
4681 }
4682 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
4683 if v.len() != specs.len() {
4684 return Err(format!("line {n}: {name} key wants {} values", specs.len()).into());
4685 }
4686 let mut values = [0.0f32; crate::effects::MAX_PARAMS];
4687 for (i, (x, field)) in values.iter_mut().zip(&v).enumerate() {
4688 *x = float(field, n)?;
4689 if !(specs[i].min..=specs[i].max).contains(x) {
4690 return Err(format!("line {n}: {name} {} is out of its range", specs[i].name).into());
4691 }
4692 }
4693 keys.push(crate::effects::EffectKey { at, values, ease });
4694 }
4695 Ok(keys)
4696}
4697
4698/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
4699/// and NaN are refused rather than carried -- they are the values a coefficient
4700/// cannot be built from, and the ones that would not compare equal to
4701/// themselves on the way back.
4702fn float(field: &[u8], line: usize) -> crate::Result<f32> {
4703 match std::str::from_utf8(field)
4704 .ok()
4705 .and_then(|s| s.parse::<f32>().ok())
4706 .filter(|f| f.is_finite())
4707 {
4708 Some(f) => Ok(f),
4709 None => Err(format!(
4710 "line {line}: {:?} is not a number",
4711 String::from_utf8_lossy(field)
4712 )
4713 .into()),
4714 }
4715}
4716
4717/// A clip's visualizer field: every bit of the byte is a flag
4718/// ([`crate::decode::VIZ_STYLE_FILL`]'s low bits, the fast bit, the ink
4719/// nibble), so a line naming one past what a byte holds is a look this
4720/// program does not have rather than a 300 that quietly loads as a 44.
4721fn flags_byte(field: &[u8], line: usize) -> crate::Result<u8> {
4722 let n = number(field, line)?;
4723 u8::try_from(n).map_err(|_| format!("line {line}: {n} is not a set of visualizer flags").into())
4724}
4725
4726fn number(field: &[u8], line: usize) -> crate::Result<u32> {
4727 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4728 Some(n) => Ok(n),
4729 None => Err(format!(
4730 "line {line}: {:?} is not a number",
4731 String::from_utf8_lossy(field)
4732 )
4733 .into()),
4734 }
4735}
4736
4737/// [`number`] for the one field wider than a `u32`: the clip's packed
4738/// visualizer look, whose strand-colour half needs the width (v23).
4739fn number64(field: &[u8], line: usize) -> crate::Result<u64> {
4740 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4741 Some(n) => Ok(n),
4742 None => Err(format!(
4743 "line {line}: {:?} is not a number",
4744 String::from_utf8_lossy(field)
4745 )
4746 .into()),
4747 }
4748}
4749
4750/// A `sub` line's window field: microseconds, which is the clock a cue is timed
4751/// in ([`crate::subtitle::Cue`]) and the one thing in this format counted in
4752/// something other than frames. Signed as the cues are, and the negative half
4753/// is refused by the never-empty check at the line, not here.
4754fn micros(field: &[u8], line: usize) -> crate::Result<i64> {
4755 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4756 Some(n) => Ok(n),
4757 None => Err(format!(
4758 "line {line}: {:?} is not a number",
4759 String::from_utf8_lossy(field)
4760 )
4761 .into()),
4762 }
4763}
4764
4765/// A `cue` line's text: the backslash that escapes it and the two line breaks,
4766/// which are the only bytes a line cannot hold (and `\r` is spelled too, so a
4767/// text ending in one does not look like a CRLF file to a hand-editor).
4768fn escape_text(text: &str, out: &mut Vec<u8>) {
4769 for c in text.chars() {
4770 match c {
4771 '\\' => out.extend_from_slice(b"\\\\"),
4772 '\n' => out.extend_from_slice(b"\\n"),
4773 '\r' => out.extend_from_slice(b"\\r"),
4774 c => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
4775 }
4776 }
4777}
4778
4779/// Undoes [`escape_text`]. Anything but the three escapes is refused by name,
4780/// so a hand-edited typo does not quietly become a different word.
4781fn unescape_text(field: &[u8], line: usize) -> crate::Result<String> {
4782 let mut out = Vec::with_capacity(field.len());
4783 let mut bytes = field.iter().copied();
4784 while let Some(b) = bytes.next() {
4785 if b != b'\\' {
4786 out.push(b);
4787 continue;
4788 }
4789 match bytes.next() {
4790 Some(b'\\') => out.push(b'\\'),
4791 Some(b'n') => out.push(b'\n'),
4792 Some(b'r') => out.push(b'\r'),
4793 _ => return Err(format!("line {line}: cue text has a bad escape").into()),
4794 }
4795 }
4796 String::from_utf8(out)
4797 .map_err(|_| -> crate::Error { format!("line {line}: cue text is not UTF-8").into() })
4798}
4799
4800/// The two bytes a line-based format cannot hold, and the escape byte itself.
4801fn escape(path: &Path, out: &mut Vec<u8>) {
4802 for &b in path.as_os_str().as_bytes() {
4803 match b {
4804 b'%' => out.extend_from_slice(b"%25"),
4805 b'\n' => out.extend_from_slice(b"%0A"),
4806 _ => out.push(b),
4807 }
4808 }
4809}
4810
4811/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
4812/// may spell a space or a quote that way, and there is no reason to refuse it.
4813fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
4814 let mut out = Vec::with_capacity(field.len());
4815 let mut i = 0;
4816 while i < field.len() {
4817 if field[i] != b'%' {
4818 out.push(field[i]);
4819 i += 1;
4820 continue;
4821 }
4822 let byte = field
4823 .get(i + 1..i + 3)
4824 .and_then(|h| std::str::from_utf8(h).ok())
4825 .and_then(|h| u8::from_str_radix(h, 16).ok())
4826 .ok_or_else(|| -> crate::Error {
4827 format!("line {line}: truncated % escape in the path").into()
4828 })?;
4829 out.push(byte);
4830 i += 3;
4831 }
4832 Ok(PathBuf::from(OsString::from_vec(out)))
4833}
4834
4835#[cfg(test)]
4836mod tests {
4837 use super::*;
4838
4839 /// [`super::emit`] for a project whose mix is flat: every lane at unity, no
4840 /// limiter, no rate written. Shadows the real one for the tests that were
4841 /// written before there was a mix to write -- the dialect they are about is
4842 /// the one this emits, and a v9 file with flat settings is a v8 file bar
4843 /// its version line, which is exactly what they assert.
4844 #[allow(clippy::too_many_arguments)]
4845 fn emit(
4846 dir: &Path,
4847 sources: &[Source],
4848 lanes: &[(LaneKind, Vec<Clip>)],
4849 eq: &[EqParams],
4850 color: &[ColorParams],
4851 resolution: (u32, u32),
4852 playhead: u32,
4853 ) -> Vec<u8> {
4854 super::emit(
4855 dir,
4856 sources,
4857 lanes,
4858 &[],
4859 &[],
4860 &[],
4861 eq,
4862 color,
4863 &[],
4864 resolution,
4865 None,
4866 crate::tonemap::Preset::default(),
4867 false,
4868 true,
4869 crate::export::EncoderSeat::default(),
4870 Limiter::default(),
4871 None,
4872 playhead,
4873 )
4874 }
4875
4876 /// A subtitle track as a save hands one over: the cues are not written and
4877 /// so are not here either.
4878 fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack {
4879 SubtitleTrack {
4880 path: PathBuf::from(path),
4881 track,
4882 language: String::new(),
4883 name: String::new(),
4884 label: String::new(),
4885 cues: Vec::new(),
4886 bitmap: false,
4887 refused: None,
4888 }
4889 }
4890
4891 /// The v24 `cue` line: a retyped cue's words escape the backslash and the
4892 /// two line breaks, come back exactly, and a line that names no track it
4893 /// has, or spells an escape it does not know, is refused by name.
4894 #[test]
4895 fn cue_lines_round_trip_their_text_and_refuse_what_they_cannot_name() {
4896 let dir = PathBuf::from("/proj");
4897 let doc = parse(
4898 b"edith 24\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
4899 cue 0 2 a \\\\ b\\nc\\r\\nd\ncue 0 0 \n",
4900 &dir,
4901 )
4902 .expect("two cue lines parse");
4903 assert_eq!(
4904 doc.cue_edits,
4905 [(0, 2, "a \\ b\nc\r\nd".to_string()), (0, 0, String::new())]
4906 );
4907
4908 // The writer's own spelling reads back as the same text, whatever is in it.
4909 let text = "back\\slash\nnew\rline \\n is not a newline";
4910 let mut out = Vec::new();
4911 escape_text(text, &mut out);
4912 assert_eq!(unescape_text(&out, 1).expect("its own escapes"), text);
4913
4914 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
4915 let head = b"edith 24\nsubtitle - subs.srt\n";
4916 let with = |line: &[u8]| [head.as_slice(), line].concat();
4917 assert!(refuse(&with(b"cue 1 0 x\n")).contains("names subtitle track 1 of 1"));
4918 assert!(refuse(&with(b"cue 0 0 \\q\n")).contains("bad escape"));
4919 assert!(refuse(&with(b"cue 0 0\n")).contains("without its text"));
4920 assert!(refuse(&with(b"cue 0\n")).contains("without a cue index"));
4921 assert!(
4922 refuse(b"edith 23\nsubtitle - subs.srt\ncue 0 0 x\n").contains("unknown keyword"),
4923 "a cue line before v24 is not a dialect"
4924 );
4925 }
4926
4927 /// The v10 line: which track of which file, written beside the sources and
4928 /// read back as the pair a load opens. And what a v9 file is -- one with no
4929 /// subtitles at all, which still opens and re-saves as v10.
4930 #[test]
4931 fn subtitles_round_trip_as_references_and_a_v9_file_has_none() {
4932 let dir = PathBuf::from("/proj");
4933 let (_, sources, lanes) = doc();
4934 let tracks = [
4935 subtitle("/proj/subs.srt", None),
4936 subtitle("/proj/a.mp4", Some(3)),
4937 subtitle("/elsewhere/od d name.ass", None),
4938 ];
4939 let bytes = super::emit(
4940 &dir,
4941 &sources,
4942 &lanes,
4943 &[],
4944 &[],
4945 &tracks,
4946 &[],
4947 &[],
4948 &[],
4949 (1280, 720),
4950 None,
4951 crate::tonemap::Preset::default(),
4952 false,
4953 true,
4954 crate::export::EncoderSeat::default(),
4955 Limiter::default(),
4956 None,
4957 0,
4958 );
4959 let text = String::from_utf8_lossy(&bytes);
4960 assert!(
4961 text.contains(
4962 "subtitle - subs.srt\n\
4963 subtitle 3 a.mp4\n\
4964 subtitle - /elsewhere/od d name.ass\n"
4965 ),
4966 "the path is relative where it can be, and runs to the end of its \
4967 line, spaces and all: {text}"
4968 );
4969 let back = parse(&bytes, &dir).expect("v10 parses");
4970 assert_eq!(
4971 back.subtitles,
4972 vec![
4973 (PathBuf::from("/proj/subs.srt"), None),
4974 (PathBuf::from("/proj/a.mp4"), Some(3)),
4975 (PathBuf::from("/elsewhere/od d name.ass"), None),
4976 ]
4977 );
4978
4979 // A v9 file is a project with no subtitles, and re-saving it writes v10.
4980 let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
4981 video 1 0 0 30 0 - - - fit 1000\n";
4982 let old = parse(v9, &dir).expect("v9 still loads");
4983 assert_eq!(old.subtitles, Vec::new());
4984 assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 30\n"));
4985 // ...and the line itself is not a v9 line: a dialect may not be mixed.
4986 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
4987 .unwrap_err()
4988 .to_string();
4989 assert_eq!(mixed, "line 3: unknown keyword \"subtitle\"");
4990 // A subtitle line with no path is refused, as a source with none is.
4991 for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] {
4992 let file = format!("edith 10\nsource 0 a.mp4\n{line}");
4993 assert!(
4994 parse(file.as_bytes(), &dir).is_err(),
4995 "{line:?} is not a subtitle line"
4996 );
4997 }
4998 }
4999
5000 /// The v33 `sublang` line: a track's language is written after the subtitle
5001 /// lines and comes back on that track. A project with no language writes no
5002 /// line and keeps its old header, and a line that names no track, has no
5003 /// language, or sits in a dialect before v33 is refused.
5004 #[test]
5005 fn sublang_lines_round_trip_and_a_project_with_none_is_unchanged() {
5006 let dir = PathBuf::from("/proj");
5007 let (_, sources, lanes) = doc();
5008 let save = |tracks: &[SubtitleTrack]| {
5009 super::emit(
5010 &dir,
5011 &sources,
5012 &lanes,
5013 &[],
5014 &[],
5015 tracks,
5016 &[],
5017 &[],
5018 &[],
5019 (1280, 720),
5020 None,
5021 crate::tonemap::Preset::default(),
5022 false,
5023 true,
5024 crate::export::EncoderSeat::default(),
5025 Limiter::default(),
5026 None,
5027 0,
5028 )
5029 };
5030 let mut eng = subtitle("/proj/subs.srt", None);
5031 eng.language = "eng".into();
5032 let mut fra = subtitle("/proj/a.mp4", Some(3));
5033 fra.language = "fra".into();
5034 let bytes = save(&[eng, fra]);
5035 let text = String::from_utf8_lossy(&bytes);
5036 assert!(text.starts_with("edith 33\n"), "a language makes it v33: {text}");
5037 assert!(
5038 text.contains("subtitle - subs.srt\nsubtitle 3 a.mp4\nsublang 0 eng\nsublang 1 fra\n"),
5039 "{text}"
5040 );
5041 let back = parse(&bytes, &dir).expect("v33 parses");
5042 assert_eq!(back.sub_langs, [(0, "eng".to_string()), (1, "fra".to_string())]);
5043
5044 // No language anywhere: no line, and the header is the one it was.
5045 let bare = save(&[subtitle("/proj/subs.srt", None)]);
5046 let text = String::from_utf8_lossy(&bare);
5047 assert!(!text.contains("sublang") && !text.starts_with("edith 33"), "{text}");
5048 assert!(parse(&bare, &dir).expect("parses").sub_langs.is_empty());
5049
5050 // A v32 file has no languages and loads as it did.
5051 let v32 = b"edith 32\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n";
5052 assert!(parse(v32, &dir).expect("v32 loads").sub_langs.is_empty());
5053
5054 // The refusals: a track that is not there, an empty language, and a
5055 // line in a dialect before v33.
5056 let head = "edith 33\nsource 0 a.mp4\nsubtitle - subs.srt\n";
5057 for line in ["sublang 1 eng\n", "sublang 0\n", "sublang x eng\n"] {
5058 assert!(
5059 parse(format!("{head}{line}").as_bytes(), &dir).is_err(),
5060 "{line:?} is not a sublang line"
5061 );
5062 }
5063 let old = b"edith 32\nsource 0 a.mp4\nsubtitle - subs.srt\nsublang 0 eng\n";
5064 assert_eq!(
5065 parse(old, &dir).unwrap_err().to_string(),
5066 "line 4: unknown keyword \"sublang\""
5067 );
5068 }
5069
5070 /// The caption's group field (v16): written only when the caption is in a
5071 /// group -- so a project nobody grouped a caption in is the same bytes it
5072 /// was in v15 -- read back as the id, and refused in an older dialect,
5073 /// which never wrote one.
5074 #[test]
5075 fn a_caption_group_round_trips_and_an_old_dialect_refuses_the_field() {
5076 let dir = PathBuf::from("/proj");
5077 let caption = |start: u32, frames: u32, link| SubClip {
5078 start,
5079 frames,
5080 track: 0,
5081 in_us: 0,
5082 out_us: i64::from(frames) * 1_000_000,
5083 link,
5084 };
5085 let lanes = vec![
5086 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(7))]),
5087 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(7))]),
5088 (LaneKind::Subtitle, Vec::new()),
5089 ];
5090 let subs = vec![
5091 vec![],
5092 vec![],
5093 vec![caption(0, 30, Some(7)), caption(40, 10, None)],
5094 ];
5095 let bytes = super::emit(
5096 &dir,
5097 &doc().1,
5098 &lanes,
5099 &[],
5100 &subs,
5101 &[subtitle("/proj/subs.srt", None)],
5102 &[],
5103 &[],
5104 &[],
5105 (1280, 720),
5106 None,
5107 crate::tonemap::Preset::default(),
5108 false,
5109 true,
5110 crate::export::EncoderSeat::default(),
5111 Limiter::default(),
5112 None,
5113 0,
5114 );
5115 let text = String::from_utf8_lossy(&bytes);
5116 assert!(
5117 text.contains("sub 1 0 30 0 0 30000000 7\n"),
5118 "the grouped caption carries its id: {text}"
5119 );
5120 assert!(
5121 text.contains("sub 1 40 10 0 0 10000000\n"),
5122 "a caption in no group writes no field: {text}"
5123 );
5124 let back = parse(&bytes, &dir).expect("v16 parses");
5125 assert_eq!(back.subs[2][0].link, Some(7));
5126 assert_eq!(back.subs[2][1].link, None);
5127
5128 // The older dialect never wrote a sixth field, and one claiming to be
5129 // it is a file this parser refuses by name.
5130 let v15 = parse(
5131 b"edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
5132 sub 1 0 30 0 0 30000000 7\n",
5133 &dir,
5134 )
5135 .unwrap_err()
5136 .to_string();
5137 assert_eq!(v15, "line 6: sub wants 5 fields, found 6");
5138 }
5139
5140 /// The v12 line: whether the project is cut on the stand-ins, written only
5141 /// when it is -- and the dialect before it, which had no stand-ins and
5142 /// whose bytes are therefore unchanged bar the version.
5143 #[test]
5144 fn the_proxy_switch_round_trips_and_a_v11_file_is_cut_on_its_films() {
5145 let dir = PathBuf::from("/proj");
5146 let (_, sources, lanes) = doc();
5147 let bytes = |proxy| {
5148 super::emit(
5149 &dir,
5150 &sources,
5151 &lanes,
5152 &[],
5153 &[],
5154 &[],
5155 &[],
5156 &[],
5157 &[],
5158 (1280, 720),
5159 None,
5160 crate::tonemap::Preset::default(),
5161 proxy,
5162 true,
5163 crate::export::EncoderSeat::default(),
5164 Limiter::default(),
5165 None,
5166 0,
5167 )
5168 };
5169 let on = bytes(true);
5170 assert!(
5171 String::from_utf8_lossy(&on).contains("proxy on\n"),
5172 "{}",
5173 String::from_utf8_lossy(&on)
5174 );
5175 assert!(parse(&on, &dir).expect("v12 parses").proxy);
5176 let off = bytes(false);
5177 assert!(
5178 !String::from_utf8_lossy(&off).contains("proxy"),
5179 "off is the line left out"
5180 );
5181 assert!(!parse(&off, &dir).expect("v12 parses").proxy);
5182
5183 // A v11 project is one cut on the films themselves, and it still loads.
5184 let v11 = b"edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5185 video 1 0 0 30 0 - - - fit 1000\n";
5186 let old = parse(v11, &dir).expect("v11 still loads");
5187 assert!(!old.proxy);
5188 assert_eq!(old.sources.len(), 1, "the rest of it came back too");
5189 // ...and the line is not a v11 line: a dialect may not be mixed.
5190 let mixed = parse(b"edith 11\nsource 0 a.mp4\nproxy on\n", &dir)
5191 .unwrap_err()
5192 .to_string();
5193 assert_eq!(mixed, "line 3: unknown keyword \"proxy\"");
5194 // Anything but on or off is a corrupt line, by name.
5195 for line in ["proxy\n", "proxy yes\n", "proxy On\n"] {
5196 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5197 assert!(
5198 parse(file.as_bytes(), &dir).is_err(),
5199 "{line:?} is not a proxy line"
5200 );
5201 }
5202 }
5203
5204 /// The v13 line: whether an import makes a stand-in by itself. Written the
5205 /// other way up from every other switch here -- on is the default and the
5206 /// line left out -- because that is what every dialect before it did, and a
5207 /// v12 file must come back doing it.
5208 #[test]
5209 fn the_auto_proxy_switch_round_trips_and_a_v12_file_makes_them_by_itself() {
5210 let dir = PathBuf::from("/proj");
5211 let (_, sources, lanes) = doc();
5212 let bytes = |proxy, auto| {
5213 super::emit(
5214 &dir,
5215 &sources,
5216 &lanes,
5217 &[],
5218 &[],
5219 &[],
5220 &[],
5221 &[],
5222 &[],
5223 (1280, 720),
5224 None,
5225 crate::tonemap::Preset::default(),
5226 proxy,
5227 auto,
5228 crate::export::EncoderSeat::default(),
5229 Limiter::default(),
5230 None,
5231 0,
5232 )
5233 };
5234 // The default is the line left out, and the two switches are two lines:
5235 // a project cut on stand-ins it does not make writes both.
5236 let on = bytes(false, true);
5237 assert!(
5238 !String::from_utf8_lossy(&on).contains("autoproxy"),
5239 "on is the line left out: {}",
5240 String::from_utf8_lossy(&on)
5241 );
5242 assert!(parse(&on, &dir).expect("v13 parses").auto_proxy);
5243 let off = bytes(true, false);
5244 let text = String::from_utf8_lossy(&off).to_string();
5245 assert!(text.contains("proxy on\nautoproxy off\n"), "{text}");
5246 let back = parse(&off, &dir).expect("v13 parses");
5247 assert!(back.proxy, "the other switch came back too");
5248 assert!(!back.auto_proxy);
5249
5250 // A v12 project made them by itself and could not be told otherwise.
5251 let v12 = b"edith 12\nplayhead 0\nresolution 1280 720\nproxy on\nsource 0 a.mp4\n\
5252 video 1 0 0 30 0 - - - fit 1000\n";
5253 let old = parse(v12, &dir).expect("v12 still loads");
5254 assert!(old.auto_proxy, "a v12 project made its stand-ins by itself");
5255 assert!(old.proxy, "the rest of it came back too");
5256 // ...and the line is not a v12 line: a dialect may not be mixed.
5257 let mixed = parse(b"edith 12\nsource 0 a.mp4\nautoproxy off\n", &dir)
5258 .unwrap_err()
5259 .to_string();
5260 assert_eq!(mixed, "line 3: unknown keyword \"autoproxy\"");
5261 // Anything but on or off is a corrupt line, by name.
5262 for line in ["autoproxy\n", "autoproxy no\n", "autoproxy Off\n"] {
5263 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5264 assert!(
5265 parse(file.as_bytes(), &dir).is_err(),
5266 "{line:?} is not an autoproxy line"
5267 );
5268 }
5269 }
5270
5271 /// The v14 line: which encoder an export writes the picture with, by name,
5272 /// read back as the very seat -- and the dialect before it, which had no
5273 /// way to say one and took whatever this machine had.
5274 #[test]
5275 fn the_encoder_seat_round_trips_by_name_and_a_v13_file_takes_the_machines() {
5276 use crate::export::EncoderSeat;
5277 let dir = PathBuf::from("/proj");
5278 let (_, sources, lanes) = doc();
5279 let bytes = |seat| {
5280 super::emit(
5281 &dir,
5282 &sources,
5283 &lanes,
5284 &[],
5285 &[],
5286 &[],
5287 &[],
5288 &[],
5289 &[],
5290 (1280, 720),
5291 None,
5292 crate::tonemap::Preset::default(),
5293 false,
5294 true,
5295 seat,
5296 Limiter::default(),
5297 None,
5298 0,
5299 )
5300 };
5301 // The default is the line left out, so a project nobody has picked a
5302 // seat for is the bytes a v13 file was bar the version line.
5303 let auto = bytes(EncoderSeat::Auto);
5304 assert!(
5305 !String::from_utf8_lossy(&auto).contains("encoder"),
5306 "auto is the line left out: {}",
5307 String::from_utf8_lossy(&auto)
5308 );
5309 assert_eq!(
5310 parse(&auto, &dir).expect("v14 parses").encoder,
5311 EncoderSeat::Auto
5312 );
5313 for seat in [EncoderSeat::Hardware, EncoderSeat::Software] {
5314 let written = bytes(seat);
5315 let text = String::from_utf8_lossy(&written).to_string();
5316 assert!(
5317 text.contains(&format!("encoder {}\n", seat.name())),
5318 "{text}"
5319 );
5320 assert_eq!(parse(&written, &dir).expect("v14 parses").encoder, seat);
5321 }
5322
5323 // A v13 project took the seat this machine had and could not be told
5324 // otherwise.
5325 let v13 = b"edith 13\nplayhead 0\nresolution 1280 720\nautoproxy off\nsource 0 a.mp4\n\
5326 video 1 0 0 30 0 - - - fit 1000\n";
5327 let old = parse(v13, &dir).expect("v13 still loads");
5328 assert_eq!(
5329 old.encoder,
5330 EncoderSeat::Auto,
5331 "a v13 project exported on whatever seat there was"
5332 );
5333 assert!(!old.auto_proxy, "the rest of it came back too");
5334 // ...and the line is not a v13 line: a dialect may not be mixed.
5335 let mixed = parse(b"edith 13\nsource 0 a.mp4\nencoder software\n", &dir)
5336 .unwrap_err()
5337 .to_string();
5338 assert_eq!(mixed, "line 3: unknown keyword \"encoder\"");
5339 // Anything but the three names is a corrupt line, by name.
5340 for line in ["encoder\n", "encoder gpu\n", "encoder Hardware\n"] {
5341 let file = format!("edith 15\nsource 0 a.mp4\n{line}");
5342 assert!(
5343 parse(file.as_bytes(), &dir).is_err(),
5344 "{line:?} is not an encoder line"
5345 );
5346 }
5347 }
5348
5349 /// The v17 line: an explicit sound rate, written only when picked and read
5350 /// back as the very number -- and a v16 file, which had no way to say one
5351 /// and meant the source's own probe, still opens with `None`.
5352 #[test]
5353 fn the_sample_rate_round_trips_and_a_v16_file_leaves_it_derived() {
5354 let dir = PathBuf::from("/proj");
5355 let (_, sources, lanes) = doc();
5356 let bytes = |rate| {
5357 super::emit(
5358 &dir,
5359 &sources,
5360 &lanes,
5361 &[],
5362 &[],
5363 &[],
5364 &[],
5365 &[],
5366 &[],
5367 (1280, 720),
5368 None,
5369 crate::tonemap::Preset::default(),
5370 false,
5371 true,
5372 crate::export::EncoderSeat::default(),
5373 Limiter::default(),
5374 rate,
5375 0,
5376 )
5377 };
5378 // Unset is the line left out, so a project nobody has chosen a rate for
5379 // is the bytes a v16 file was bar the version line.
5380 let unset = bytes(None);
5381 assert!(
5382 !String::from_utf8_lossy(&unset).contains("samplerate"),
5383 "no pick is the line left out: {}",
5384 String::from_utf8_lossy(&unset)
5385 );
5386 assert_eq!(parse(&unset, &dir).expect("v17 parses").sample_rate, None);
5387 for rate in [44_100, 48_000, 96_000] {
5388 let written = bytes(Some(rate));
5389 let text = String::from_utf8_lossy(&written).to_string();
5390 assert!(text.contains(&format!("samplerate {rate}\n")), "{text}");
5391 assert_eq!(
5392 parse(&written, &dir).expect("v17 parses").sample_rate,
5393 Some(rate)
5394 );
5395 }
5396 // A v16 project had no rate of its own to say: the field comes back
5397 // `None`, which is what "derive it from the source" already meant.
5398 let v16 = b"edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5399 video 1 0 0 30 0 - - - fit 1000\n";
5400 assert_eq!(parse(v16, &dir).expect("v16 still loads").sample_rate, None);
5401 // ...and the line is not a v16 line: a dialect may not be mixed.
5402 let mixed = parse(b"edith 16\nsource 0 a.mp4\nsamplerate 48000\n", &dir)
5403 .unwrap_err()
5404 .to_string();
5405 assert_eq!(mixed, "line 3: unknown keyword \"samplerate\"");
5406 // A number out of a sound rate's range is a corrupt line, by name.
5407 for line in ["samplerate 0\n", "samplerate 500000\n", "samplerate nope\n"] {
5408 let file = format!("edith 18\nsource 0 a.mp4\n{line}");
5409 assert!(
5410 parse(file.as_bytes(), &dir).is_err(),
5411 "{line:?} is not a sound rate line"
5412 );
5413 }
5414 }
5415
5416 /// The v11 line: the HDR rendition, written by name, read back as the very
5417 /// preset -- and the dialect before it, which had no way to say one and
5418 /// meant the published conversion.
5419 #[test]
5420 fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
5421 let dir = PathBuf::from("/proj");
5422 let (_, sources, lanes) = doc();
5423 for preset in crate::tonemap::Preset::ALL {
5424 let bytes = super::emit(
5425 &dir,
5426 &sources,
5427 &lanes,
5428 &[],
5429 &[],
5430 &[],
5431 &[],
5432 &[],
5433 &[],
5434 (1280, 720),
5435 None,
5436 preset,
5437 false,
5438 true,
5439 crate::export::EncoderSeat::default(),
5440 Limiter::default(),
5441 None,
5442 0,
5443 );
5444 let text = String::from_utf8_lossy(&bytes).to_string();
5445 assert_eq!(
5446 text.contains(&format!("tonemap {}\n", preset.name())),
5447 preset != crate::tonemap::Preset::default(),
5448 "the default is the line left out: {text}"
5449 );
5450 assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
5451 }
5452
5453 // A v10 file is a project shown the published way, and re-saving it
5454 // writes v11 with nothing more in it.
5455 let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5456 video 1 0 0 30 0 - - - fit 1000\n";
5457 let old = parse(v10, &dir).expect("v10 still loads");
5458 assert_eq!(old.tone, crate::tonemap::Preset::Reference);
5459 // ...and the line itself is not a v10 line: a dialect may not be mixed.
5460 let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
5461 .unwrap_err()
5462 .to_string();
5463 assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
5464 // A rendition nobody wrote is a corrupt line, by name -- not a silent
5465 // fall back to another picture.
5466 for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
5467 let file = format!("edith 11\nsource 0 a.mp4\n{line}");
5468 assert!(
5469 parse(file.as_bytes(), &dir).is_err(),
5470 "{line:?} is not a tonemap line"
5471 );
5472 }
5473 }
5474
5475 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
5476 Clip {
5477 speed_keys: Vec::new(),
5478 reversed: false,
5479 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5480 angle: Default::default(),
5481 fade_in: 0,
5482 fade_out: 0,
5483 transition_out: 0,
5484 transition_kind: Default::default(),
5485 visualizer: 0,
5486 viz_paint: 0,
5487 gain_db: 0.0,
5488 gain_keys: Vec::new(),
5489 pan: 0,
5490 transform_keys: Vec::new(),
5491 opacity_keys: Vec::new(),
5492 color_keys: Vec::new(),
5493 effects: Vec::new(),
5494 start,
5495 in_frame,
5496 out_frame,
5497 source,
5498 link,
5499 eq: None,
5500 color: None,
5501 transform: None,
5502 fit: FitPolicy::default(),
5503 speed: Speed::NORMAL,
5504 pitch: 0,
5505 }
5506 }
5507
5508 /// [`emit`] for a timeline that equalizes nothing, which is every case that
5509 /// predates the eq lines.
5510 fn flat(
5511 dir: &Path,
5512 sources: &[Source],
5513 lanes: &[(LaneKind, Vec<Clip>)],
5514 playhead: u32,
5515 ) -> Vec<u8> {
5516 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
5517 }
5518
5519 /// Two sources, one under the project's own directory and one not, a clip
5520 /// from each on the video lane, and an audio lane with a gap in the middle
5521 /// -- the shape every case below starts from.
5522 fn source(path: &str, audio_stream: usize) -> Source {
5523 Source {
5524 path: PathBuf::from(path),
5525 audio_stream,
5526 ..Default::default()
5527 }
5528 }
5529
5530 /// Lanes in display order, as [`Document::lanes`] holds them.
5531 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
5532
5533 /// `V1` then `A1`, the shape every dialect before v4 held.
5534 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
5535 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5536 }
5537
5538 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
5539 (
5540 PathBuf::from("/proj"),
5541 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
5542 two(
5543 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
5544 vec![clip(0, 0, 30, 0, Some(0))],
5545 ),
5546 )
5547 }
5548
5549 #[test]
5550 fn relative_and_absolute_paths_round_trip() {
5551 let (dir, sources, lanes) = doc();
5552 let bytes = flat(&dir, &sources, &lanes, 12);
5553 assert_eq!(
5554 String::from_utf8_lossy(&bytes),
5555 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
5556 source 2 /elsewhere/b.mp4\n\
5557 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0 - 0 0\n\
5558 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
5559 "the file under the project directory is written relative to it, \
5560 each with the audio stream it plays"
5561 );
5562 let back = parse(&bytes, &dir).expect("parse");
5563 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
5564 assert_eq!(
5565 back.lanes, lanes,
5566 "both lanes, in display order; the trailing gap needs no line"
5567 );
5568 assert_eq!(back.playhead, 12);
5569 // ...and emitting the parsed document reproduces the same bytes.
5570 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5571 }
5572
5573 /// The whole of the bump: a project of any number of lanes writes and reads
5574 /// back, in display order, empty lanes and cross-lane groups included.
5575 #[test]
5576 fn any_number_of_lanes_round_trips() {
5577 let dir = PathBuf::from("/proj");
5578 let sources = vec![source("/proj/a.mp4", 0)];
5579 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
5580 // shows, not video-then-audio -- with one take grouped across V1 and A2
5581 // (no paired ord, the lanes between them empty of it) and an A1 holding
5582 // nothing at all.
5583 let lanes = vec![
5584 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
5585 (LaneKind::Audio, Vec::new()),
5586 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
5587 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
5588 ];
5589 let bytes = flat(&dir, &sources, &lanes, 7);
5590 assert_eq!(
5591 String::from_utf8_lossy(&bytes),
5592 "edith 30\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
5593 video 1 0 0 30 0 4 - - fit 1000 0 0 0 - 0 0\naudio 1\n\
5594 video 2 40 0 10 0 - - - fit 1000 0 0 0 - 0 0\naudio 2 0 0 30 0 4 - - fit 1000 0 0 0 - 0 0\n",
5595 "an empty lane is a line of its own; everything else is its clips"
5596 );
5597 let back = parse(&bytes, &dir).expect("parse");
5598 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
5599 assert_eq!(back.playhead, 7);
5600 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5601
5602 // A lane number may not skip one of its kind: that lane was declared by
5603 // nothing, and the refusal names it.
5604 for (file, want) in [
5605 (
5606 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
5607 "line 3: lane V2 comes before V1",
5608 ),
5609 (
5610 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
5611 "line 4: lane A3 comes before A1",
5612 ),
5613 (
5614 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
5615 "line 3: lane numbers start at 1",
5616 ),
5617 // The clip fields are still the clip fields, one lane number on.
5618 (
5619 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
5620 "line 3: clip wants 5 fields, found 4",
5621 ),
5622 // ...and a v4 line in a v3 file reads as the garbled clip it is.
5623 (
5624 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
5625 "line 3: clip wants 5 fields, found 6",
5626 ),
5627 ] {
5628 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
5629 }
5630 // Lanes and nothing on them is the emptied timeline, saved: a project.
5631 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
5632 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
5633 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
5634 }
5635
5636 /// One band, spelled the way an eq line spells it.
5637 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
5638 Band {
5639 freq_hz,
5640 gain_db,
5641 q,
5642 kind,
5643 }
5644 }
5645
5646 /// The whole of the v5 bump: the clips name a shared equalizer table, the
5647 /// bytes are the ones documented at the top of this file, and every f32 in
5648 /// them comes back *bit* for bit -- which is what makes a re-save of a
5649 /// loaded project produce the same file rather than a drifting one.
5650 #[test]
5651 fn equalizers_round_trip_bit_exactly_and_are_shared() {
5652 let dir = PathBuf::from("/proj");
5653 let sources = vec![source("/proj/a.mp4", 0)];
5654 let eq = vec![
5655 EqParams {
5656 bands: vec![
5657 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
5658 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
5659 ],
5660 },
5661 // The awkward ones: a value needing all 24 mantissa bits, one whose
5662 // shortest spelling is exponential, a subnormal, and a negative
5663 // zero -- plus the empty cascade, which is a setting like any other.
5664 EqParams {
5665 bands: vec![band_of(
5666 16_777_215.0,
5667 -0.1,
5668 f32::MIN_POSITIVE / 3.0,
5669 BandKind::HighShelf,
5670 )],
5671 },
5672 EqParams { bands: Vec::new() },
5673 ];
5674 // Two clips share entry 0, so it is written once; one clip plays flat.
5675 let lanes = two(
5676 vec![
5677 Clip {
5678 fade_in: 0,
5679 fade_out: 0,
5680 transition_out: 0,
5681 transition_kind: Default::default(),
5682 visualizer: 0,
5683 viz_paint: 0,
5684 gain_db: 0.0,
5685 eq: Some(0),
5686 ..clip(0, 0, 30, 0, Some(0))
5687 },
5688 Clip {
5689 fade_in: 0,
5690 fade_out: 0,
5691 transition_out: 0,
5692 transition_kind: Default::default(),
5693 visualizer: 0,
5694 viz_paint: 0,
5695 gain_db: 0.0,
5696 eq: Some(1),
5697 ..clip(30, 10, 20, 0, None)
5698 },
5699 ],
5700 vec![
5701 Clip {
5702 fade_in: 0,
5703 fade_out: 0,
5704 transition_out: 0,
5705 transition_kind: Default::default(),
5706 visualizer: 0,
5707 viz_paint: 0,
5708 gain_db: 0.0,
5709 eq: Some(0),
5710 ..clip(0, 0, 30, 0, Some(0))
5711 },
5712 Clip {
5713 fade_in: 0,
5714 fade_out: 0,
5715 transition_out: 0,
5716 transition_kind: Default::default(),
5717 visualizer: 0,
5718 viz_paint: 0,
5719 gain_db: 0.0,
5720 eq: Some(2),
5721 ..clip(30, 0, 10, 0, None)
5722 },
5723 ],
5724 );
5725 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
5726 assert_eq!(
5727 String::from_utf8_lossy(&bytes),
5728 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5729 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
5730 eq 16777215.0:-0.1:3.918315e-39:hs\n\
5731 eq\n\
5732 video 1 0 0 30 0 0 0 - fit 1000 0 0 0 - 0 0\nvideo 1 30 10 20 0 - 1 - fit 1000 0 0 0 - 0 0\n\
5733 audio 1 0 0 30 0 0 0 - fit 1000 0 0 0 - 0 0\naudio 1 30 0 10 0 - 2 - fit 1000 0 0 0 - 0 0\n",
5734 "the table comes before the clips, and a clip names a line of it"
5735 );
5736
5737 let back = parse(&bytes, &dir).expect("parse");
5738 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
5739 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
5740 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
5741 assert_eq!(
5742 (
5743 got.freq_hz.to_bits(),
5744 got.gain_db.to_bits(),
5745 got.q.to_bits(),
5746 got.kind
5747 ),
5748 (
5749 want.freq_hz.to_bits(),
5750 want.gain_db.to_bits(),
5751 want.q.to_bits(),
5752 want.kind
5753 ),
5754 "eq {i} band {b} came back as other bits"
5755 );
5756 }
5757 }
5758 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
5759 assert_eq!(
5760 emit(
5761 &dir,
5762 &back.sources,
5763 &back.lanes,
5764 &back.eq,
5765 &back.color,
5766 (1280, 720),
5767 0
5768 ),
5769 bytes
5770 );
5771 }
5772
5773 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
5774 /// colour table, the bytes are the ones documented at the top of this file,
5775 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
5776 #[test]
5777 fn colours_round_trip_bit_exactly_and_are_shared() {
5778 let dir = PathBuf::from("/proj");
5779 let sources = vec![source("/proj/a.mp4", 0)];
5780 let color = vec![
5781 ColorParams {
5782 brightness: 0.1,
5783 contrast: 1.2,
5784 saturation: 0.9,
5785 tint: -0.3,
5786 ..Default::default()
5787 },
5788 // The awkward ones again: all 24 mantissa bits, an exponential
5789 // spelling, a subnormal and a negative zero -- and the identity,
5790 // which is a setting like any other.
5791 ColorParams {
5792 brightness: -0.000_000_1,
5793 contrast: 16_777_215.0,
5794 saturation: f32::MIN_POSITIVE / 3.0,
5795 tint: -0.0,
5796 ..Default::default()
5797 },
5798 ColorParams::default(),
5799 ];
5800 // Two clips share entry 0, so it is written once; one clip is ungraded.
5801 let lanes = two(
5802 vec![
5803 Clip {
5804 fade_in: 0,
5805 fade_out: 0,
5806 transition_out: 0,
5807 transition_kind: Default::default(),
5808 visualizer: 0,
5809 viz_paint: 0,
5810 gain_db: 0.0,
5811 color: Some(0),
5812 fit: FitPolicy::default(),
5813 speed: Speed::NORMAL,
5814 ..clip(0, 0, 30, 0, Some(0))
5815 },
5816 Clip {
5817 fade_in: 0,
5818 fade_out: 0,
5819 transition_out: 0,
5820 transition_kind: Default::default(),
5821 visualizer: 0,
5822 viz_paint: 0,
5823 gain_db: 0.0,
5824 color: Some(1),
5825 fit: FitPolicy::default(),
5826 speed: Speed::NORMAL,
5827 ..clip(30, 10, 20, 0, None)
5828 },
5829 ],
5830 vec![
5831 Clip {
5832 fade_in: 0,
5833 fade_out: 0,
5834 transition_out: 0,
5835 transition_kind: Default::default(),
5836 visualizer: 0,
5837 viz_paint: 0,
5838 gain_db: 0.0,
5839 color: Some(0),
5840 fit: FitPolicy::default(),
5841 speed: Speed::NORMAL,
5842 ..clip(0, 0, 30, 0, Some(0))
5843 },
5844 Clip {
5845 fade_in: 0,
5846 fade_out: 0,
5847 transition_out: 0,
5848 transition_kind: Default::default(),
5849 visualizer: 0,
5850 viz_paint: 0,
5851 gain_db: 0.0,
5852 color: Some(2),
5853 fit: FitPolicy::default(),
5854 speed: Speed::NORMAL,
5855 ..clip(30, 0, 10, 0, None)
5856 },
5857 ],
5858 );
5859 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
5860 assert_eq!(
5861 String::from_utf8_lossy(&bytes),
5862 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5863 color 0.1:1.2:0.9:-0.3\n\
5864 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
5865 color 0.0:1.0:1.0:0.0\n\
5866 video 1 0 0 30 0 0 - 0 fit 1000 0 0 0 - 0 0\nvideo 1 30 10 20 0 - - 1 fit 1000 0 0 0 - 0 0\n\
5867 audio 1 0 0 30 0 0 - 0 fit 1000 0 0 0 - 0 0\naudio 1 30 0 10 0 - - 2 fit 1000 0 0 0 - 0 0\n",
5868 "the table comes before the clips, and a clip names a line of it"
5869 );
5870
5871 let back = parse(&bytes, &dir).expect("parse");
5872 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
5873 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
5874 assert_eq!(
5875 (
5876 got.brightness.to_bits(),
5877 got.contrast.to_bits(),
5878 got.saturation.to_bits(),
5879 got.tint.to_bits()
5880 ),
5881 (
5882 want.brightness.to_bits(),
5883 want.contrast.to_bits(),
5884 want.saturation.to_bits(),
5885 want.tint.to_bits()
5886 ),
5887 "color {i} came back as other bits"
5888 );
5889 }
5890 assert_eq!(back.color.len(), 3);
5891 assert_eq!(
5892 emit(
5893 &dir,
5894 &back.sources,
5895 &back.lanes,
5896 &back.eq,
5897 &back.color,
5898 (1280, 720),
5899 0
5900 ),
5901 bytes
5902 );
5903 }
5904
5905 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
5906 /// intact, and re-saving it writes the new magic and a `-` colour field.
5907 #[test]
5908 fn a_v5_file_grades_nothing() {
5909 let dir = PathBuf::from("/proj");
5910 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
5911 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
5912 let old = parse(v5, &dir).expect("v5 parses");
5913 assert!(old.color.is_empty(), "nothing before v6 grades anything");
5914 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
5915 assert_eq!(old.lanes[0].1[0].eq, Some(0));
5916 assert!(old.lanes[0].1[0].color.is_none());
5917 assert_eq!(
5918 String::from_utf8_lossy(&emit(
5919 &dir,
5920 &old.sources,
5921 &old.lanes,
5922 &old.eq,
5923 &old.color,
5924 (1280, 720),
5925 old.playhead
5926 )),
5927 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5928 eq 80.0:-3.0:0.707:ls\n\
5929 video 1 0 0 30 0 0 0 - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n"
5930 );
5931 }
5932
5933 /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
5934 /// written on its own line, comes back as the very number that was set, and
5935 /// a v7 file -- which has no such field -- loads at real time and re-saves
5936 /// saying so.
5937 #[test]
5938 fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
5939 let dir = PathBuf::from("/proj");
5940 let sources = vec![Source::new("/proj/a.mp4", 0)];
5941 let speeded = |start, in_frame, out_frame, permille| Clip {
5942 speed_keys: Vec::new(),
5943 reversed: false,
5944 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5945 angle: Default::default(),
5946 fade_in: 0,
5947 fade_out: 0,
5948 transition_out: 0,
5949 transition_kind: Default::default(),
5950 visualizer: 0,
5951 viz_paint: 0,
5952 gain_db: 0.0,
5953 gain_keys: Vec::new(),
5954 pan: 0,
5955 transform_keys: Vec::new(),
5956 opacity_keys: Vec::new(),
5957 color_keys: Vec::new(),
5958 effects: Vec::new(),
5959 start,
5960 in_frame,
5961 out_frame,
5962 source: 0,
5963 link: None,
5964 eq: None,
5965 color: None,
5966 transform: None,
5967 fit: FitPolicy::default(),
5968 speed: Speed::from_permille(permille),
5969 pitch: 0,
5970 };
5971 // 30 source frames at 2x is 15 timeline frames, which is where the
5972 // second clip starts -- the file writes the source range and the rate,
5973 // and the length on the timeline is derived from the two.
5974 let lanes = vec![
5975 (
5976 LaneKind::Video,
5977 vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
5978 ),
5979 (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
5980 ];
5981 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
5982 assert_eq!(
5983 String::from_utf8_lossy(&bytes),
5984 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5985 video 1 0 0 30 0 - - - fit 2000 0 0 0 - 0 0\nvideo 1 15 30 40 0 - - - fit 250 0 0 0 - 0 0\n\
5986 audio 1 0 0 30 0 - - - fit 2000 0 0 0 - 0 0\n",
5987 "the rate is the clip line's last field, in thousandths"
5988 );
5989 let back = parse(&bytes, &dir).expect("parse");
5990 assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
5991
5992 // ...and the dialect before it, which had no rate to name.
5993 let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5994 video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
5995 let old = parse(v7, &dir).expect("v7 parses");
5996 assert!(
5997 old.lanes
5998 .iter()
5999 .flat_map(|(_, clips)| clips)
6000 .all(|c| c.speed == Speed::NORMAL),
6001 "nothing before v8 plays at anything but real time"
6002 );
6003 assert_eq!(
6004 String::from_utf8_lossy(&emit(
6005 &dir,
6006 &old.sources,
6007 &old.lanes,
6008 &old.eq,
6009 &old.color,
6010 (1280, 720),
6011 old.playhead
6012 )),
6013 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6014 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n"
6015 );
6016 // A rate outside what the editor can set is a corrupt line, by name.
6017 let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
6018 assert_eq!(
6019 parse(bad, &dir).unwrap_err().to_string(),
6020 "line 3: speed 9000 is outside 250-4000 thousandths"
6021 );
6022 }
6023
6024 #[test]
6025 fn a_v17_file_loads_with_zero_fades_and_fades_round_trip_bit_exactly() {
6026 let dir = PathBuf::from("/proj");
6027 // The v17 dialect: nine clip fields, the last the speed -- no fade
6028 // pair after it at all, not even zeroes.
6029 let v17 = b"edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6030 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6031 let old = parse(v17, &dir).expect("v17 parses");
6032 assert!(
6033 old.lanes
6034 .iter()
6035 .flat_map(|(_, clips)| clips)
6036 .all(|c| c.fade_in == 0 && c.fade_out == 0),
6037 "nothing before v18 had a fade to name"
6038 );
6039
6040 // ...and the dialect that does: nonzero fades on both edges, written
6041 // and read back as the very numbers.
6042 let sources = vec![Source::new("/proj/a.mp4", 0)];
6043 let faded = Clip {
6044 speed_keys: Vec::new(),
6045 reversed: false,
6046 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6047 angle: Default::default(),
6048 fade_in: 5,
6049 fade_out: 7,
6050 transition_out: 0,
6051 transition_kind: Default::default(),
6052 visualizer: 0,
6053 viz_paint: 0,
6054 gain_db: 0.0,
6055 gain_keys: Vec::new(),
6056 pan: 0,
6057 transform_keys: Vec::new(),
6058 opacity_keys: Vec::new(),
6059 color_keys: Vec::new(),
6060 effects: Vec::new(),
6061 start: 0,
6062 in_frame: 0,
6063 out_frame: 30,
6064 source: 0,
6065 link: None,
6066 eq: None,
6067 color: None,
6068 transform: None,
6069 fit: FitPolicy::default(),
6070 speed: Speed::NORMAL,
6071 pitch: 0,
6072 };
6073 let lanes = vec![(LaneKind::Video, vec![faded])];
6074 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6075 assert_eq!(
6076 String::from_utf8_lossy(&bytes),
6077 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6078 video 1 0 0 30 0 - - - fit 1000 5 7 0 - 0 0\n",
6079 "the fades are the clip line's last two fields"
6080 );
6081 let back = parse(&bytes, &dir).expect("parse");
6082 assert_eq!(
6083 back.lanes, lanes,
6084 "the fades round trip as the very numbers"
6085 );
6086 }
6087
6088 /// The whole of the v19 bump, the fade test's twin: a clip's dissolve into
6089 /// its successor is written as the clip line's own last field, comes back
6090 /// as the very number that was set, and a v18 file -- which has no such
6091 /// field -- loads with every clip's [`Clip::transition_out`] at zero and
6092 /// re-saves saying so.
6093 #[test]
6094 fn a_v18_file_loads_with_no_transition_and_transitions_round_trip_bit_exactly() {
6095 let dir = PathBuf::from("/proj");
6096 // The v18 dialect: eleven clip fields, the last the fade-out -- no
6097 // transition field after it at all, not even a zero.
6098 let v18 = b"edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6099 video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n";
6100 let old = parse(v18, &dir).expect("v18 parses");
6101 assert!(
6102 old.lanes
6103 .iter()
6104 .flat_map(|(_, clips)| clips)
6105 .all(|c| c.transition_out == 0),
6106 "nothing before v19 had a dissolve to name"
6107 );
6108
6109 // ...and the dialect that does: a nonzero dissolve, written and read
6110 // back as the very number.
6111 let sources = vec![Source::new("/proj/a.mp4", 0)];
6112 let dissolving = Clip {
6113 speed_keys: Vec::new(),
6114 reversed: false,
6115 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6116 angle: Default::default(),
6117 fade_in: 0,
6118 fade_out: 0,
6119 transition_out: 9,
6120 transition_kind: Default::default(),
6121 visualizer: 0,
6122 viz_paint: 0,
6123 gain_db: 0.0,
6124 gain_keys: Vec::new(),
6125 pan: 0,
6126 transform_keys: Vec::new(),
6127 opacity_keys: Vec::new(),
6128 color_keys: Vec::new(),
6129 effects: Vec::new(),
6130 start: 0,
6131 in_frame: 0,
6132 out_frame: 30,
6133 source: 0,
6134 link: None,
6135 eq: None,
6136 color: None,
6137 transform: None,
6138 fit: FitPolicy::default(),
6139 speed: Speed::NORMAL,
6140 pitch: 0,
6141 };
6142 let lanes = vec![(LaneKind::Video, vec![dissolving])];
6143 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6144 assert_eq!(
6145 String::from_utf8_lossy(&bytes),
6146 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6147 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n",
6148 "the dissolve is the clip line's own last field"
6149 );
6150 let back = parse(&bytes, &dir).expect("parse");
6151 assert_eq!(
6152 back.lanes, lanes,
6153 "the dissolve round trips as the very number"
6154 );
6155 }
6156
6157 /// The clip's packed look (v23): a chosen strand colour rides in the
6158 /// field's own bytes under the top bit and comes back bit-exact, a v22
6159 /// file's 32-bit value is the low half of that field with no strand
6160 /// colour, and a file older than the field itself is the zero it always
6161 /// was.
6162 #[test]
6163 fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() {
6164 use crate::decode::{
6165 VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue,
6166 with_viz_paint_strand_sat,
6167 };
6168 let (dir, sources, lanes) = doc();
6169 let mut painted = lanes.clone();
6170 // Azure, its dual half a chosen green rather than the automatic
6171 // complement of the clip's own hue.
6172 let chosen = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 64), 200);
6173 assert!(viz_strand_set(chosen));
6174 painted[0].1[0].viz_paint = chosen;
6175 let bytes = flat(&dir, &sources, &painted, 0);
6176 assert!(
6177 bytes.starts_with(b"edith 30\n"),
6178 "a project with a strand colour saves as v23: {}",
6179 String::from_utf8_lossy(&bytes)
6180 );
6181 let back = parse(&bytes, &dir).expect("v23 parses");
6182 assert_eq!(back.lanes, painted, "the look round-trips bit-exactly");
6183
6184 // A v22 file's field is a u32: the value lands in the low half
6185 // untouched, and a strand colour it cannot carry reads as auto.
6186 let look = VIZ_PAINT_AZURE as u32;
6187 let v22 = format!(
6188 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6189 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 {look}\n"
6190 );
6191 let old = parse(v22.as_bytes(), &dir).expect("v22 still loads");
6192 let paint = old.lanes[0].1[0].viz_paint;
6193 assert_eq!(paint, u64::from(look), "the low half is the v22 value");
6194 assert!(!viz_strand_set(paint), "a v22 look chose no strand colour");
6195 assert_eq!(viz_hue_ui(paint), 150);
6196 assert_eq!(viz_sat_ui(paint), 160);
6197 // ...and a file older than the field is the zero that means the
6198 // azure default, as it was before the field was widened.
6199 let v21 = b"edith 21\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6200 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0\n";
6201 let older = parse(v21, &dir).expect("v21 still loads");
6202 assert_eq!(older.lanes[0].1[0].viz_paint, 0);
6203 }
6204
6205 /// A v19 file is a v20 one that places no clip anywhere but its fit
6206 /// policy's own spot: it loads with every clip's [`Clip::transform`] at
6207 /// `None`, which is what a v19 file's missing field still means.
6208 #[test]
6209 fn a_v19_file_loads_untransformed() {
6210 let dir = PathBuf::from("/proj");
6211 // The v19 dialect: twelve clip fields, the last the transition -- no
6212 // transform field after it at all, not even a `-`.
6213 let v19 = b"edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6214 video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n";
6215 let old = parse(v19, &dir).expect("v19 parses");
6216 assert!(old.transform.is_empty(), "nothing before v20 has a table");
6217 assert!(
6218 old.lanes
6219 .iter()
6220 .flat_map(|(_, clips)| clips)
6221 .all(|c| c.transform.is_none()),
6222 "nothing before v20 had a placement to name"
6223 );
6224 }
6225
6226 /// [`colours_round_trip_bit_exactly_and_are_shared`]'s twin: two clips
6227 /// sharing one transform table entry write it once, and both bytes and
6228 /// values come back bit-exact.
6229 #[test]
6230 fn transforms_round_trip_bit_exactly_and_are_shared() {
6231 let dir = PathBuf::from("/proj");
6232 let sources = vec![source("/proj/a.mp4", 0)];
6233 let transform = vec![
6234 TransformParams {
6235 pos_x: 0.1,
6236 pos_y: -0.2,
6237 scale: 1.5,
6238 rotate: 90.0,
6239 crop_l: 0.1,
6240 crop_r: 0.0,
6241 crop_t: 0.0,
6242 crop_b: 0.05,
6243 opacity: 0.25,
6244 },
6245 // The awkward ones again: all 24 mantissa bits, an exponential
6246 // spelling, a subnormal and a negative zero -- and the identity,
6247 // which is a setting like any other.
6248 TransformParams {
6249 pos_x: -0.000_000_1,
6250 pos_y: 16_777_215.0,
6251 scale: f32::MIN_POSITIVE / 3.0,
6252 rotate: -0.0,
6253 crop_l: 0.0,
6254 crop_r: 0.0,
6255 crop_t: 0.0,
6256 crop_b: 0.0,
6257 opacity: 1.0,
6258 },
6259 TransformParams::default(),
6260 ];
6261 // Two clips share entry 0, so it is written once; one clip is untransformed.
6262 let lanes = two(
6263 vec![
6264 Clip {
6265 fade_in: 0,
6266 fade_out: 0,
6267 transition_out: 0,
6268 transition_kind: Default::default(),
6269 visualizer: 0,
6270 viz_paint: 0,
6271 gain_db: 0.0,
6272 transform: Some(0),
6273 fit: FitPolicy::default(),
6274 speed: Speed::NORMAL,
6275 ..clip(0, 0, 30, 0, Some(0))
6276 },
6277 Clip {
6278 fade_in: 0,
6279 fade_out: 0,
6280 transition_out: 0,
6281 transition_kind: Default::default(),
6282 visualizer: 0,
6283 viz_paint: 0,
6284 gain_db: 0.0,
6285 transform: Some(1),
6286 fit: FitPolicy::default(),
6287 speed: Speed::NORMAL,
6288 ..clip(30, 10, 20, 0, None)
6289 },
6290 ],
6291 vec![
6292 Clip {
6293 fade_in: 0,
6294 fade_out: 0,
6295 transition_out: 0,
6296 transition_kind: Default::default(),
6297 visualizer: 0,
6298 viz_paint: 0,
6299 gain_db: 0.0,
6300 transform: Some(0),
6301 fit: FitPolicy::default(),
6302 speed: Speed::NORMAL,
6303 ..clip(0, 0, 30, 0, Some(0))
6304 },
6305 Clip {
6306 fade_in: 0,
6307 fade_out: 0,
6308 transition_out: 0,
6309 transition_kind: Default::default(),
6310 visualizer: 0,
6311 viz_paint: 0,
6312 gain_db: 0.0,
6313 transform: Some(2),
6314 fit: FitPolicy::default(),
6315 speed: Speed::NORMAL,
6316 ..clip(30, 0, 10, 0, None)
6317 },
6318 ],
6319 );
6320 let bytes = super::emit(
6321 &dir,
6322 &sources,
6323 &lanes,
6324 &[],
6325 &[],
6326 &[],
6327 &[],
6328 &[],
6329 &transform,
6330 (1280, 720),
6331 None,
6332 crate::tonemap::Preset::default(),
6333 false,
6334 true,
6335 crate::export::EncoderSeat::default(),
6336 Limiter::default(),
6337 None,
6338 0,
6339 );
6340 assert_eq!(
6341 String::from_utf8_lossy(&bytes),
6342 "edith 31\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6343 transform 0.1:-0.2:1.5:90.0:0.1:0.0:0.0:0.05:0.25\n\
6344 transform -1e-7:16777215.0:3.918315e-39:-0.0:0.0:0.0:0.0:0.0\n\
6345 transform 0.0:0.0:1.0:0.0:0.0:0.0:0.0:0.0\n\
6346 video 1 0 0 30 0 0 - - fit 1000 0 0 0 0 0 0\nvideo 1 30 10 20 0 - - - fit 1000 0 0 0 1 0 0\n\
6347 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 0 0 0\naudio 1 30 0 10 0 - - - fit 1000 0 0 0 2 0 0\n",
6348 "the table comes before the clips, and a clip names a line of it"
6349 );
6350
6351 let back = parse(&bytes, &dir).expect("parse");
6352 assert_eq!(back.lanes, lanes, "every clip keeps the transform it named");
6353 for (i, (got, want)) in back.transform.iter().zip(&transform).enumerate() {
6354 assert_eq!(
6355 (
6356 got.pos_x.to_bits(),
6357 got.pos_y.to_bits(),
6358 got.scale.to_bits(),
6359 got.rotate.to_bits(),
6360 got.crop_l.to_bits(),
6361 got.crop_r.to_bits(),
6362 got.crop_t.to_bits(),
6363 got.crop_b.to_bits(),
6364 got.opacity.to_bits(),
6365 ),
6366 (
6367 want.pos_x.to_bits(),
6368 want.pos_y.to_bits(),
6369 want.scale.to_bits(),
6370 want.rotate.to_bits(),
6371 want.crop_l.to_bits(),
6372 want.crop_r.to_bits(),
6373 want.crop_t.to_bits(),
6374 want.crop_b.to_bits(),
6375 want.opacity.to_bits(),
6376 ),
6377 "transform {i} came back as other bits"
6378 );
6379 }
6380 assert_eq!(back.transform.len(), 3);
6381 }
6382
6383 /// The whole of the v9 bump, the speed test's twin: the mix a project was
6384 /// left at -- every track's own volume and the master limiter -- plus the
6385 /// rate it was cut at, all written, all read back as the very numbers, and
6386 /// a v8 file (which has none of them) loading flat and unlimited.
6387 #[test]
6388 fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
6389 let dir = PathBuf::from("/proj");
6390 let sources = vec![Source::new("/proj/a.mp4", 0)];
6391 let lanes = vec![
6392 (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
6393 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6394 // A second audio track, turned down: the gain lines are per lane,
6395 // so the two must not run into one another.
6396 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6397 ];
6398 let limiter = Limiter {
6399 ceiling_db: -1.5,
6400 on: true,
6401 };
6402 let bytes = super::emit(
6403 &dir,
6404 &sources,
6405 &lanes,
6406 &[0.0, 3.0, -6.5],
6407 &[],
6408 &[],
6409 &[],
6410 &[],
6411 &[],
6412 (1280, 720),
6413 Some(23.976023976023978),
6414 crate::tonemap::Preset::default(),
6415 false,
6416 true,
6417 crate::export::EncoderSeat::default(),
6418 limiter,
6419 None,
6420 0,
6421 );
6422 assert_eq!(
6423 String::from_utf8_lossy(&bytes),
6424 "edith 30\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
6425 limiter -1.5 on\nsource 0 a.mp4\n\
6426 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6427 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6428 gain audio 1 3.0\ngain audio 2 -6.5\n",
6429 "the mix is lines of its own, the gains after the lanes they name"
6430 );
6431 let back = parse(&bytes, &dir).expect("parse");
6432 assert_eq!(back.lanes, lanes);
6433 assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
6434 assert_eq!(back.limiter, limiter);
6435 assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
6436
6437 // ...and the dialect before it, which carried none of the three: a v8
6438 // file mixes flat, limits nothing, and says nothing about its rate.
6439 let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6440 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6441 let old = parse(v8, &dir).expect("v8 parses");
6442 assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
6443 assert_eq!(old.limiter, Limiter::default());
6444 assert_eq!(old.fps, None);
6445 // A v9 file may leave all three out too, and means the same thing.
6446 assert_eq!(
6447 String::from_utf8_lossy(&emit(
6448 &dir,
6449 &old.sources,
6450 &old.lanes,
6451 &old.eq,
6452 &old.color,
6453 (1280, 720),
6454 old.playhead
6455 )),
6456 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6457 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"
6458 );
6459
6460 // Each of the three refuses by name, on its own line.
6461 for (text, want) in [
6462 (
6463 "edith 9\nfps nope\nsource 0 a.mp4\n",
6464 "line 2: \"nope\" is not a frame rate",
6465 ),
6466 (
6467 "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
6468 "line 2: limiter is on or off, not \"maybe\"",
6469 ),
6470 (
6471 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
6472 "line 4: gain names a lane that is not there",
6473 ),
6474 (
6475 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
6476 "line 4: gain names \"lane\", not a lane kind",
6477 ),
6478 ] {
6479 assert_eq!(
6480 parse(text.as_bytes(), &dir).unwrap_err().to_string(),
6481 want,
6482 "{text:?}"
6483 );
6484 }
6485 // A hand-written ceiling nothing could limit at is clamped, not taken.
6486 let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
6487 assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
6488 }
6489
6490 /// The refusals the colour grammar adds, each naming its line.
6491 #[test]
6492 fn a_malformed_colour_names_its_line() {
6493 let dir = PathBuf::from("/proj");
6494 let head = "edith 6\nsource 0 a.mp4\n";
6495 // v6, deliberately: the colour grammar is the same one v7 inherits, and
6496 // a v6 clip line is one field shorter.
6497 for (file, want) in [
6498 (
6499 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
6500 "line 3: color wants 4 fields, found 3",
6501 ),
6502 (
6503 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"),
6504 "line 3: color wants 1 fields, found 2",
6505 ),
6506 (
6507 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6508 "line 3: \"warm\" is not a number",
6509 ),
6510 // The two values the format cannot write and read back as itself.
6511 (
6512 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6513 "line 3: \"inf\" is not a number",
6514 ),
6515 (
6516 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
6517 "line 3: \"NaN\" is not a number",
6518 ),
6519 (
6520 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
6521 "line 4: clip names color 1 of 1",
6522 ),
6523 (
6524 format!("{head}video 1 0 0 5 0 - - 0\n"),
6525 "line 3: clip names color 0 of 0",
6526 ),
6527 // A clip's colour field is not optional in v6, and the table has to
6528 // be declared before the clip that names it.
6529 (
6530 format!("{head}video 1 0 0 5 0 - -\n"),
6531 "line 3: clip wants 7 fields, found 6",
6532 ),
6533 (
6534 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
6535 "line 4: color after a clip",
6536 ),
6537 // ...and a colour line in a file that predates them is a corrupt one.
6538 (
6539 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
6540 "line 3: unknown keyword \"color\"",
6541 ),
6542 ] {
6543 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6544 }
6545 }
6546
6547 /// The cut shapes are two more spellings of the same band grammar: they
6548 /// round-trip bit-exactly like the others, and a cut's gain is written as
6549 /// it was given even though the filter ignores it.
6550 #[test]
6551 fn cut_bands_round_trip_as_lc_and_hc() {
6552 let dir = PathBuf::from("/proj");
6553 let sources = vec![source("/proj/a.mp4", 0)];
6554 let eq = vec![EqParams {
6555 bands: vec![
6556 band_of(80.0, 0.0, 0.707, BandKind::LowCut),
6557 band_of(12_000.0, -6.5, 0.5, BandKind::HighCut),
6558 ],
6559 }];
6560 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], Vec::new());
6561 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
6562 assert!(
6563 String::from_utf8_lossy(&bytes).contains("eq 80.0:0.0:0.707:lc 12000.0:-6.5:0.5:hc\n"),
6564 "the cut shapes are spelled lc and hc"
6565 );
6566
6567 let back = parse(&bytes, &dir).expect("parse");
6568 assert_eq!(back.eq, eq, "both cut bands come back as they went in");
6569 assert_eq!(back.lanes, lanes);
6570 }
6571
6572 /// The refusals the eq grammar adds, each naming its line.
6573 #[test]
6574 fn a_malformed_equalizer_names_its_line() {
6575 let dir = PathBuf::from("/proj");
6576 let head = "edith 5\nsource 0 a.mp4\n";
6577 for (file, want) in [
6578 (
6579 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
6580 "line 3: band wants 4 fields, found 3",
6581 ),
6582 (
6583 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
6584 "line 3: \"notch\" is not a band shape",
6585 ),
6586 (
6587 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
6588 "line 3: \"wide\" is not a number",
6589 ),
6590 // Neither of the two values a coefficient cannot be built from, and
6591 // NaN would not even compare equal to itself on the way back.
6592 (
6593 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6594 "line 3: \"inf\" is not a number",
6595 ),
6596 (
6597 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6598 "line 3: \"NaN\" is not a number",
6599 ),
6600 (
6601 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
6602 "line 4: clip names eq 1 of 1",
6603 ),
6604 (
6605 format!("{head}video 1 0 0 5 0 - 0\n"),
6606 "line 3: clip names eq 0 of 0",
6607 ),
6608 // A clip's eq field is not optional in v5, and the table has to be
6609 // declared before the clip that names it.
6610 (
6611 format!("{head}video 1 0 0 5 0 -\n"),
6612 "line 3: clip wants 6 fields, found 5",
6613 ),
6614 (
6615 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
6616 "line 4: eq after a clip",
6617 ),
6618 // ...and an eq line in a file that predates them is a corrupt file.
6619 (
6620 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
6621 "line 3: unknown keyword \"eq\"",
6622 ),
6623 ] {
6624 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6625 }
6626 }
6627
6628 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
6629 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
6630 /// and not one byte else.
6631 #[test]
6632 fn a_v4_file_equalizes_nothing() {
6633 let dir = PathBuf::from("/proj");
6634 let (_, sources, lanes) = doc();
6635 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6636 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
6637 let old = parse(v4, &dir).expect("v4 parses");
6638 assert_eq!(
6639 (&old.sources, &old.lanes, old.playhead),
6640 (&sources, &lanes, 12)
6641 );
6642 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
6643 assert_eq!(
6644 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
6645 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6646 source 2 /elsewhere/b.mp4\n\
6647 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0 - 0 0\n\
6648 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n"
6649 );
6650 // An empty lane's line is still the whole of that lane, eq or no eq.
6651 let empty = parse(
6652 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
6653 &dir,
6654 )
6655 .expect("parse");
6656 assert!(empty.lanes[1].1.is_empty());
6657 }
6658
6659 /// The other half of the compatibility promise: a v3 file is a v4 one
6660 /// without the lane numbers, and a v2 file names no audio stream and means
6661 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
6662 /// they always were, and saving either writes v5 with nothing else changed.
6663 #[test]
6664 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
6665 let dir = PathBuf::from("/proj");
6666 let (_, _, lanes) = doc();
6667 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6668 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6669 let old = parse(v3, &dir).expect("v3 parses");
6670 assert_eq!(
6671 (&old.sources, &old.lanes, old.playhead),
6672 (
6673 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
6674 &lanes,
6675 12
6676 ),
6677 "a v3 file loads as exactly the state its v5 twin does"
6678 );
6679 // ...and re-saved it *is* that twin: the magic and a lane number per
6680 // clip line, and not one byte else.
6681 assert_eq!(
6682 flat(&dir, &old.sources, &old.lanes, old.playhead),
6683 flat(&dir, &old.sources, &lanes, 12),
6684 );
6685
6686 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
6687 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6688 let back = parse(v2, &dir).expect("v2 parses");
6689 assert_eq!(
6690 back.sources,
6691 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
6692 );
6693 assert_eq!(back.lanes, lanes);
6694
6695 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6696 assert_eq!(
6697 String::from_utf8_lossy(&v5),
6698 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6699 source 0 /elsewhere/b.mp4\n\
6700 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\nvideo 1 30 10 20 1 1 - - fit 1000 0 0 0 - 0 0\n\
6701 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
6702 "a re-saved v2 project differs only by its version, the lane \
6703 numbers, the streams it always meant and an equalizer it has none of"
6704 );
6705 let again = parse(&v5, &dir).expect("v5 parses");
6706 assert_eq!(again.sources, back.sources);
6707 }
6708
6709 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
6710 /// lanes, and saving it again writes v5.
6711 #[test]
6712 fn a_v1_file_loads_as_two_grouped_lanes() {
6713 let dir = PathBuf::from("/proj");
6714 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
6715 let back = parse(v1, &dir).expect("v1 parses");
6716 assert_eq!(
6717 back.lanes[0].1,
6718 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
6719 "v1 clips queue up: the second starts where the first ended"
6720 );
6721 assert_eq!(
6722 back.lanes,
6723 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
6724 "one take per clip, on both lanes"
6725 );
6726 assert_eq!(back.playhead, 5);
6727 // Saved again it is the current version, which round-trips to the
6728 // same document.
6729 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6730 assert!(v5.starts_with(b"edith 30\n"));
6731 let again = parse(&v5, &dir).expect("v5 parses");
6732 assert_eq!(again.lanes, back.lanes);
6733 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
6734 for (bytes, want) in [
6735 (
6736 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
6737 "line 3: unknown keyword \"video\"",
6738 ),
6739 (
6740 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
6741 "line 3: unknown keyword \"clip\"",
6742 ),
6743 ] {
6744 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
6745 }
6746 }
6747
6748 /// A gap is the absence of a line, so a lane's placements must arrive in
6749 /// order and never overlap -- the invariant the whole model rests on.
6750 #[test]
6751 fn a_lane_out_of_order_or_overlapping_is_refused() {
6752 let dir = PathBuf::from("/proj");
6753 for bytes in [
6754 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
6755 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
6756 ] {
6757 let err = parse(bytes, &dir).unwrap_err().to_string();
6758 assert!(err.starts_with("line 4: clip at "), "{err}");
6759 }
6760 // The lanes are independent, so a video line never crowds an audio one.
6761 assert!(
6762 parse(
6763 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
6764 &dir
6765 )
6766 .is_ok()
6767 );
6768 // ...and a lane may be empty as long as the other one is not.
6769 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
6770 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
6771 }
6772
6773 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
6774 /// and wrap in release, and a wrapped end passes the overlap check --
6775 /// crafted numbers must be refused by name, in both dialects.
6776 #[test]
6777 fn a_clip_whose_end_overflows_is_refused() {
6778 let dir = PathBuf::from("/proj");
6779 for bytes in [
6780 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
6781 // Two of them: the second would land *before* the first once wrapped.
6782 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
6783 // v1 has no `start` field, but its queue reaches the same ceiling.
6784 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
6785 ] {
6786 let err = parse(bytes, &dir).unwrap_err().to_string();
6787 assert!(
6788 err.contains("runs past the last frame there is"),
6789 "not refused by name: {err}"
6790 );
6791 }
6792 }
6793
6794 /// The relocatability promise, from the two directions a project path
6795 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
6796 /// clip.mp4`, whose parent is `""`) and a directory reached through a
6797 /// symlink. Both used to emit absolute source lines.
6798 #[test]
6799 fn a_non_canonical_project_path_still_writes_relative_sources() {
6800 assert_eq!(
6801 project_dir(Path::new("a.edith")),
6802 std::env::current_dir().expect("cwd"),
6803 "a bare filename is saved into the working directory"
6804 );
6805
6806 let dir = crate::scratch::Scratch::dir("ve_edith_link");
6807 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
6808 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
6809 let source = dir.join("real/a.mp4");
6810 let path = dir.join("link/p.edith");
6811
6812 let one = [clip(0, 0, 30, 0, None)];
6813 let entry = Source {
6814 path: source,
6815 audio_stream: 1, ..Default::default()
6816 };
6817 save(
6818 &path,
6819 &[entry],
6820 &two(one.to_vec(), one.to_vec()),
6821 &[],
6822 &[],
6823 &[],
6824 &[],
6825 &[],
6826 &[],
6827 (1280, 720),
6828 None,
6829 crate::tonemap::Preset::default(),
6830 false,
6831 true,
6832 crate::export::EncoderSeat::default(),
6833 Limiter::default(),
6834 None,
6835 0,
6836 )
6837 .expect("save");
6838 let bytes = std::fs::read(&path).expect("read back");
6839 assert_eq!(
6840 String::from_utf8_lossy(&bytes),
6841 "edith 30\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
6842 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"
6843 );
6844 // Loading rejoins the *given* directory, so the file is reached by the
6845 // way the project was opened -- the same file, through the link, still
6846 // playing the stream it was saved on.
6847 assert_eq!(
6848 load(&path).expect("load").sources,
6849 vec![Source {
6850 path: dir.join("link/a.mp4"),
6851 audio_stream: 1, ..Default::default()
6852 }]
6853 );
6854 std::fs::remove_dir_all(&dir).expect("cleanup");
6855 }
6856
6857 #[test]
6858 fn escapes_survive_the_bytes_json_would_not() {
6859 let dir = PathBuf::from("/proj");
6860 // A newline and a percent in a filename, plus a non-UTF-8 byte.
6861 let nasty = Source {
6862 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
6863 audio_stream: 0, ..Default::default()
6864 };
6865 let bytes = flat(
6866 &dir,
6867 std::slice::from_ref(&nasty),
6868 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
6869 0,
6870 );
6871 assert_eq!(
6872 bytes.iter().filter(|&&b| b == b'\n').count(),
6873 6,
6874 "the escaped newline must not become a line break: magic, playhead, \
6875 resolution, source, the clip, and the empty audio lane's own line"
6876 );
6877 let back = parse(&bytes, &dir).expect("parse");
6878 // The spaces in it are the reason the stream field leads rather than
6879 // trails: everything after the first one is path.
6880 assert_eq!(back.sources, vec![nasty]);
6881 }
6882
6883 /// A `flags` line names its lane the way a gain does and carries only the
6884 /// switches its kind of lane can have. A lane with none has no line, so a
6885 /// v23 file -- which has no such line -- parses with every switch clear, and
6886 /// one that carries the line before v24 is an unknown keyword.
6887 #[test]
6888 fn lane_switches_parse_by_kind_and_a_v23_file_has_none() {
6889 let dir = PathBuf::from("/proj");
6890 let doc = parse(
6891 b"edith 24\nvideo 1\naudio 1\nsub 1\nflags video 1 hidden locked\nflags audio 1 muted\nflags sub 1 hidden\n",
6892 &dir,
6893 )
6894 .expect("a v24 file with switches parses");
6895 assert_eq!(
6896 doc.flags,
6897 vec![
6898 LaneFlags {
6899 hidden: true,
6900 muted: false,
6901 locked: true,
6902 pan: 0.0,
6903 },
6904 LaneFlags {
6905 hidden: false,
6906 muted: true,
6907 locked: false,
6908 pan: 0.0,
6909 },
6910 LaneFlags {
6911 hidden: true,
6912 muted: false,
6913 locked: false,
6914 pan: 0.0,
6915 },
6916 ]
6917 );
6918
6919 let plain = parse(b"edith 24\nvideo 1\naudio 1\n", &dir).expect("no switches");
6920 assert_eq!(plain.flags, vec![LaneFlags::default(); 2]);
6921 let old = parse(b"edith 23\nvideo 1\naudio 1\n", &dir).expect("a v23 file loads");
6922 assert_eq!(
6923 old.flags,
6924 vec![LaneFlags::default(); 2],
6925 "every switch clear"
6926 );
6927
6928 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
6929 assert!(
6930 refuse(b"edith 24\nvideo 1\nflags video 1 hidden hidden\n").contains("twice"),
6931 "a switch named twice"
6932 );
6933 assert!(
6934 refuse(b"edith 24\naudio 1\nflags audio 1 hidden\n").contains("cannot be set"),
6935 "a hidden audio lane"
6936 );
6937 assert!(
6938 refuse(b"edith 24\nvideo 1\nflags video 1 muted\n").contains("cannot be set"),
6939 "a muted video lane"
6940 );
6941 assert!(
6942 refuse(b"edith 24\nvideo 1\nflags video 2 hidden\n").contains("not there"),
6943 "a lane that is not there"
6944 );
6945 assert!(
6946 refuse(b"edith 24\nvideo 1\nflags video 1\n").contains("no switch"),
6947 "a line with no switch"
6948 );
6949 assert!(
6950 refuse(b"edith 23\nvideo 1\nflags video 1 hidden\n").contains("unknown keyword"),
6951 "a flags line before v24 is not a dialect"
6952 );
6953 }
6954
6955 #[test]
6956 fn a_duck_line_round_trips_and_is_bounded_by_name() {
6957 let dir = PathBuf::from("/proj");
6958 let head = "edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6959 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6960 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6961 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
6962 let ok = parse(
6963 format!("{head}duck audio 2 1 -12.0 -40.0 80.0 400.0\n").as_bytes(),
6964 &dir,
6965 )
6966 .expect("a duck of A2 under A1 parses");
6967 assert_eq!(
6968 ok.ducks,
6969 vec![
6970 vec![],
6971 vec![],
6972 vec![crate::duck::Duck {
6973 under: 0,
6974 depth_db: -12.0,
6975 threshold_db: -40.0,
6976 attack_ms: 80.0,
6977 release_ms: 400.0,
6978 }]
6979 ],
6980 "one list per lane, the key named 0-based in the struct"
6981 );
6982 let refuse = |line: &str| {
6983 parse(format!("{head}{line}\n").as_bytes(), &dir)
6984 .unwrap_err()
6985 .to_string()
6986 };
6987 assert!(refuse("duck audio 2 2 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
6988 assert!(refuse("duck audio 2 3 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
6989 assert!(refuse("duck audio 2 0 -12.0 -40.0 80.0 400.0").contains("lane 0"));
6990 assert!(refuse("duck audio 2 1 -41.0 -40.0 80.0 400.0").contains("out of its range"));
6991 assert!(refuse("duck audio 2 1 -12.0 -40.0 0.0 400.0").contains("out of its range"));
6992 assert!(refuse("duck video 1 1 -12.0 -40.0 80.0 400.0").contains("not an audio lane"));
6993 // A dialect before v25 has no ducks, so the same line is an unknown one.
6994 let v24 = format!(
6995 "{}duck audio 2 1 -12.0 -40.0 80.0 400.0\n",
6996 head.replacen("edith 25", "edith 24", 1)
6997 );
6998 assert!(
6999 parse(v24.as_bytes(), &dir)
7000 .unwrap_err()
7001 .to_string()
7002 .contains("unknown keyword"),
7003 "a v24 file cannot carry a duck"
7004 );
7005 // ...and a v24 file without one still loads, with every lane unducked.
7006 let old = parse(head.replacen("edith 25", "edith 24", 1).as_bytes(), &dir)
7007 .expect("v24 still loads");
7008 assert!(old.ducks.iter().all(Vec::is_empty));
7009 }
7010
7011 /// The v42 `effect` lines: a clip's whole stack round-trips in order, switch and
7012 /// every value included, through the same `save_flagged` every save takes; a project
7013 /// with no effect keeps its older header; a v41 file refuses the line; a bad line is
7014 /// refused by name.
7015 #[test]
7016 fn effect_lines_round_trip_in_v42_and_older_files_refuse_them() {
7017 use crate::effects::{Effect, EffectKind};
7018 let dir = std::env::temp_dir().join(format!("edith-effects-{}", std::process::id()));
7019 std::fs::create_dir_all(&dir).unwrap();
7020 let path = dir.join("fx.edith");
7021 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7022 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
7023 save_flagged(
7024 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7025 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7026 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7027 )
7028 .expect("saves");
7029 std::fs::read_to_string(&path).unwrap()
7030 };
7031 let plain = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7032 let before = save(&plain);
7033 assert!(!before.starts_with("edith 42") && !before.contains("effect"), "{before}");
7034 let mut lanes = plain.clone();
7035 let mut blur = Effect::new(EffectKind::Blur);
7036 blur.set("radius", 12.25).unwrap();
7037 let mut key = Effect::new(EffectKind::ChromaKey);
7038 key.on = false;
7039 key.set("tolerance", 0.123_456_7).unwrap();
7040 let stack = vec![Effect::new(EffectKind::Vignette), blur, key, Effect::new(EffectKind::EllipseMask)];
7041 lanes[0].1[0].effects = stack.clone();
7042 let text = save(&lanes);
7043 assert!(text.starts_with("edith 42\n"), "an effect makes it v42: {text}");
7044 assert!(text.contains("\neffect video 1 0 blur 1 12.25\n"), "{text}");
7045 assert!(text.contains("\neffect video 1 0 chroma_key 0 0 255 0 0.1234567 0.1 0.5\n"), "{text}");
7046 let back = load(&path).expect("v42 loads");
7047 assert_eq!(back.lanes[0].1[0].effects, stack, "order, switches and values survive");
7048 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7049 lanes[0].1[0].effects.clear();
7050 assert_eq!(save(&lanes), before, "no effect: the bytes it was");
7051 std::fs::remove_dir_all(&dir).ok();
7052
7053 let dir = PathBuf::from("/proj");
7054 let video_head = "edith 42\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7055 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7056 let doc = parse(format!("{video_head}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).expect("parses");
7057 assert_eq!(doc.lanes[0].1[0].effects[0].get("amount"), Some(0.5));
7058 let refuse = |line: &str| parse(format!("{video_head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7059 assert!(refuse("effect video 1 0 sparkle 1 0.5").contains("not one"));
7060 assert!(refuse("effect video 1 0 sharpen 2 0.5").contains("not 0 or 1"));
7061 assert!(refuse("effect video 1 0 sharpen 1 9").contains("out of its range"));
7062 assert!(refuse("effect video 1 0 vignette 1 0.5").contains("wants 2 values"));
7063 assert!(refuse("effect video 1 4 sharpen 1 0.5").contains("does not have"));
7064 assert!(refuse("effect audio 1 0 sharpen 1 0.5").contains("wants a video clip"));
7065 assert!(refuse("effect video 2 0 sharpen 1 0.5").contains("not there"));
7066 let v41 = video_head.replacen("edith 42", "edith 41", 1);
7067 let err = parse(format!("{v41}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).unwrap_err().to_string();
7068 assert!(err.contains("unknown keyword \"effect\""), "{err}");
7069 }
7070
7071 /// The v50 pan lines: a clip pan and a lane pan round-trip, a project with neither keeps its
7072 /// header and its bytes, and an out-of-range or unknown-lane pan is refused by name.
7073 #[test]
7074 fn pan_lines_round_trip_in_v50() {
7075 let dir = std::env::temp_dir().join(format!("edith-pan-{}", std::process::id()));
7076 std::fs::create_dir_all(&dir).unwrap();
7077 let path = dir.join("pan.edith");
7078 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7079 let save = |lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]| {
7080 save_flagged(
7081 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7082 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7083 Limiter::default(), None, 0, flags, &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7084 )
7085 .expect("saves");
7086 std::fs::read_to_string(&path).unwrap()
7087 };
7088 let plain = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0)), clip(30, 0, 30, 0, Some(0))]);
7089 let before = save(&plain, &[]);
7090 assert!(!before.contains("pan"), "{before}");
7091 let mut lanes = plain.clone();
7092 lanes[1].1[1].pan = -25;
7093 let flags = [LaneFlags::default(), LaneFlags { pan: 0.5, locked: true, ..LaneFlags::default() }];
7094 let text = save(&lanes, &flags);
7095 assert!(text.starts_with("edith 50\n"), "{text}");
7096 assert!(text.contains("\nlanepan audio 1 0.5\n") && text.contains("\nclippan audio 1 1 -0.25\n"), "{text}");
7097 let back = load(&path).expect("v50 loads");
7098 assert_eq!(back.lanes[1].1[1].pan, -25);
7099 assert_eq!(back.lanes[1].1[0].pan, 0);
7100 assert_eq!(back.flags[1].pan, 0.5);
7101 assert!(back.flags[1].locked, "the switches stay");
7102 assert_eq!(save(&back.lanes, &back.flags), text, "saved again: the same bytes");
7103 let dirp = PathBuf::from("/proj");
7104 let head = "edith 50\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7105 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7106 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7107 assert!(refuse("clippan audio 1 0 2").contains("out of its range"));
7108 assert!(refuse("clippan audio 1 4 0.5").contains("does not have"));
7109 assert!(refuse("lanepan audio 3 0.5").contains("not there"));
7110 assert!(refuse("lanepan video 1 0.5").contains("not an audio lane"));
7111 let old = head.replacen("edith 50", "edith 49", 1);
7112 let err = parse(format!("{old}lanepan audio 1 0.5\n").as_bytes(), &dirp).unwrap_err().to_string();
7113 assert!(err.contains("unknown keyword"), "{err}");
7114 std::fs::remove_dir_all(&dir).ok();
7115 }
7116
7117
7118 /// A custom bezier ease is a v56 word: a v56 file loads it and a v55 file naming one is refused.
7119 #[test]
7120 fn bezier_ease_is_a_v56_word() {
7121 let dirp = PathBuf::from("/proj");
7122 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7123 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7124 let line = "tkeys video 1 0 0:lin:0,0,1,0,0,0,0,0,1 20:b420_0_580_1000:0,0,2,0,0,0,0,0,0.5\n";
7125 let doc = parse(format!("edith 56\n{head}{line}").as_bytes(), &dirp).expect("a v56 file loads");
7126 let bezier = crate::transform::Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
7127 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Bezier(bezier));
7128 let err = parse(format!("edith 55\n{head}{line}").as_bytes(), &dirp).unwrap_err().to_string();
7129 assert!(err.contains("tkeys ease"), "{err}");
7130 }
7131
7132 /// The v55 pitch lines: a clip's semitones round-trip and a project with none is the bytes a
7133 /// v51 one was; an out-of-range, unknown-lane or unknown-clip pitch is refused by name, and a
7134 /// pitch line under an older header is refused as unknown.
7135 #[test]
7136 fn pitch_lines_round_trip_in_v55() {
7137 let dir = std::env::temp_dir().join(format!("edith-pitch-{}", std::process::id()));
7138 std::fs::create_dir_all(&dir).unwrap();
7139 let path = dir.join("pitch.edith");
7140 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7141 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
7142 save_flagged(
7143 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7144 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7145 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7146 )
7147 .expect("saves");
7148 std::fs::read_to_string(&path).unwrap()
7149 };
7150 let plain = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0)), clip(30, 0, 30, 0, Some(0))]);
7151 let before = save(&plain);
7152 assert!(!before.contains("pitch"), "{before}");
7153 assert!(!before.starts_with("edith 55"), "{before}");
7154 let mut lanes = plain.clone();
7155 lanes[1].1[1].pitch = -7;
7156 let text = save(&lanes);
7157 assert!(text.starts_with("edith 55\n"), "{text}");
7158 assert!(text.contains("\npitch audio 1 1 -7\n"), "{text}");
7159 let back = load(&path).expect("v55 loads");
7160 assert_eq!(back.lanes[1].1[1].pitch, -7);
7161 assert_eq!(back.lanes[1].1[0].pitch, 0);
7162 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7163 let dirp = PathBuf::from("/proj");
7164 let head = "edith 55\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7165 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7166 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7167 assert!(refuse("pitch audio 1 0 13").contains("out of its range"));
7168 assert!(refuse("pitch audio 1 0 1.5").contains("out of its range"));
7169 assert!(refuse("pitch audio 1 4 3").contains("does not have"));
7170 assert!(refuse("pitch audio 3 0 3").contains("not there"));
7171 assert!(refuse("pitch video 1 0 3").contains("not an audio lane"));
7172 let old = head.replacen("edith 55", "edith 51", 1);
7173 let err = parse(format!("{old}pitch audio 1 0 3\n").as_bytes(), &dirp).unwrap_err().to_string();
7174 assert!(err.contains("unknown keyword"), "{err}");
7175 std::fs::remove_dir_all(&dir).ok();
7176 }
7177
7178 /// The v51 library lines: bins, filed sources and starred ones round-trip; a project with
7179 /// none keeps its v50 bytes; the lines are refused in v50 and bad ones by name.
7180 #[test]
7181 fn library_lines_round_trip_with_effect_keys_in_v56() {
7182 use crate::project::Bin;
7183 let dir = std::env::temp_dir().join(format!("edith-bins-{}", std::process::id()));
7184 std::fs::create_dir_all(&dir).unwrap();
7185 let path = dir.join("bins.edith");
7186 let mut src = vec![
7187 Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() },
7188 Source { path: dir.join("b.mp4"), audio_stream: 0, ..Default::default() },
7189 ];
7190 let mut lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7191 let mut mask = crate::effects::Effect::new(crate::effects::EffectKind::EllipseMask);
7192 mask.keys = vec![crate::effects::EffectKey {
7193 at: 0, values: [0.5, 0.5, 0.4, 0.4, 0.02, 0.0], ease: KeyEase::Linear,
7194 }];
7195 lanes[0].1[0].effects = vec![mask];
7196 let save = |src: &[Source], bins: &[Bin]| {
7197 let main = encode_flagged(
7198 &dir, src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7199 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7200 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7201 );
7202 let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS);
7203 std::fs::write(&path, &bytes).unwrap();
7204 String::from_utf8(bytes).unwrap()
7205 };
7206 let plain = save(&src, &[]);
7207 assert!(plain.starts_with("edith 45\n") || !plain.starts_with("edith 51"), "{plain}");
7208 assert!(!plain.contains("bin") && !plain.contains("srcfav"), "{plain}");
7209 let bins = vec![
7210 Bin { id: 1, parent: 0, name: "Interviews \"A\"".into() },
7211 Bin { id: 3, parent: 1, name: "B roll".into() },
7212 ];
7213 src[0].bin = 3;
7214 src[1].fav = true;
7215 src[1].bin = 1;
7216 let text = save(&src, &bins);
7217 // An effect key is v56, and the library and the notes lines keep it there.
7218 assert!(text.starts_with("edith 56\n"), "{text}");
7219 assert!(text.contains("\nsrcbin 0 3\n") && text.contains("\nsrcfav 1\n"), "{text}");
7220 assert!(text.contains("\nekeys video 1 0 0 0:lin:0.5,0.5,0.4,0.4,0.02,0\n") && text.contains("\nnotes Two cuts\n"), "{text}");
7221 let back = load(&path).expect("v56 loads");
7222 assert_eq!(back.notes, "Two cuts");
7223 assert_eq!(back.bins, bins);
7224 assert_eq!((back.sources[0].bin, back.sources[0].fav), (3, false));
7225 assert_eq!((back.sources[1].bin, back.sources[1].fav), (1, true));
7226 assert_eq!(save(&back.sources, &back.bins), text, "saved again: the same bytes");
7227 let dirp = PathBuf::from("/proj");
7228 let head = "edith 51\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7229 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7230 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7231 assert!(refuse("bin 1 0").contains("wants an id"));
7232 assert!(refuse("bin 0 0 x").contains("not a new id"));
7233 assert!(refuse("bin 1 0 x\nbin 1 0 y").contains("not a new id"));
7234 assert!(refuse("bin 2 1 x").contains("not a top-level bin"));
7235 assert!(refuse("bin 1 0 x\nbin 2 0 X").contains("two bins named"));
7236 assert!(refuse("bin 1 0 x\nbin 2 1 y\nbin 3 2 z").contains("not a top-level bin"));
7237 assert!(refuse("srcbin 0 9").contains("not defined"));
7238 assert!(refuse("bin 1 0 x\nsrcbin 4 1").contains("does not have"));
7239 assert!(refuse("srcfav 7").contains("does not have"));
7240 let old = head.replacen("edith 51", "edith 50", 1);
7241 for line in ["bin 1 0 x", "srcfav 0"] {
7242 let err = parse(format!("{old}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7243 assert!(err.contains("unknown keyword"), "{err}");
7244 }
7245 std::fs::remove_dir_all(&dir).ok();
7246 }
7247
7248 /// The v41 `voice` lines: every processor of an audio lane (the noise profile included)
7249 /// round-trips bit for bit; a lane with no voice setting writes none, so a project nobody
7250 /// has cleaned keeps its older header and its exact bytes; a v40 file loads with every
7251 /// processor off and refuses the lines; a number out of range is refused by name.
7252 /// The v43 look lines: wheels, curves and a LUT path (relative inside the
7253 /// project folder) round trip bit-exactly; a grade without a look writes none
7254 /// and stays under its old header; a missing LUT still loads; bad lines are
7255 /// refused by name.
7256 #[test]
7257 fn look_lines_round_trip_in_v43() {
7258 use crate::color::{Curve, Look, Wheels};
7259 let dir = std::env::temp_dir().join(format!("edith-look-{}", std::process::id()));
7260 std::fs::create_dir_all(dir.join("luts")).unwrap();
7261 let cube = dir.join("luts/warm look.cube");
7262 std::fs::write(&cube, "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").unwrap();
7263 let path = dir.join("look.edith");
7264 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7265 let lanes = two(
7266 vec![Clip { color: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { color: Some(1), ..clip(30, 0, 30, 0, Some(0)) }],
7267 vec![clip(0, 0, 60, 0, Some(0))],
7268 );
7269 let look = Look {
7270 wheels: Wheels { lift: [0.1, -0.000_000_1, 0.0, 0.25], gamma: [0.0, 0.0, 0.3, 0.0], gain: [-0.5, 0.0, 0.0, 1.0] },
7271 curves: [
7272 Curve::new(&[[0.25, 0.2], [0.75, 0.8]]).unwrap(),
7273 Curve::default(),
7274 Curve::new(&[[0.0, 0.1], [0.5, 0.5], [1.0, 0.95]]).unwrap(),
7275 Curve::default(),
7276 ],
7277 lut: Some(crate::cube::LutRef::open(&cube)),
7278 lut_mix: 0.7,
7279 };
7280 let color = vec![ColorParams { contrast: 1.1, look, ..Default::default() }, ColorParams { tint: 0.2, ..Default::default() }];
7281 let save = |color: &[ColorParams]| {
7282 save_flagged(
7283 &path, &src, &lanes, &[], &[], &[], &[], color, &[], (1280, 720), Some(30.0),
7284 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7285 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7286 )
7287 .expect("saves");
7288 std::fs::read_to_string(&path).unwrap()
7289 };
7290 let text = save(&color);
7291 assert!(text.starts_with("edith 43\n"), "a look makes it v43: {text}");
7292 assert!(text.contains("\nwheels 0 0.1:-1e-7:0.0:0.25 0.0:0.0:0.3:0.0 -0.5:0.0:0.0:1.0\n"), "{text}");
7293 assert!(text.contains("\ncurve 0 master 0.25:0.2,0.75:0.8\n") && text.contains("\ncurve 0 green 0.0:0.1,0.5:0.5,1.0:0.95\n"), "{text}");
7294 assert!(text.contains("\nlut 0 0.7 luts/warm look.cube\n"), "relative inside the folder: {text}");
7295 assert!(!text.contains("curve 1") && !text.contains("lut 1"), "no look, no lines");
7296 let back = load(&path).expect("v43 loads");
7297 assert_eq!(back.color, color, "every number survives");
7298 assert_eq!(save(&back.color), text, "a re-save is the same file");
7299 // No look: the old header and no look line.
7300 let plain = save(&[color[1], color[1]]);
7301 assert!(plain.starts_with("edith 3") && !plain.contains("wheels") && !plain.contains("\nlut "), "{plain}");
7302 // A missing LUT loads, and says why it cannot be used.
7303 let gone = text.replace("luts/warm look.cube", "luts/gone.cube");
7304 std::fs::write(&path, &gone).unwrap();
7305 let doc = load(&path).expect("a missing LUT still loads");
7306 let lut = doc.color[0].look.lut.expect("named");
7307 assert!(lut.problem().expect("missing").contains("cannot read"));
7308 std::fs::remove_dir_all(&dir).ok();
7309
7310 let head = "edith 43\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\n\
7311 video 1 0 0 30 0 - - 0 fit 1000 0 0 0 - 0 0\n";
7312 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7313 assert!(refuse("wheels 1 0:0:0:0 0:0:0:0 0:0:0:0").contains("names color 1"));
7314 assert!(refuse("wheels 0 2:0:0:0 0:0:0:0 0:0:0:0").contains("outside -1..1"));
7315 assert!(refuse("wheels 0 0:0:0 0:0:0:0 0:0:0:0").contains("4 values"));
7316 assert!(refuse("curve 0 cyan 0.1:0.2").contains("not master"));
7317 assert!(refuse("curve 0 red 0.5:0.2,0.4:0.3").contains("strictly increase"));
7318 assert!(refuse("curve 0 red 0.5").contains("<x>:<y>"));
7319 assert!(refuse("lut 0 1.5 a.cube").contains("0..=1"));
7320 assert!(refuse("lut 0 1.0").contains("<mix> <path>"));
7321 for old in ["edith 42", "edith 41"] {
7322 let older = head.replacen("edith 43", old, 1);
7323 assert!(parse(format!("{older}lut 0 1.0 a.cube\n").as_bytes(), &dir).is_err(), "a {old} file has no lut line");
7324 }
7325 }
7326
7327 #[test]
7328 fn voice_lines_round_trip_in_v41_and_older_files_load_with_them_off() {
7329 use crate::voice::{PROFILE_BANDS, Strength};
7330 let dir = std::env::temp_dir().join(format!("edith-voice-{}", std::process::id()));
7331 std::fs::create_dir_all(&dir).unwrap();
7332 let path = dir.join("voice.edith");
7333 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7334 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7335 let profile: Vec<f32> = (0..PROFILE_BANDS).map(|b| -80.0 + b as f32 * 0.1).collect();
7336 let fx = VoiceFx::clean_voice(Strength::Strong, profile, Some(-52.0));
7337 let save = |voices: &[VoiceFx]| {
7338 save_flagged(
7339 &path, &src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7340 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7341 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), voices, &[],
7342 )
7343 .expect("saves");
7344 std::fs::read_to_string(&path).unwrap()
7345 };
7346 let text = save(&[VoiceFx::default(), fx.clone()]);
7347 assert!(text.starts_with("edith 41\n"), "a voice makes it v41: {text}");
7348 for kind in ["gate", "nr", "comp", "deess"] {
7349 assert!(text.contains(&format!("\nvoice audio 1 {kind} 1 ")), "{kind}: {text}");
7350 }
7351 let back = load(&path).expect("v41 loads");
7352 assert_eq!(back.voices, vec![VoiceFx::default(), fx.clone()], "every number and the profile survive");
7353 // Saved again from what was loaded: the same bytes.
7354 let again = save(&back.voices);
7355 assert_eq!(again, text);
7356 // Only what differs from the default is written, and a lane with nothing writes no line.
7357 let comp_only = VoiceFx { comp: Compressor { on: true, ..Compressor::DEFAULT }, ..Default::default() };
7358 let text = save(&[VoiceFx::default(), comp_only.clone()]);
7359 assert_eq!(text.matches("\nvoice ").count(), 1, "{text}");
7360 assert_eq!(load(&path).unwrap().voices[1], comp_only);
7361 // Nothing set: not v41 and no voice line -- the bytes a v40 save wrote.
7362 let plain = save(&[VoiceFx::default(), VoiceFx::default()]);
7363 assert!(!plain.contains("voice") && plain.starts_with("edith 3") && !plain.starts_with("edith 41"), "{plain}");
7364 assert_eq!(save(&[]), plain, "no list is the same as a list of defaults");
7365 std::fs::remove_file(&path).ok();
7366
7367 let head = "edith 41\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7368 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7369 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7370 assert!(refuse("voice audio 1 gate 1 -45.0 2.0 150.0 60.0 5.0").contains("out of its range"));
7371 assert!(refuse("voice audio 1 comp 1 -24.0 0.5 10.0 100.0 6.0 0.0 1").contains("out of its range"));
7372 assert!(refuse("voice audio 1 nr 1 0.6 -18.0 -").contains("no noise profile"));
7373 assert!(refuse("voice audio 1 nr 0 0.6 -18.0 1.0,2.0").contains("out of its range"), "a profile is 256 bands");
7374 assert!(refuse("voice audio 1 gate 2 -45.0 2.0 150.0 60.0 -18.0").contains("not 0 or 1"));
7375 assert!(refuse("voice audio 1 gate 1 -45.0 2.0").contains("wants 6 fields"));
7376 assert!(refuse("voice audio 1 reverb 1").contains("not a processor"));
7377 assert!(refuse("voice audio 2 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not there"));
7378 assert!(refuse("voice video 1 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not an audio lane"));
7379 // A v40 file carries none, and the same line in one is an unknown keyword.
7380 let v40 = head.replacen("edith 41", "edith 40", 1);
7381 let err = parse(format!("{v40}voice audio 1 gate 1 -45.0 2.0 150.0 60.0 -18.0\n").as_bytes(), &dir)
7382 .unwrap_err()
7383 .to_string();
7384 assert!(err.contains("unknown keyword"), "{err}");
7385 let old = parse(v40.as_bytes(), &dir).expect("v40 still loads");
7386 assert!(old.voices.iter().all(|v| !v.is_active()) && old.voices.len() == 2);
7387 std::fs::remove_dir_all(&dir).ok();
7388 }
7389
7390 #[test]
7391 fn a_lane_ducked_under_two_keys_round_trips_in_v30() {
7392 let dir = PathBuf::from("/proj");
7393 let head = "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7394 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7395 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7396 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7397 audio 3 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7398 let two = format!(
7399 "{head}duck audio 3 1 -12.0 -40.0 80.0 400.0\nduck audio 3 2 -6.0 -30.0 50.0 300.0\n"
7400 );
7401 let ok = parse(two.as_bytes(), &dir).expect("two keys for A3 parse");
7402 assert_eq!(ok.ducks[3].len(), 2, "both ducks kept, in file order");
7403 assert_eq!(ok.ducks[3][0].under, 0);
7404 assert_eq!(ok.ducks[3][1].under, 1);
7405 let refuse = |text: String| parse(text.as_bytes(), &dir).unwrap_err().to_string();
7406 assert!(
7407 refuse(format!("{head}duck audio 3 1 -12.0 -40.0 80.0 400.0\nduck audio 3 1 -6.0 -30.0 50.0 300.0\n"))
7408 .contains("same key twice")
7409 );
7410 // A v29 file cannot hold two for one lane: refused by name, not dropped.
7411 let v29 = format!(
7412 "{}duck audio 3 1 -12.0 -40.0 80.0 400.0\nduck audio 3 2 -6.0 -30.0 50.0 300.0\n",
7413 head.replacen("edith 30", "edith 29", 1)
7414 );
7415 assert!(refuse(v29).contains("names a lane twice"));
7416 }
7417
7418 #[test]
7419 fn a_wrong_first_line_is_refused_by_name() {
7420 let dir = PathBuf::from("/proj");
7421 let err = parse(b"edith 999\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
7422 .unwrap_err()
7423 .to_string();
7424 assert_eq!(err, "line 1: unsupported version 999");
7425 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
7426 assert_eq!(
7427 parse(junk, &dir).unwrap_err().to_string(),
7428 "line 1: not an edith file"
7429 );
7430 }
7431 }
7432
7433 /// The v34 `chapter` line: a project's chapters are saved in frame order and
7434 /// come back as they were, and a project with none is still a v33-or-older
7435 /// file. A v33 file loads with no chapters, and a chapter line in one is refused.
7436 #[test]
7437 fn chapters_round_trip_and_a_v33_file_loads_without_them() {
7438 use crate::project::Chapter;
7439 let dir = std::env::temp_dir().join(format!("edith-chapters-{}", std::process::id()));
7440 std::fs::create_dir_all(&dir).unwrap();
7441 let path = dir.join("chapters.edith");
7442 let chapters = vec![
7443 Chapter { frame: 0, title: "Intro".into() },
7444 Chapter { frame: 1500, title: "Setup: 100% \\ done".into() },
7445 ];
7446 save_flagged(
7447 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7448 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7449 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &chapters, &[], &CaptionStyle::default(), &[], &[],
7450 )
7451 .expect("a project with chapters saves");
7452 let text = std::fs::read_to_string(&path).unwrap();
7453 assert!(text.starts_with("edith 34\n"), "chapters make it v34: {text}");
7454 assert!(text.contains("\nchapter 0 Intro\nchapter 1500 "), "frame order, one line each: {text}");
7455 let back = load(&path).expect("v34 loads");
7456 assert_eq!(back.chapters, chapters);
7457 std::fs::remove_file(&path).ok();
7458
7459 // A project with no chapters keeps the header it always had.
7460 let bare = b"edith 33\nplayhead 0\nsource 0 a.mp4\n";
7461 let old = parse(bare, &dir).expect("a v33 file loads");
7462 assert!(old.chapters.is_empty());
7463 let mixed = parse(b"edith 33\nsource 0 a.mp4\nchapter 0 Intro\n", &dir)
7464 .unwrap_err()
7465 .to_string();
7466 assert_eq!(mixed, "line 3: unknown keyword \"chapter\"");
7467 // Out of order, a name with none, and a frame that is not a frame are refused.
7468 for line in ["chapter 10 B\nchapter 5 A\n", "chapter 5 \n", "chapter x Intro\n"] {
7469 let file = format!("edith 34\nsource 0 a.mp4\n{line}");
7470 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7471 }
7472 std::fs::remove_dir(&dir).ok();
7473 }
7474
7475 /// The v36 `marker` and `marknote` lines: markers (point and range, with and without a
7476 /// note, two on one frame) round-trip and make the file v36; a v35 file loads with none
7477 /// and refuses the lines; a project with no marker keeps its older header.
7478 #[test]
7479 fn markers_round_trip_and_a_v35_file_loads_without_them() {
7480 use crate::project::{Marker, MarkerColor};
7481 let dir = std::env::temp_dir().join(format!("edith-markers-{}", std::process::id()));
7482 std::fs::create_dir_all(&dir).unwrap();
7483 let path = dir.join("markers.edith");
7484 let mk = |frame, length, name: &str, note: &str, color| Marker { frame, length, name: name.into(), note: note.into(), color };
7485 let markers = vec![
7486 mk(0, 0, "Intro", "", MarkerColor::Blue),
7487 mk(100, 50, "Fix: 100% \\ the cut", "line one\nline two", MarkerColor::Red),
7488 mk(100, 0, "Same frame", "", MarkerColor::Purple),
7489 mk(900, 0, "Late", "has a note", MarkerColor::Green),
7490 ];
7491 let save = |markers: &[Marker]| {
7492 save_flagged(
7493 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7494 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7495 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, &CaptionStyle::default(), &[], &[],
7496 )
7497 .expect("saves");
7498 };
7499 save(&markers);
7500 let text = std::fs::read_to_string(&path).unwrap();
7501 assert!(text.starts_with("edith 36\n"), "markers make it v36: {text}");
7502 assert!(text.contains("\nmarker 0 0 blue Intro\nmarker 100 50 red "), "{text}");
7503 assert!(text.contains("\nmarknote 1 line one\\nline two\nmarknote 3 has a note\n"), "{text}");
7504 assert_eq!(load(&path).expect("v36 loads").markers, markers);
7505 save(&[]);
7506 let text = std::fs::read_to_string(&path).unwrap();
7507 assert!(!text.starts_with("edith 36") && !text.contains("marker"), "no markers, an older file: {text}");
7508 std::fs::remove_file(&path).ok();
7509
7510 let old = parse(b"edith 35\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v35 file loads");
7511 assert!(old.markers.is_empty());
7512 let mixed = parse(b"edith 35\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).unwrap_err().to_string();
7513 assert_eq!(mixed, "line 3: unknown keyword \"marker\"");
7514 for line in [
7515 "marker 10 0 red B\nmarker 5 0 red A\n",
7516 "marker 5 0 red \n",
7517 "marker 5 0 pink A\n",
7518 "marker x 0 red A\n",
7519 "marknote 0 hi\n",
7520 ] {
7521 let file = format!("edith 36\nsource 0 a.mp4\n{line}");
7522 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7523 }
7524 std::fs::remove_dir(&dir).ok();
7525 }
7526
7527 /// The v40 `capstyle` line: an animated caption style round-trips and makes the file v40;
7528 /// the default style writes no line and keeps the older header; a v36 file loads as the
7529 /// default and a v39 file refuses the line; a bad line is refused by name.
7530 /// The v40 `cuewords` lines: word times round-trip through the text, a cue without any
7531 /// writes no line, and a v39 file refuses the line.
7532 #[test]
7533 fn cue_word_times_round_trip_through_the_lines() {
7534 let dir = PathBuf::from("/proj");
7535 let cue = |text: &str, words: Vec<(i64, i64, String)>| crate::subtitle::Cue {
7536 start_us: 0,
7537 end_us: 3_000_000,
7538 text: text.into(),
7539 image: None,
7540 words,
7541 karaoke: Vec::new(),
7542 };
7543 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7544 track.cues = vec![
7545 cue("plain", vec![]),
7546 cue("two words", vec![(0, 1_000_000, "two".into()), (1_000_000, 2_500_000, "words".into())]),
7547 ];
7548 let lines = String::from_utf8(cue_word_lines(&[track])).unwrap();
7549 assert_eq!(lines, "cuewords 0 1 0 1000000 two 1000000 2500000 words\n");
7550 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7551 let doc = parse(file.as_bytes(), &dir).expect("v40 parses");
7552 assert_eq!(
7553 doc.cue_words,
7554 vec![(0, 1, vec![(0, 1_000_000, "two".to_string()), (1_000_000, 2_500_000, "words".to_string())])]
7555 );
7556 let old = file.replacen("edith 40", "edith 39", 1);
7557 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("unknown keyword"));
7558 for bad in ["cuewords 0 1 0 5\n", "cuewords 9 1 0 5 a\n", "cuewords 0 1 x 5 a\n"] {
7559 let f = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{bad}");
7560 assert!(parse(f.as_bytes(), &dir).is_err(), "{bad:?} is refused");
7561 }
7562 }
7563
7564 /// The whole project loop for word times: a track with uneven word times is written as
7565 /// `cuewords` lines, read back and attached to a freshly loaded project, and the cue then
7566 /// answers with the same uneven times -- until its text is retyped, which drops them.
7567 #[test]
7568 fn a_projects_cue_word_times_survive_the_file_and_die_with_a_text_edit() {
7569 let words = vec![(0, 200_000, "so".to_string()), (200_000, 2_600_000, "extraordinary".to_string())];
7570 let make = |words: Vec<(i64, i64, String)>| {
7571 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7572 track.cues = vec![crate::subtitle::Cue {
7573 start_us: 0,
7574 end_us: 3_000_000,
7575 text: "So extraordinary".into(),
7576 image: None,
7577 words,
7578 karaoke: Vec::new(),
7579 }];
7580 track
7581 };
7582 let mut project = crate::Project::single("/proj/a.mp4", 150);
7583 assert!(project.add_subtitles(&make(words.clone())));
7584 let lines = String::from_utf8(cue_word_lines(project.subtitles())).unwrap();
7585 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7586 let doc = parse(file.as_bytes(), &PathBuf::from("/proj")).expect("the file parses");
7587
7588 let mut loaded = crate::Project::single("/proj/a.mp4", 150);
7589 assert!(loaded.add_subtitles(&make(Vec::new())));
7590 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "the SRT alone has no word times");
7591 let mut loaded = loaded.with_cue_words(&doc.cue_words);
7592 assert_eq!(loaded.subtitles()[0].cues[0].real_words(), Some(&words[..]), "the uneven times are back");
7593 assert!(loaded.set_cue_text(0, 0, "Something else"));
7594 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "retyped words have no times");
7595 }
7596
7597 #[test]
7598 fn the_caption_style_round_trips_and_a_v36_file_loads_as_static() {
7599 use crate::captionanim::CaptionAnim;
7600 let dir = std::env::temp_dir().join(format!("edith-capstyle-{}", std::process::id()));
7601 std::fs::create_dir_all(&dir).unwrap();
7602 let path = dir.join("capstyle.edith");
7603 let save = |cs: &CaptionStyle| {
7604 save_flagged(
7605 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7606 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7607 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], cs, &[], &[],
7608 )
7609 .expect("saves");
7610 };
7611 let style = CaptionStyle {
7612 anim: CaptionAnim::Karaoke,
7613 highlight: [0x12, 0xab, 0xff],
7614 hl_box: true,
7615 uppercase: true,
7616 words_per_line: 3,
7617 };
7618 save(&style);
7619 let text = std::fs::read_to_string(&path).unwrap();
7620 assert!(text.starts_with("edith 40\n"), "{text}");
7621 assert!(text.contains("\ncapstyle karaoke 12abff 1 1 3\n"), "{text}");
7622 assert_eq!(load(&path).expect("v40 loads").caption_style, style);
7623 // The default is no line and an older header: the bytes an older build wrote.
7624 save(&CaptionStyle::default());
7625 let text = std::fs::read_to_string(&path).unwrap();
7626 assert!(!text.contains("capstyle") && !text.starts_with("edith 40"), "{text}");
7627 assert_eq!(load(&path).unwrap().caption_style, CaptionStyle::default());
7628 let old = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v36 file loads");
7629 assert_eq!(old.caption_style, CaptionStyle::default());
7630 let mixed = parse(b"edith 39\nsource 0 a.mp4\ncapstyle pop ffd600 0 0 0\n", &dir)
7631 .unwrap_err()
7632 .to_string();
7633 assert_eq!(mixed, "line 3: unknown keyword \"capstyle\"");
7634 for line in [
7635 "capstyle spin ffd600 0 0 0",
7636 "capstyle pop ffd60 0 0 0",
7637 "capstyle pop ffd600 2 0 0",
7638 "capstyle pop ffd600 0 0 99",
7639 "capstyle pop ffd600 0 0",
7640 ] {
7641 let file = format!("edith 40\nsource 0 a.mp4\n{line}\n");
7642 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7643 }
7644 std::fs::remove_file(&path).ok();
7645 std::fs::remove_dir(&dir).ok();
7646 }
7647
7648 /// Crafted files that declare more than any editor writes get a clear error,
7649 /// never an allocation or a hang.
7650 #[test]
7651 fn crafted_tables_over_the_caps_are_refused() {
7652 let dir = PathBuf::from("/proj");
7653 let head = "edith 40\nsource 0 a.mp4\n";
7654 let bands = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS + 1].join(" ");
7655 let words = "0 1 w ".repeat(MAX_CUE_WORDS + 1);
7656 let order = (0..=MAX_SEQUENCES).map(|i| i.to_string()).collect::<Vec<_>>().join(" ");
7657 for (file, what) in [
7658 (format!("{head}eq {bands}\n"), "equalizer"),
7659 (format!("{head}cuewords 0 0 {}\n", words.trim_end()), "cuewords"),
7660 (format!("edith 45\nsource 0 a.mp4\nseqorder {order}\n"), "seqorder"),
7661 ] {
7662 let err = parse(file.as_bytes(), &dir).expect_err(what).to_string();
7663 assert!(err.contains("at most") || err.contains("more than"), "{what}: {err}");
7664 }
7665 // And a table of exactly the cap still opens.
7666 let ok = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS].join(" ");
7667 assert!(parse(format!("{head}eq {ok}\n").as_bytes(), &dir).is_ok());
7668 // A project whose lists run past the cap is refused as a whole.
7669 let mut many = String::from("edith 40\nsource 0 a.mp4\n");
7670 for i in 0..=MAX_LIST_ENTRIES {
7671 many.push_str(&format!("chapter {i} c\n"));
7672 }
7673 let err = parse(many.as_bytes(), &dir).unwrap_err().to_string();
7674 assert!(err.contains("at most"), "{err}");
7675 }
7676
7677 #[test]
7678 fn the_newest_version_is_the_magic_line_the_writer_emits() {
7679 assert_eq!(MAGIC, format!("edith {NEWEST_VERSION}").as_bytes());
7680 }
7681
7682 #[test]
7683 fn malformed_lines_name_their_line_number() {
7684 let dir = PathBuf::from("/proj");
7685 let cases: [(&[u8], &str); 10] = [
7686 // v3 wants the stream before the path, and a path after it.
7687 (
7688 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
7689 "line 2: \"a.mp4\" is not a number",
7690 ),
7691 (
7692 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
7693 "line 2: source without a path",
7694 ),
7695 (
7696 b"edith 1\nsource a.mp4\nclip 0 5\n",
7697 "line 3: clip wants 3 fields, found 2",
7698 ),
7699 (
7700 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
7701 "line 3: \"five\" is not a number",
7702 ),
7703 (
7704 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
7705 "line 3: clip [5, 5) is empty",
7706 ),
7707 (
7708 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
7709 "line 3: clip [7, 5) is empty",
7710 ),
7711 (
7712 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
7713 "line 3: clip names source 1 of 1",
7714 ),
7715 (
7716 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
7717 "line 4: source after a clip",
7718 ),
7719 (
7720 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
7721 "line 3: unknown keyword \"\"",
7722 ),
7723 (
7724 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
7725 "line 3: playhead belongs once, before the sources",
7726 ),
7727 ];
7728 for (bytes, want) in cases {
7729 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
7730 }
7731 }
7732
7733 /// The emptied timeline writes and reads back: every lane declared, no clip
7734 /// on any of them, and the source that gave the project its frame rate still
7735 /// named. Nothing about the format changes for it -- an empty lane already
7736 /// had a line of its own.
7737 #[test]
7738 fn a_project_without_clips_round_trips() {
7739 let dir = PathBuf::from("/proj");
7740 let source = Source {
7741 path: PathBuf::from("/proj/a.mp4"),
7742 audio_stream: 0, ..Default::default()
7743 };
7744 let bytes = flat(
7745 &dir,
7746 std::slice::from_ref(&source),
7747 &two(Vec::new(), Vec::new()),
7748 0,
7749 );
7750 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
7751 assert_eq!(back.sources, vec![source]);
7752 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
7753 assert_eq!(back.playhead, 0);
7754 // Older dialects, where the two lanes are implied rather than declared.
7755 assert_eq!(
7756 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
7757 two(Vec::new(), Vec::new())
7758 );
7759 assert!(
7760 parse(b"edith 1\n", &dir)
7761 .expect("a project of nothing")
7762 .sources
7763 .is_empty()
7764 );
7765 }
7766
7767 /// Every truncation of a good file either parses or refuses; none panics.
7768 #[test]
7769 fn truncations_never_panic() {
7770 let (dir, sources, lanes) = doc();
7771 let bytes = flat(&dir, &sources, &lanes, 12);
7772 for cut in 0..bytes.len() {
7773 let _ = parse(&bytes[..cut], &dir);
7774 // ...and the same file with a byte lopped off the front, which
7775 // shifts every field into the wrong place.
7776 let _ = parse(&bytes[cut..], &dir);
7777 }
7778 // A % escape at the very end of a line has nothing to consume.
7779 assert_eq!(
7780 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
7781 .unwrap_err()
7782 .to_string(),
7783 "line 2: truncated % escape in the path"
7784 );
7785 }
7786
7787 /// A clip's visualizer field is a whole byte of flags, and a line naming one
7788 /// past it used to be truncated into a look nobody chose (`300` loaded as
7789 /// `44`, with the fast bit and the ink nibble both wrong). It is refused by
7790 /// name now, like the resolution's bound, the sample rate's range, the tone
7791 /// map and the encoder seat beside it.
7792 #[test]
7793 fn a_visualizer_byte_past_a_byte_is_refused_and_the_legal_ones_still_load() {
7794 // The door the parser reads that field through: the low bits are the
7795 // style, bit 3 the fast flag and the high nibble the ink, so every value a
7796 // byte holds is a look and 256 and up is not one.
7797 assert_eq!(flags_byte(b"0", 1).expect("zero is the plain look"), 0);
7798 assert_eq!(flags_byte(b"255", 1).expect("the whole byte is flags"), 255);
7799 let refused = flags_byte(b"300", 9).expect_err("300 is not a byte of flags");
7800 assert_eq!(
7801 refused.to_string(),
7802 "line 9: 300 is not a set of visualizer flags"
7803 );
7804 }
7805
7806 /// ...and the same field through the parser, on a document of the newest
7807 /// dialect: the legal byte is what lands in the clip, the illegal one is the
7808 /// refusal above rather than a truncation.
7809 #[test]
7810 fn a_clip_line_whose_visualizer_is_past_a_byte_loses_the_whole_load() {
7811 let dir = PathBuf::from("/proj");
7812 let line = |flags: &str| {
7813 format!(
7814 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7815 video 1 0 0 30 0 - - - fit 1000 0 0 0 - {flags} 0\n"
7816 )
7817 };
7818 let doc = parse(line("12").as_bytes(), &dir).expect("12 is a look");
7819 // The keyword is the saver's own for this dialect, so a mismatch here would
7820 // be this test's line and not the field it is about.
7821 assert_eq!(doc.lanes[0].1[0].visualizer, 12);
7822 let refused = parse(line("300").as_bytes(), &dir).expect_err("300 is not a look");
7823 assert!(
7824 refused
7825 .to_string()
7826 .contains("is not a set of visualizer flags"),
7827 "{refused}"
7828 );
7829 }
7830}
7831
7832#[cfg(test)]
7833mod title_tests {
7834 use super::*;
7835
7836 fn sample() -> Vec<Title> {
7837 vec![
7838 Title {
7839 start: 0,
7840 frames: 90,
7841 text: "Episode 17\n100% \\ done".into(),
7842 style: TextStyle {
7843 size: 80,
7844 outline: Outline::Thick,
7845 boxed: false,
7846 place: Place::Centre,
7847 ..TextStyle::default()
7848 },
7849 fade_in: 10,
7850 fade_out: 5,
7851 in_anim: TitleAnim::None,
7852 out_anim: TitleAnim::None,
7853 anim_frames: 0,
7854 keys: Vec::new(),
7855 },
7856 Title {
7857 start: 60,
7858 frames: 120,
7859 text: "Jane Doe \u{2014} Engineer".into(),
7860 style: TextStyle::default(),
7861 fade_in: 0,
7862 fade_out: 0,
7863 in_anim: Default::default(),
7864 out_anim: Default::default(),
7865 anim_frames: 0,
7866 keys: Vec::new(),
7867 },
7868 ]
7869 }
7870
7871 fn styled() -> Vec<Title> {
7872 let mut t = sample();
7873 t[1].style = TextStyle {
7874 hplace: HPlace::Left,
7875 align: Align::Right,
7876 weight: Weight::Bold,
7877 ink: [255, 204, 0],
7878 box_color: [10, 20, 30, 200],
7879 ..TextStyle::default()
7880 };
7881 t
7882 }
7883
7884 #[test]
7885 fn a_title_look_round_trips_and_only_a_styled_one_writes_a_line() {
7886 // Default looks write no `titlestyle` line at all.
7887 assert!(!String::from_utf8(title_lines(&sample())).unwrap().contains("titlestyle"));
7888 let titles = styled();
7889 let body = title_lines(&titles);
7890 let text = String::from_utf8(body.clone()).unwrap();
7891 assert_eq!(text.matches("titlestyle").count(), 1);
7892 assert!(text.contains("titlestyle 1 left right bold ffcc00 0a141ec8\n"), "{text}");
7893 let mut bytes = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7894 bytes.extend_from_slice(&body);
7895 let doc = parse(&bytes, Path::new(".")).expect("a v49 file with a title look parses");
7896 assert_eq!(doc.titles, titles);
7897 let mut again = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7898 again.extend_from_slice(&title_lines(&doc.titles));
7899 assert_eq!(again, bytes);
7900 }
7901
7902 #[test]
7903 fn a_title_look_is_a_v49_line_and_a_bad_one_is_refused_by_name() {
7904 let head = |v: u32| format!("edith {v}\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\ntitle 0 10 0 0 50 none 1 bottom hi\n");
7905 let ok = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(49));
7906 assert!(parse(ok.as_bytes(), Path::new(".")).is_ok());
7907 let old = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(48));
7908 assert!(parse(old.as_bytes(), Path::new(".")).is_err(), "titlestyle is not a v48 line");
7909 // A v48 file with plain titles still loads, with the default look.
7910 let doc = parse(head(48).as_bytes(), Path::new(".")).unwrap();
7911 assert_eq!(doc.titles[0].style, TextStyle { boxed: true, ..TextStyle::default() });
7912 for line in [
7913 "titlestyle 0 middle left bold ffffff 000000ff",
7914 "titlestyle 0 left up bold ffffff 000000ff",
7915 "titlestyle 0 left left heavy ffffff 000000ff",
7916 "titlestyle 0 left left bold fff 000000ff",
7917 "titlestyle 0 left left bold ffffff 000000",
7918 "titlestyle 5 left left bold ffffff 000000ff",
7919 ] {
7920 let text = format!("{}{line}\n", head(49));
7921 assert!(parse(text.as_bytes(), Path::new(".")).is_err(), "{line}");
7922 }
7923 }
7924
7925 #[test]
7926 fn title_lines_round_trip_through_the_loader_with_escapes() {
7927 let titles = sample();
7928 let mut bytes = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7929 bytes.extend_from_slice(&title_lines(&titles));
7930 let doc = parse(&bytes, Path::new(".")).expect("a v26 file with titles parses");
7931 assert_eq!(doc.titles, titles);
7932 // Written and read again, the same bytes come back.
7933 let mut again = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7934 again.extend_from_slice(&title_lines(&doc.titles));
7935 assert_eq!(again, bytes);
7936 }
7937
7938 #[test]
7939 fn a_v25_file_has_no_titles_and_loads() {
7940 let v25 = b"edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7941 let doc = parse(v25, Path::new(".")).expect("v25 still loads");
7942 assert!(doc.titles.is_empty());
7943 let as_v25 = b"edith 25\nplayhead 0\nsource 0 a.mp4\ntitle 0 10 0 0 50 none 0 bottom hi\n";
7944 assert!(
7945 parse(as_v25, Path::new(".")).is_err(),
7946 "title is not a v25 line"
7947 );
7948 }
7949
7950 #[test]
7951 fn a_title_line_outside_its_range_is_refused_by_name() {
7952 let head = "edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7953 for line in [
7954 "title 0 0 0 0 50 none 0 bottom hi",
7955 "title 0 10 0 0 9 none 0 bottom hi",
7956 "title 0 10 0 0 50 wavy 0 bottom hi",
7957 "title 0 10 0 0 50 none 2 bottom hi",
7958 "title 0 10 0 0 50 none 0 middle hi",
7959 "title 0 10 11 0 50 none 0 bottom hi",
7960 "title 0 10 0 0 50 none 0 bottom",
7961 ] {
7962 let body = format!("{head}{line}\n");
7963 assert!(
7964 parse(body.as_bytes(), Path::new(".")).is_err(),
7965 "{line} was accepted"
7966 );
7967 }
7968 }
7969}
7970
7971#[cfg(test)]
7972mod clip_gain_tests {
7973 use super::*;
7974
7975 /// A v26 file loads, every clip at unity; a `clipgain` line in one is a
7976 /// line the dialect does not have, so it is refused by number.
7977 #[test]
7978 fn a_v26_file_loads_at_unity_and_refuses_a_clipgain_line() {
7979 let dir = PathBuf::from("/proj");
7980 let old = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7981 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7982 let doc = parse(old, &dir).expect("a v26 file still loads");
7983 assert_eq!(doc.lanes[0].1[0].gain_db, 0.0);
7984 let with = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7985 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\nclipgain audio 1 0 -6\n";
7986 let err = parse(with, &dir).unwrap_err().to_string();
7987 assert!(err.contains("line 6"), "{err}");
7988 }
7989
7990 /// The writer's own bytes: a gained clip gets a `clipgain` line after its
7991 /// lanes, unity clips get none, and the value comes back exactly.
7992 #[test]
7993 fn clip_gain_lines_are_written_only_off_unity_and_round_trip() {
7994 let dir = PathBuf::from("/proj");
7995 let clip = |gain_db: f32| Clip {
7996 speed_keys: Vec::new(),
7997 reversed: false,
7998 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
7999 angle: Default::default(),
8000 gain_keys: Vec::new(),
8001 pan: 0,
8002 transform_keys: Vec::new(),
8003 opacity_keys: Vec::new(),
8004 color_keys: Vec::new(),
8005 effects: Vec::new(),
8006 start: 0,
8007 in_frame: 0,
8008 out_frame: 30,
8009 source: 0,
8010 link: None,
8011 eq: None,
8012 color: None,
8013 transform: None,
8014 fit: FitPolicy::default(),
8015 speed: Speed::NORMAL,
8016 fade_in: 0,
8017 fade_out: 0,
8018 transition_out: 0,
8019 transition_kind: Default::default(),
8020 visualizer: 0,
8021 viz_paint: 0,
8022 gain_db,
8023 pitch: 0,
8024 };
8025 let lanes = vec![
8026 (LaneKind::Video, vec![clip(0.0)]),
8027 (LaneKind::Audio, vec![clip(-6.5), clip(0.0)]),
8028 ];
8029 let bytes = clip_gain_lines(&lanes);
8030 assert_eq!(bytes, b"clipgain audio 1 0 -6.5\n".to_vec());
8031 let mut text = b"edith 27\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8032 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8033 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8034 audio 1 30 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"
8035 .to_vec();
8036 text.extend_from_slice(&bytes);
8037 let doc = parse(&text, &dir).expect("a v27 file with a clip gain parses");
8038 assert_eq!(doc.lanes[1].1[0].gain_db, -6.5);
8039 assert_eq!(doc.lanes[1].1[1].gain_db, 0.0);
8040 }
8041}
8042
8043#[cfg(test)]
8044mod gain_key_tests {
8045 use super::*;
8046
8047 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8048 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8049
8050 /// A v27 file loads with every clip's envelope empty, and a `gainkeys` line
8051 /// in one is a line the dialect does not have, so it is refused by number.
8052 #[test]
8053 fn a_v27_file_loads_flat_and_refuses_a_gainkeys_line() {
8054 let dir = PathBuf::from("/proj");
8055 let old = format!("edith 27\n{HEAD}");
8056 let doc = parse(old.as_bytes(), &dir).expect("a v27 file still loads");
8057 assert!(doc.lanes[0].1[0].gain_keys.is_empty());
8058 let with = format!("edith 27\n{HEAD}gainkeys audio 1 0 0:-6\n");
8059 let err = parse(with.as_bytes(), &dir).unwrap_err().to_string();
8060 assert!(err.contains("line 6"), "{err}");
8061 }
8062
8063 /// The writer's own bytes: a clip with points gets one `gainkeys` line after
8064 /// its lanes, a clip without gets none, and the points come back exactly.
8065 #[test]
8066 fn gain_key_lines_are_written_only_with_points_and_round_trip() {
8067 let dir = PathBuf::from("/proj");
8068 let mut text = format!("edith 28\n{HEAD}").into_bytes();
8069 text.extend_from_slice(b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n");
8070 let doc = parse(&text, &dir).expect("a v28 file with an envelope parses");
8071 let keys = &doc.lanes[0].1[0].gain_keys;
8072 assert_eq!(
8073 keys,
8074 &[
8075 GainKey::new(0, 0.0),
8076 GainKey::new(30, -20.0),
8077 GainKey::new(45, -6.5),
8078 ]
8079 );
8080 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8081 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8082 let bytes = gain_key_lines(&lanes);
8083 assert_eq!(bytes, b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n".to_vec());
8084 let again = parse(
8085 &[format!("edith 28\n{HEAD}").as_bytes(), &bytes].concat(),
8086 &dir,
8087 )
8088 .expect("the writer's own line parses");
8089 assert_eq!(again.lanes[0].1[0].gain_keys, *keys);
8090 }
8091
8092 /// A ramp can make a clip shorter than its constant footprint, which the lines before
8093 /// its `speedkeys` still show: the next clip, placed against the ramp's length, loads;
8094 /// one that really overlaps the ramped footprint is refused.
8095 #[test]
8096 fn a_clip_placed_against_a_shorter_ramp_loads_and_a_real_overlap_does_not() {
8097 let dir = PathBuf::from("/proj");
8098 let next = |start: u32| {
8099 format!("audio 1 {start} 0 30 0 - - - fit 1000 0 0 0 - 0 0\n")
8100 };
8101 let ok = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(22));
8102 let doc = parse(ok.as_bytes(), &dir).expect("the ramp is 22 frames, the next clip starts at 22");
8103 assert_eq!(doc.lanes[0].1.len(), 2);
8104 let bad = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(21));
8105 assert!(parse(bad.as_bytes(), &dir).is_err(), "21 is inside the ramped clip");
8106 }
8107
8108 /// A `speedkeys` line is a v35 clip's ramp: it reads back as the keys, its footprint
8109 /// is the ramp's, and the writer's own line reads back to the same keys. A clip with no
8110 /// keys writes no line.
8111 #[test]
8112 fn speedkeys_lines_round_trip_and_a_clip_without_a_ramp_writes_none() {
8113 let dir = PathBuf::from("/proj");
8114 let text = format!("edith 35\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8115 let doc = parse(text.as_bytes(), &dir).expect("a v35 file with a ramp parses");
8116 let clip = &doc.lanes[0].1[0];
8117 assert_eq!(
8118 clip.speed_keys,
8119 vec![
8120 SpeedKey { at: 0, speed: Speed::NORMAL },
8121 SpeedKey { at: 30, speed: Speed::from_permille(2000) },
8122 ]
8123 );
8124 // 30 source frames at a rate that climbs from 1x to 2x: 22 timeline frames.
8125 assert_eq!(clip.frames(), 22);
8126 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8127 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8128 assert_eq!(speed_key_lines(&lanes), b"speedkeys audio 1 0 0:1000 30:2000\n".to_vec());
8129 let mut plain = lanes.clone();
8130 plain[0].1[0].speed_keys.clear();
8131 assert!(speed_key_lines(&plain).is_empty(), "no ramp, no line");
8132 let again = parse(
8133 &[format!("edith 35\n{HEAD}").as_bytes(), &speed_key_lines(&lanes)].concat(),
8134 &dir,
8135 )
8136 .expect("the writer's own line parses");
8137 assert_eq!(again.lanes[0].1[0].speed_keys, clip.speed_keys);
8138 }
8139
8140 /// A `transition` line (v37) names how a clip's dissolve is drawn: every kind's name
8141 /// reads back as the kind, the writer's own lines parse, a clip with the default writes
8142 /// none, and an older file (no line) means a dissolve.
8143 #[test]
8144 fn transition_lines_round_trip_every_kind_and_old_files_dissolve() {
8145 let dir = PathBuf::from("/proj");
8146 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8147 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8148 let old = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("v35 parses");
8149 assert_eq!(old.lanes[0].1[0].transition_kind, TransitionKind::Dissolve);
8150 let mut kinds = Vec::new();
8151 for shape in TransitionKind::SHAPES {
8152 match shape.dir() {
8153 Some(_) => kinds.extend(crate::transitions::Dir::ALL.map(|d| shape.with_dir(d))),
8154 None => kinds.push(shape),
8155 }
8156 }
8157 for kind in kinds {
8158 let mut lanes: Vec<(LaneKind, Vec<Clip>)> = old.lanes.clone();
8159 lanes[0].1[0].transition_kind = kind;
8160 let lines = transition_lines(&lanes);
8161 if kind == TransitionKind::Dissolve {
8162 assert!(lines.is_empty(), "the default writes no line");
8163 }
8164 let text = [format!("edith 37\n{head}").as_bytes(), &lines].concat();
8165 let back = parse(&text, &dir).unwrap_or_else(|e| panic!("{}: {e}", kind.name()));
8166 assert_eq!(back.lanes[0].1[0].transition_kind, kind);
8167 }
8168 for bad in ["transition video 1 0 swirl\n", "transition video 1 4 zoom\n", "transition video 2 0 zoom\n"] {
8169 let err = parse(format!("edith 37\n{head}{bad}").as_bytes(), &dir).unwrap_err().to_string();
8170 assert!(err.contains("line 6"), "{bad}: {err}");
8171 }
8172 for old in [35, 36] {
8173 let file = format!("edith {old}\n{head}transition video 1 0 zoom\n");
8174 assert!(parse(file.as_bytes(), &dir).is_err(), "a v{old} reader has no such line");
8175 }
8176 }
8177
8178 /// The writer emits the highest version a project needs: markers alone are v36, a
8179 /// transition kind makes it v37 (markers and all, which round-trip together), only
8180 /// dissolves and no markers fall back to the older header, and a v36 file still loads.
8181 #[test]
8182 fn the_header_is_the_highest_version_needed_and_v36_and_v37_round_trip() {
8183 use crate::project::{Marker, MarkerColor};
8184 let dir = std::env::temp_dir().join(format!("edith-v37-{}", std::process::id()));
8185 std::fs::create_dir_all(&dir).unwrap();
8186 let path = dir.join("v37.edith");
8187 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8188 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8189 let sources = doc.sources;
8190 let mut lanes = doc.lanes;
8191 let markers = vec![Marker { frame: 12, length: 0, name: "Beat".into(), note: "a note".into(), color: MarkerColor::Blue }];
8192 let save_styled = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker], cs: &CaptionStyle| {
8193 save_flagged(
8194 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8195 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8196 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, cs, &[], &[],
8197 )
8198 .expect("saves");
8199 std::fs::read_to_string(&path).unwrap()
8200 };
8201 let save = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker]| {
8202 save_styled(lanes, markers, &CaptionStyle::default())
8203 };
8204 assert!(save(&lanes, &markers).starts_with("edith 36\n"), "markers alone are v36");
8205 lanes[0].1[0].transition_kind = TransitionKind::Zoom;
8206 let text = save(&lanes, &markers);
8207 assert!(text.starts_with("edith 37\n"), "a transition makes it v37: {text}");
8208 let back = load(&path).expect("v37 loads");
8209 assert_eq!(back.markers, markers);
8210 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8211 let text = save(&lanes, &[]);
8212 assert!(text.starts_with("edith 37\n") && text.contains("transition "), "{text}");
8213 lanes[0].1[0].reversed = true;
8214 let text = save(&lanes, &markers);
8215 assert!(text.starts_with("edith 38\n") && text.contains("reverse video 1 0"), "a reversed clip makes it v38: {text}");
8216 let back = load(&path).expect("v38 loads");
8217 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8218 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8219 lanes[0].1[0].opacity_keys = vec![OpacityKey { at: 0, opacity: 0.5, ease: KeyEase::Hold }];
8220 let text = save(&lanes, &markers);
8221 assert!(text.starts_with("edith 39\n") && text.contains("okeys video 1 0"), "an animation makes it v39: {text}");
8222 let back = load(&path).expect("v39 loads");
8223 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8224 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8225 // ...and a project caption style on top of all of it makes it v40.
8226 let style = CaptionStyle { anim: crate::captionanim::CaptionAnim::Pop, ..CaptionStyle::default() };
8227 let text = save_styled(&lanes, &markers, &style);
8228 assert!(text.starts_with("edith 40\n") && text.contains("\ncapstyle pop "), "a caption style makes it v40: {text}");
8229 let back = load(&path).expect("v40 loads");
8230 assert!(back.lanes[0].1[0].reversed && back.markers == markers && back.caption_style == style);
8231 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8232 lanes[0].1[0].opacity_keys.clear();
8233 lanes[0].1[0].reversed = false;
8234 lanes[0].1[0].transition_kind = TransitionKind::Dissolve;
8235 let text = save(&lanes, &[]);
8236 assert!(!text.starts_with("edith 40") && !text.starts_with("edith 39") && !text.starts_with("edith 38") && !text.starts_with("edith 37") && !text.starts_with("edith 36"), "{text}");
8237 let v36 = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).expect("a v36 file loads");
8238 assert_eq!(v36.markers.len(), 1);
8239 std::fs::remove_dir_all(&dir).ok();
8240 }
8241
8242 /// `lanename` and `deint` lines are v46: both round-trip, a project with neither keeps
8243 /// its older header and exact bytes, an older header refuses them and bad ones are
8244 /// refused by line.
8245 #[test]
8246 fn lane_names_and_deinterlace_round_trip_in_v46_and_without_them_the_bytes_are_unchanged() {
8247 let dir = std::env::temp_dir().join(format!("edith-v46-{}", std::process::id()));
8248 std::fs::create_dir_all(&dir).unwrap();
8249 let path = dir.join("v46.edith");
8250 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8251 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8252 let sources = doc.sources;
8253 let mut lanes = doc.lanes;
8254 let n = lanes.len();
8255 let save = |lanes: &[(LaneKind, Vec<Clip>)], names: &[String]| {
8256 save_flagged(
8257 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8258 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8259 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], names,
8260 )
8261 .expect("saves");
8262 std::fs::read_to_string(&path).unwrap()
8263 };
8264 let blank = vec![String::new(); n];
8265 let plain = save(&lanes, &blank);
8266 assert!(!plain.contains("lanename") && !plain.contains("deint") && !plain.starts_with("edith 46"), "{plain}");
8267 let mut names = blank.clone();
8268 names[0] = "Main \\ cam".into();
8269 let text = save(&lanes, &names);
8270 assert!(text.starts_with("edith 46\n") && text.contains("\nlanename video 1 Main \\\\ cam\n"), "{text}");
8271 assert_eq!(load(&path).expect("v46 loads").names[0], "Main \\ cam");
8272 assert_eq!(save(&lanes, &blank), plain, "no names is the bytes it was");
8273 lanes[0].1[0].deinterlace = Deinterlace::Field;
8274 let text = save(&lanes, &blank);
8275 assert!(text.starts_with("edith 46\n") && text.contains("\ndeint video 1 0 field\n"), "{text}");
8276 assert_eq!(load(&path).unwrap().lanes[0].1[0].deinterlace, Deinterlace::Field);
8277 for older in ["edith 45", "edith 44"] {
8278 for line in ["lanename video 1 X\n", "deint video 1 0 off\n"] {
8279 let old = format!("{older}\n{head}{line}");
8280 assert!(parse(old.as_bytes(), &dir).is_err(), "{older} refuses {line:?}");
8281 }
8282 }
8283 for (line, why) in [
8284 ("lanename video 1 \n", "1 to"),
8285 ("lanename video 3 X\n", "not there"),
8286 ("lanename tape 1 X\n", "not a lane kind"),
8287 ("deint video 1 0 weave\n", "frame, field or off"),
8288 ("deint video 1 4 off\n", "does not have"),
8289 ] {
8290 let err = parse(format!("edith 46\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8291 assert!(err.contains(why) && err.contains("line"), "{line:?}: {err}");
8292 }
8293 let long = "x".repeat(crate::project::MAX_LANE_NAME_CHARS + 1);
8294 assert!(parse(format!("edith 46\n{head}lanename video 1 {long}\n").as_bytes(), &dir).is_err());
8295 std::fs::remove_file(&path).ok();
8296 std::fs::remove_dir(&dir).ok();
8297 }
8298
8299 /// A `stab` line is a v44 clip's stabilisation: it round-trips through a save, a
8300 /// project with no stabilised clip keeps its older header and its exact bytes, an
8301 /// older file refuses the line and a bad one is refused by its line number.
8302 #[test]
8303 fn stab_lines_round_trip_in_v44_and_without_one_the_bytes_are_unchanged() {
8304 let dir = std::env::temp_dir().join(format!("edith-stab-{}", std::process::id()));
8305 std::fs::create_dir_all(&dir).unwrap();
8306 let path = dir.join("v44.edith");
8307 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8308 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8309 let sources = doc.sources;
8310 let mut lanes = doc.lanes;
8311 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
8312 save_flagged(
8313 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8314 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8315 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
8316 )
8317 .expect("saves");
8318 std::fs::read_to_string(&path).unwrap()
8319 };
8320 let plain = save(&lanes);
8321 assert!(!plain.contains("stab") && !plain.starts_with("edith 44"), "{plain}");
8322 let st = crate::stabilise::Stabilise::new(0.75, crate::stabilise::Crop::Full);
8323 lanes[0].1[0].stabilise = Some(st);
8324 let text = save(&lanes);
8325 assert!(text.starts_with("edith 44\n") && text.contains("\nstab video 1 0 0.75 full\n"), "{text}");
8326 assert_eq!(load(&path).expect("v44 loads").lanes[0].1[0].stabilise, Some(st));
8327 lanes[0].1[0].stabilise = None;
8328 assert_eq!(save(&lanes), plain, "off again is the bytes it was");
8329 for older in ["edith 43", "edith 42", "edith 41"] {
8330 let old = format!("{older}\n{head}stab video 1 0 0.5 zoom\n");
8331 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("stab"), "{older} has no stab line");
8332 }
8333 for (line, why) in [
8334 ("stab video 1 0 0.5\n", "wants a video clip"),
8335 ("stab video 1 0 1.5 zoom\n", "from 0 to 1"),
8336 ("stab video 1 0 0.5 tilt\n", "zoom or full"),
8337 ("stab video 1 4 0.5 zoom\n", "which the lane does not have"),
8338 ] {
8339 let err = parse(format!("edith 44\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8340 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8341 }
8342 std::fs::remove_dir_all(&dir).ok();
8343 }
8344
8345 /// A `reverse` line is a v38 clip's direction: it reads back as `reversed`, the
8346 /// writer's own line reads back the same, a project with none is written under
8347 /// the v35 header it always was, and an older file or a bad line is refused by
8348 /// its line number.
8349 #[test]
8350 fn reverse_lines_round_trip_and_older_files_and_bad_lines_are_refused() {
8351 let dir = PathBuf::from("/proj");
8352 let text = format!("edith 38\n{HEAD}reverse audio 1 0\n");
8353 let doc = parse(text.as_bytes(), &dir).expect("a v38 file with a reversed clip parses");
8354 assert!(doc.lanes[0].1[0].reversed);
8355 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8356 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8357 assert_eq!(reverse_lines(&lanes), b"reverse audio 1 0\n".to_vec());
8358 let mut plain = lanes.clone();
8359 plain[0].1[0].reversed = false;
8360 assert!(reverse_lines(&plain).is_empty(), "forward, no line");
8361 let again = parse(
8362 &[format!("edith 38\n{HEAD}").as_bytes(), &reverse_lines(&lanes)].concat(),
8363 &dir,
8364 )
8365 .expect("the writer's own line parses");
8366 assert!(again.lanes[0].1[0].reversed);
8367 // A v37 file (or older) has no such line.
8368 for old in [35, 37] {
8369 let file = format!("edith {old}\n{HEAD}reverse audio 1 0\n");
8370 let err = parse(file.as_bytes(), &dir).unwrap_err().to_string();
8371 assert!(err.contains("reverse"), "v{old}: {err}");
8372 }
8373 let head = format!("edith 38\n{HEAD}");
8374 for (line, why) in [
8375 ("reverse audio 1\n", "wants a lane and a clip"),
8376 ("reverse subtitle 1 0\n", "not a lane kind"),
8377 ("reverse audio 9 0\n", "a lane that is not there"),
8378 ("reverse audio 1 5\n", "which the lane does not have"),
8379 ] {
8380 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8381 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8382 }
8383 }
8384
8385 /// A v34 file has no `speedkeys` line, and a bad ramp is refused by its line: a speed
8386 /// out of range, keys out of frame order, a key without a speed, or more than the cap.
8387 #[test]
8388 fn a_v34_file_refuses_a_speedkeys_line_and_a_bad_ramp_is_refused() {
8389 let dir = PathBuf::from("/proj");
8390 let v34 = format!("edith 34\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8391 let err = parse(v34.as_bytes(), &dir).unwrap_err().to_string();
8392 assert!(err.contains("speedkeys"), "{err}");
8393 let head = format!("edith 35\n{HEAD}");
8394 for line in [
8395 "speedkeys audio 1 0 0:9000\n",
8396 "speedkeys audio 1 0 30:1000 0:1000\n",
8397 "speedkeys audio 1 0 0\n",
8398 "speedkeys audio 1 0 0:1000 1:1000 2:1000 3:1000 4:1000 5:1000 6:1000 7:1000 8:1000\n",
8399 ] {
8400 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8401 assert!(err.contains("line 6"), "{line}: {err}");
8402 }
8403 }
8404
8405 /// A point out of source order, one out of range, or a clip with more than
8406 /// the cap are all refused by line; the dialect keeps the invariants.
8407 #[test]
8408 fn a_bad_gainkeys_line_is_refused() {
8409 let dir = PathBuf::from("/proj");
8410 let head = format!("edith 28\n{HEAD}");
8411 for line in [
8412 "gainkeys audio 1 0 30:-6 0:0\n",
8413 "gainkeys audio 1 0 0:-90\n",
8414 "gainkeys audio 1 0 0\n",
8415 "gainkeys audio 1 0 0 0x\n",
8416 ] {
8417 let text = format!("{head}{line}");
8418 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8419 assert!(err.contains("line 6"), "{line}: {err}");
8420 }
8421 let many: String = (0..=MAX_GAIN_KEYS as u32)
8422 .map(|i| format!(" {i}:0"))
8423 .collect();
8424 let text = format!("{head}gainkeys audio 1 0 0{many}\n");
8425 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8426 assert!(err.contains("more than"), "{err}");
8427 }
8428}
8429
8430#[cfg(test)]
8431mod animation_key_tests {
8432 use super::*;
8433
8434 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8435 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8436 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8437
8438 /// A v35 file written before the easings existed still loads, every key linear
8439 /// (or the `ease` it said), and resaving it does not change a key.
8440 #[test]
8441 fn a_v35_file_upgrades_with_its_keys_linear_and_resaves_as_v32_bytes() {
8442 let dir = PathBuf::from("/proj");
8443 let text = format!(
8444 "edith 35\n{HEAD}gainkeys audio 1 0 0:0 20:-6.5\n\
8445 tkeys video 1 0 0:lin:0,0,1,0,0,0,0,0,1 20:ease:0,0,2,0,0,0,0,0,0.5\n"
8446 );
8447 let doc = parse(text.as_bytes(), &dir).expect("a v35 file loads");
8448 let clips = &doc.lanes[1].1;
8449 assert_eq!(clips[0].gain_keys, [GainKey::new(0, 0.0), GainKey::new(20, -6.5)]);
8450 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Ease);
8451 assert!(doc.lanes[0].1[0].opacity_keys.is_empty() && doc.lanes[0].1[0].color_keys.is_empty());
8452 // The writers' lines for those clips are the bytes the file had.
8453 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0 20:-6.5\n".to_vec());
8454 assert_eq!(
8455 tkey_lines(&doc.lanes),
8456 b"tkeys video 1 0 0:lin:0,0,1,0,0,0,0,0,1 20:ease:0,0,2,0,0,0,0,0,0.5\n".to_vec()
8457 );
8458 assert!(doc.lanes.iter().all(|(_, clips)| !clips.iter().any(needs_v39)), "still not a v39 project");
8459 assert!(opacity_key_lines(&doc.lanes).is_empty() && color_key_lines(&doc.lanes).is_empty());
8460 }
8461
8462 /// The v39 lines read back, in range and in order, and an older dialect has
8463 /// no such lines (nor the new easings) and says so by line number.
8464 #[test]
8465 fn v39_reads_okeys_ckeys_and_eased_points_and_older_dialects_refuse_them() {
8466 let dir = PathBuf::from("/proj");
8467 let new = format!(
8468 "edith 39\n{HEAD}okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n\
8469 ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n\
8470 gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n\
8471 tkeys video 1 0 0:in:0,0,1,0,0,0,0,0,1 20:hold:0,0,2,0,0,0,0,0,1\n"
8472 );
8473 let doc = parse(new.as_bytes(), &dir).expect("a v39 file loads");
8474 let v = &doc.lanes[0].1[0];
8475 assert_eq!(v.opacity_keys.len(), 3);
8476 assert_eq!(v.opacity_keys[0].ease, KeyEase::EaseIn);
8477 assert_eq!(v.opacity_keys[1], OpacityKey { at: 10, opacity: 0.5, ease: KeyEase::Hold });
8478 assert_eq!(v.color_keys[0].ease, KeyEase::EaseOut);
8479 assert_eq!(v.color_keys[1].params.contrast, 2.0);
8480 assert_eq!(v.transform_keys[1].ease, KeyEase::Hold);
8481 let g = &doc.lanes[1].1[0].gain_keys;
8482 assert_eq!((g[0].ease, g[1].ease, g[2].ease), (KeyEase::EaseOut, KeyEase::Hold, KeyEase::Linear));
8483 // ...and writing them gives the same lines back.
8484 assert_eq!(
8485 opacity_key_lines(&doc.lanes),
8486 b"okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n".to_vec()
8487 );
8488 assert_eq!(
8489 color_key_lines(&doc.lanes),
8490 b"ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n".to_vec()
8491 );
8492 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n".to_vec());
8493
8494 // A v35 reader has none of it.
8495 let old = format!("edith 35\n{HEAD}okeys video 1 0 0:lin:0\n");
8496 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("line 7"));
8497 // ...and so has a v38 one.
8498 let old = format!("edith 38\n{HEAD}okeys video 1 0 0:lin:0\n");
8499 assert!(parse(old.as_bytes(), &dir).is_err(), "a v38 reader has no okeys line");
8500 let old = format!("edith 35\n{HEAD}tkeys video 1 0 0:hold:0,0,1,0,0,0,0,0,1\n");
8501 assert!(parse(old.as_bytes(), &dir).is_err(), "a hold ease is not a v35 word");
8502 }
8503
8504 #[test]
8505 fn bad_okeys_and_ckeys_lines_are_refused() {
8506 let dir = PathBuf::from("/proj");
8507 for bad in [
8508 "okeys video 1 0 0:lin:1.5", // opacity out of range
8509 "okeys video 1 0 5:lin:0 5:lin:1", // two at one frame
8510 "okeys video 1 0 9:lin:0 5:lin:1", // not in source order
8511 "okeys video 1 0 0:wobble:1", // unknown ease
8512 "okeys audio 1 0 0:lin:1", // not a video lane
8513 "okeys video 1 3 0:lin:1", // no such clip
8514 "ckeys video 1 0 0:lin:2,1,1,0", // brightness out of range
8515 "ckeys video 1 0 0:lin:0,1,1", // three values
8516 "ckeys video 1 0 0:lin:0,3,1,0", // contrast out of range
8517 ] {
8518 let text = format!("edith 39\n{HEAD}{bad}\n");
8519 assert!(parse(text.as_bytes(), &dir).is_err(), "{bad}");
8520 }
8521 }
8522}