forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

edith.rs8375 lines, 374.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//! A `cueadd` line is one cue added to a subtitle track, which no file has:
230//! `cueadd <track> <start_us> <end_us> <text>`, the track by its position in
231//! the `subtitle` lines, the times in microseconds on the track's own clock, and
232//! the text escaped as a `cue` line's is. It comes after the `cue` lines, so an
233//! added cue lands among the file's cues however they were retyped. A project
234//! with none is the bytes a v28 one was bar the version line.
235//!
236//! A `pitch` line is `pitch audio <ord> <index> <semitones>`: an audio clip's pitch
237//! shift in whole semitones, `-12` to `12`, written for each clip that is not at `0`,
238//! after the lanes it names (as `clippan` is). **Version 52** is the first dialect
239//! with one; a project with none is the bytes a v51 one was bar the version line.
240//!
241//! The `resolution` line is the **project's** picture size, which is a
242//! different thing from any source's: media of other sizes are placed on it.
243//! It belongs once, beside the playhead, and a file without one (every dialect
244//! before v7) means "source 0's own picture", which is what such a project
245//! always was.
246//!
247//! A source line is `source <audio stream> <path>`: which of the file's audio
248//! tracks that source plays, in the file order
249//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
250//! stream first because a path runs to the end of the line (it may hold
251//! spaces) and an optional *trailing* field could not be told from one.
252//!
253//! An eq line is `eq <band>...`, one band per field, each
254//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk`, `hs`,
255//! `lc` (low cut) or `hc` (high cut) ([`crate::eq::BandKind`]). Like a source it is named by *position* --
256//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
257//! curve write it once. `eq` on its own is the empty cascade, which is a
258//! setting like any other. The numbers are printed to round trip bit-exactly;
259//! anything not finite is refused, here and at [`crate::Project::set_eq`].
260//!
261//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
262//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
263//! -- the first colour line is color 0 -- printed and refused by the same rules.
264//!
265//! A colour line's look ([`crate::color::Look`]) rides on three line types
266//! written at the end of the file and naming the colour line by position:
267//! `wheels <color> <lift> <gamma> <gain>` (each `<master>:<red>:<green>:<blue>`,
268//! -1..1), `curve <color> <channel> <x>:<y>,...` (channel `master`, `red`, `green`
269//! or `blue`, up to 16 points in 0..1 with rising inputs) and `lut <color> <mix>
270//! <path>` (mix 0..1, the path written as a source's is). **Version 43** is the
271//! first dialect with them; a project whose grades have no look is written under
272//! the header it needed before. A LUT file that is missing or malformed does not
273//! stop the load: the clip plays without it and the project names it
274//! ([`crate::Project::lut_problems`]).
275//!
276//! A transform line is `transform <pos_x>:<pos_y>:<scale>:<rotate>:<crop_l>:
277//! <crop_r>:<crop_t>:<crop_b>` ([`crate::transform::TransformParams`]), named by
278//! position exactly as an eq or a colour line is -- the first transform line is
279//! transform 0 -- printed and refused by the same rules: how a clip's picture
280//! sits, is sized, is turned and is trimmed on the canvas, on top of whatever
281//! its fit policy already placed.
282//!
283//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
284//! <color> <fit> <speed> <fade_in> <fade_out> <transition_out> <transform> <visualizer> <viz_paint>`:
285//! which lane the clip is on -- its kind and its 1-based number
286//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
287//! column shows -- then where the clip sits on the timeline, the half-open
288//! source range it plays, the file it plays from, its group id, the eq line it
289//! plays through, the colour line it is graded by (`-` for none of those three)
290//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
291//! `stretch` or `center` ([`crate::scale::FitPolicy`]), how fast it plays,
292//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip
293//! nobody has speeded), and finally its ramp up from silence and ramp down to
294//! it, in timeline frames ([`crate::project::Clip::fade_in`],
295//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), its
296//! cross-dissolve into whatever abuts its end
297//! ([`crate::project::Clip::transition_out`], `0` for a hard cut), and last of
298//! all the transform line it is placed, sized, turned and cropped by, on top
299//! of everything its fit policy already did (`-` for a clip left at its fit
300//! policy's own spot, [`crate::project::Clip::transform`]), a visualizer
301//! flags byte (`0` for an ordinary picture, bit 0 for a waveform of the
302//! source's sound, the rest outline/smooth/fast/tint) and that waveform's
303//! packed look ([`crate::project::Clip::viz_paint`]): hue, sat, strands and
304//! glow in the low four bytes, then the strand colour's own hue and sat,
305//! with the top bit set once a clip has chosen one.
306//! Timeline placement is
307//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
308//! to write for one, and nothing that can disagree about its length. The `<in>`
309//! and `<out>` are *source* frames whatever the speed says: how long the clip is
310//! on the timeline is that range divided by the rate, and is written nowhere.
311//!
312//! A lane is declared by the clips on it, in the order the lanes are displayed
313//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
314//! is the only way an empty lane could still be there on the way back. A lane
315//! number may not skip one of its kind.
316//!
317//! A subtitle lane is a lane like the other two and is written in its place
318//! among them, `sub` for its kind: `sub <lane> <start> <frames> <track>
319//! <in> <out>` ([`crate::project::SubClip`]) -- where the caption sits on the
320//! timeline and how many frames it covers, then which `subtitle` line's words
321//! it shows (by position, the first one is track 0) and the half-open window of
322//! that track it shows, in *microseconds*, which is the clock the cues
323//! themselves are timed in. Two clocks on one line because a subtitle has two:
324//! a placement is in timeline frames like everything else, and a window is in
325//! the file's own time whatever the timeline runs at. A lane holding nothing
326//! has the bare `sub <lane>` line for the reason a video one does, and the
327//! track a caption names has to be one the file declared -- a `sub` line naming
328//! track 3 of a two-track palette is refused here, as a clip naming a source
329//! that is not there is.
330//!
331//! **Version 23** was this without the `flags` lines: such a project has no
332//! lane hidden, muted or locked, which is what every lane of every dialect
333//! before it is.
334//! **Version 22** was this with a 32-bit packed look: such a project's clips
335//! chose no strand colour, which is what the top bit still clear means, and
336//! their value is the low half of the one v23 writes.
337//! **Version 19** was this without the clip's transform field: such a project
338//! places no clip anywhere but its fit policy's own spot, which is what `-`
339//! still means. **Version 18** was that without the clip's transition field:
340//! such a project dissolves no clip into its neighbor, which is what `0` still
341//! means. **Version 17** was this without the clip's two fade fields: such a project
342//! holds no clip anyone has faded, which is what a `0 0` pair still means.
343//! **Version 15** was this without the caption's group field: such a project
344//! holds captions no hand ever grouped, which is every caption there could be.
345//! **Version 14** was that without the `sub` lines: such a project holds no
346//! subtitle lane at all -- its `subtitle` lines are the palette, and where the
347//! words of it were shown was nowhere in the file.
348//! **Version 13** was that without the `encoder` line: such a project takes the
349//! hardware seat where there is one and the software encoder
350//! everywhere else, which is the only choice those projects had.
351//! **Version 12** was that without the `autoproxy` line: such a project makes a
352//! stand-in for every film that wants one the moment it arrives, which is all
353//! any project could do.
354//! **Version 11** was that without the `proxy` line: such a project is cut on
355//! its films themselves, which is all any project could do.
356//! **Version 10** was that without the `tonemap` line: such a project is shown
357//! in the reference rendition, which is the only one there was.
358//! **Version 9** was that without the `subtitle` lines: such a project shows no
359//! subtitles, which is all any project could do.
360//! **Version 8** was that without the `fps` and `limiter` lines and without
361//! the `gain` ones: such a project mixes every lane at unity, limits nothing,
362//! and comes back at the rate its scaffolding source runs at.
363//! **Version 7** was that without the clip's speed field -- every clip of such
364//! a project plays at real time, which is the only rate there was.
365//! **Version 6** was that without the `resolution` line and without the clip's
366//! fit field -- such a project is the size of its first source and letterboxes
367//! nothing, because nothing on it could differ in size. **Version 5** was that
368//! without the colour lines and without the clip's colour
369//! field. **Version 4** was that without the eq lines and without the clip's eq
370//! field. **Version 3** was that without the lane number, and held one video
371//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
372//! well, which is this file's stream 0 -- one per file, whichever audio track
373//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
374//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
375//! cumulatively and copied onto both lanes as one group each, which is exactly
376//! what a v1 timeline meant, and an older file simply equalizes and grades
377//! nothing, and an older one plays everything at real time, and an older one
378//! mixes flat, and an older one shows no subtitles, and an older one is shown
379//! in the reference rendition, and an older one places none of the words it
380//! names, and an older one has no lane hidden, muted or locked -- and saving
381//! any of them writes v24. An older
382//! reader refuses a newer file by name.
383//!
384//! Text because an edit list is a few integers and a path, and a path is
385//! *bytes* on this platform -- a JSON string would have to lossily decode one.
386//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
387//! everything a line-based format cannot carry) and survives round-trip
388//! exactly. Paths under the project file's own directory are written relative
389//! to it, so a folder holding the media and the `.edith` can be moved or
390//! copied anywhere and still open; anything else is absolute.
391//!
392//! The parser is strict and every refusal names its 1-based line: a project
393//! file is generated, so a line it did not generate is a corrupt file, not a
394//! dialect. Structure is checked here (fields, ordering, empty clips,
395//! out-of-range source indexes); whether the files on disk still match the
396//! timeline is [`crate::PlaybackSession::open_project`]'s business.
397//!
398//! Writing goes through `<path>.part` and a rename, as an export does, so an
399//! interrupted save cannot destroy the previous version of the project. The
400//! bytes are fsynced before the rename and the directory after it, so what a
401//! power loss can lose is a whole save, never half of one under the real name.
402
403use std::ffi::OsString;
404use std::io::Write;
405use std::os::unix::ffi::{OsStrExt, OsStringExt};
406use std::path::{Path, PathBuf};
407
408use crate::color::ColorParams;
409use crate::duck::{
410 Duck, MAX_ATTACK_MS, MAX_DEPTH_DB, MAX_RELEASE_MS, MAX_THRESHOLD_DB, MIN_DEPTH_DB,
411 MIN_THRESHOLD_DB, MIN_TIME_MS,
412};
413use crate::eq::{Band, BandKind, EqParams};
414use crate::limiter::Limiter;
415use crate::project::{
416 Chapter, Clip, Deinterlace, GainKey, Marker, MarkerColor, Lane, LaneFlags, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_KEYS,
417 MAX_SPEED_KEYS, MIN_CLIP_GAIN_DB, STILL_DEFAULT_SECS, STILL_MAX_SECS, STILL_MIN_SECS, Source, Speed, SpeedKey, SubClip,
418 Title, check_chapter, check_marker, check_title,
419};
420use crate::scale::FitPolicy;
421use crate::subtitle::SubtitleTrack;
422use crate::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};
423use crate::voice::{Compressor, DeEsser, Gate, NoiseReduction, VoiceFx};
424use crate::text::{Align, HPlace, Outline, Place, TextStyle, Weight};
425use crate::titleanim::TitleAnim;
426use crate::color::{ColorKey, MAX_COLOR_KEYS};
427use crate::transitions::TransitionKind;
428use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, TransformParams};
429
430/// The newest project format version: the `N` in the `edith N` first line that
431/// [`save`] writes for a project that uses the newest features. A reader refuses any
432/// higher version by name.
433pub const NEWEST_VERSION: u32 = 55;
434
435/// What [`save`] writes. Read support goes back to `edith 1`; see the module
436/// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`].
437const MAGIC: &[u8] = b"edith 55";
438const MAGIC_V54: &[u8] = b"edith 54";
439const MAGIC_V53: &[u8] = b"edith 53";
440const MAGIC_V52: &[u8] = b"edith 52";
441const MAGIC_V51: &[u8] = b"edith 51";
442const MAGIC_V50: &[u8] = b"edith 50";
443const MAGIC_V49: &[u8] = b"edith 49";
444const MAGIC_V48: &[u8] = b"edith 48";
445const MAGIC_V47: &[u8] = b"edith 47";
446const MAGIC_V46: &[u8] = b"edith 46";
447/// The most bands one equalizer line may declare. A hand-built cascade is a
448/// handful; the cap keeps a crafted line from making every clip run a million
449/// filters.
450const MAX_EQ_BANDS: usize = 64;
451/// The most words one `cuewords` line may carry (a cue is a line or two).
452const MAX_CUE_WORDS: usize = 1_000;
453/// The most sequences (tabs) a project may hold, each a parse of its own.
454const MAX_SEQUENCES: usize = 256;
455/// The most chapters, and the most markers, a project may hold.
456const MAX_LIST_ENTRIES: usize = 100_000;
457
458const MAGIC_V45: &[u8] = b"edith 45";
459const MAGIC_V44: &[u8] = b"edith 44";
460const MAGIC_V43: &[u8] = b"edith 43";
461const MAGIC_V42: &[u8] = b"edith 42";
462const MAGIC_V41: &[u8] = b"edith 41";
463const MAGIC_V40: &[u8] = b"edith 40";
464const MAGIC_V39: &[u8] = b"edith 39";
465const MAGIC_V38: &[u8] = b"edith 38";
466const MAGIC_V37: &[u8] = b"edith 37";
467const MAGIC_V36: &[u8] = b"edith 36";
468const MAGIC_V35: &[u8] = b"edith 35";
469const MAGIC_V34: &[u8] = b"edith 34";
470const MAGIC_V33: &[u8] = b"edith 33";
471const MAGIC_V32: &[u8] = b"edith 32";
472const MAGIC_V31: &[u8] = b"edith 31";
473const MAGIC_V30: &[u8] = b"edith 30";
474const MAGIC_V29: &[u8] = b"edith 29";
475const MAGIC_V28: &[u8] = b"edith 28";
476const MAGIC_V27: &[u8] = b"edith 27";
477const MAGIC_V26: &[u8] = b"edith 26";
478const MAGIC_V25: &[u8] = b"edith 25";
479const MAGIC_V24: &[u8] = b"edith 24";
480const MAGIC_V23: &[u8] = b"edith 23";
481const MAGIC_V22: &[u8] = b"edith 22";
482const MAGIC_V21: &[u8] = b"edith 21";
483const MAGIC_V20: &[u8] = b"edith 20";
484const MAGIC_V19: &[u8] = b"edith 19";
485const MAGIC_V18: &[u8] = b"edith 18";
486const MAGIC_V17: &[u8] = b"edith 17";
487const MAGIC_V16: &[u8] = b"edith 16";
488const MAGIC_V15: &[u8] = b"edith 15";
489const MAGIC_V14: &[u8] = b"edith 14";
490const MAGIC_V13: &[u8] = b"edith 13";
491const MAGIC_V12: &[u8] = b"edith 12";
492const MAGIC_V11: &[u8] = b"edith 11";
493const MAGIC_V10: &[u8] = b"edith 10";
494const MAGIC_V9: &[u8] = b"edith 9";
495const MAGIC_V8: &[u8] = b"edith 8";
496const MAGIC_V7: &[u8] = b"edith 7";
497const MAGIC_V6: &[u8] = b"edith 6";
498const MAGIC_V5: &[u8] = b"edith 5";
499const MAGIC_V4: &[u8] = b"edith 4";
500const MAGIC_V3: &[u8] = b"edith 3";
501const MAGIC_V2: &[u8] = b"edith 2";
502const MAGIC_V1: &[u8] = b"edith 1";
503
504/// What a project file says: an edit list plus where the playhead stood.
505/// Structurally valid by construction -- see [`parse`].
506#[derive(Debug)]
507pub struct Document {
508 /// Paths absolute, relative entries already joined to the file's own
509 /// directory.
510 pub sources: Vec<Source>,
511 /// Every lane, in display order, which is the order
512 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
513 /// `A1` -- for every dialect before v4.
514 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
515 /// What is placed on each lane, in the order `lanes` is in and as long as
516 /// it -- the `sub` lines. Empty for every video and audio lane, which hold
517 /// no [`SubClip`], and for every lane of every dialect before v15, which
518 /// placed no words anywhere ([`crate::Project::with_subs`] takes it back).
519 pub subs: Vec<Vec<SubClip>>,
520 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
521 /// every dialect before v5.
522 pub eq: Vec<EqParams>,
523 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
524 /// every dialect before v6.
525 pub color: Vec<ColorParams>,
526 /// The transform table [`Clip::transform`] indexes into, in file order.
527 /// Empty for every dialect before v20.
528 pub transform: Vec<TransformParams>,
529 /// The project's own picture size. `None` for every dialect before v7 and
530 /// for a v7 file that leaves it out, which both mean "source 0's picture".
531 pub resolution: Option<(u32, u32)>,
532 /// Every lane's own volume in dB, in the order `lanes` is in and as long as
533 /// it; `0.0` for a lane nobody has turned, which is every lane of every
534 /// dialect before v9.
535 pub gains: Vec<f32>,
536 /// Every lane's switches -- hidden, muted, locked -- in the order `lanes` is
537 /// in and as long as it. All clear for every dialect before v24, which had
538 /// no such switches, and for a lane a `flags` line does not name.
539 pub flags: Vec<LaneFlags>,
540 /// Every lane's auto-ducks, in the order `lanes` is in and as long as it;
541 /// empty for every lane but an audio lane somebody has ducked. Each lane
542 /// has at most one duck per key. Empty of every list for every dialect
543 /// before v25, which had no ducks, and at most one per lane before v30.
544 pub ducks: Vec<Vec<Duck>>,
545 /// The title cards and text overlays, in the order the file has them.
546 /// Empty for every dialect before v26, which had none.
547 pub titles: Vec<Title>,
548 /// The chapter markers, in frame order. Empty for every dialect before v34.
549 pub chapters: Vec<Chapter>,
550 /// The comment markers, in frame order. Empty for every dialect before v36.
551 pub markers: Vec<Marker>,
552 /// How burned captions animate, the `capstyle` line. The default (static cues) for every
553 /// dialect before v40.
554 pub caption_style: CaptionStyle,
555 /// Every lane's voice processors, in the order `lanes` is in and as long as it.
556 /// All off for every dialect before v41, and for a lane no `voice` line names.
557 pub voices: Vec<VoiceFx>,
558 /// One display name per lane (empty for none), from the `lanename` lines (v46).
559 pub names: Vec<String>,
560 /// The master limiter. Off for every dialect before v9, and for a v9 file
561 /// that leaves the line out.
562 pub limiter: Limiter,
563 /// The subtitle tracks, as the file names them: the path the cues are in
564 /// and which track of it, which is what [`crate::subtitle::open`] takes.
565 /// Reading them is the loader's business, not this module's -- a `.edith`
566 /// holds no cues. Empty for every dialect before v10.
567 pub subtitles: Vec<(PathBuf, Option<u64>)>,
568 /// The language of a subtitle track, `(track, code)`: the track by its
569 /// position in `subtitles`, the code as the file holds it (ISO 639-2 for
570 /// one set by a person, a container's own tag for an embedded track that
571 /// was not retyped). Empty for every dialect before v33.
572 pub sub_langs: Vec<(usize, String)>,
573 /// The cue overrides, `(track, cue, text)`: the track by its position in
574 /// `subtitles`, the cue by its position in that track. Empty for every
575 /// dialect before v24.
576 pub cue_edits: Vec<(usize, usize, String)>,
577 /// The cues added to a track ([`crate::project::AddedCue`]), each on its
578 /// track's own clock. Empty for every dialect before v29.
579 pub cue_adds: Vec<crate::project::AddedCue>,
580 /// The word times of cues, `(track, cue, words)` with the cue by its position in the track
581 /// as it stands after the edits and additions: the `cuewords` lines (v40). Empty before v40.
582 pub cue_words: Vec<crate::project::CueWordRow>,
583 /// The timeline's frame rate. `None` for every dialect before v9 and for a
584 /// v9 file that leaves it out, which both mean "whatever the scaffolding
585 /// source runs at" -- the inference a project of nothing but stills and
586 /// songs has no answer for (see
587 /// [`crate::PlaybackSession::open_project`]).
588 pub fps: Option<f64>,
589 /// The HDR-to-SDR rendition every clip on an HDR curve is shown in.
590 /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and
591 /// for a v11 file that leaves the line out, which both mean the published
592 /// conversion -- the only one those projects had.
593 pub tone: crate::tonemap::Preset,
594 /// Whether the films are cut on their stand-ins ([`crate::proxy`]). `false`
595 /// for every dialect before v12 and for a v12 file that leaves the line
596 /// out, which both mean the films themselves -- the only thing those
597 /// projects could do.
598 pub proxy: bool,
599 /// Whether an import makes a stand-in for a film that wants one by itself
600 /// ([`crate::proxy`]). `true` for every dialect before v13 and for a v13
601 /// file that leaves the line out, which both mean by itself -- the only
602 /// thing those projects did.
603 pub auto_proxy: bool,
604 /// Which encoder an export writes the picture with
605 /// ([`crate::export::EncoderSeat`]). `Auto` for every dialect before v14 and
606 /// for a v14 file that leaves the line out, which both mean the seat this
607 /// machine has -- the only choice those projects offered.
608 pub encoder: crate::export::EncoderSeat,
609 /// The rate the project's *sound* is mixed and exported at, chosen rather
610 /// than probed. `None` for every dialect before v17 and for a v17 file that
611 /// leaves the line out, which both mean what they always did: the rate of
612 /// the sources' own: the highest rate among the sources that have sound,
613 /// or 48 kHz when every one of them is below 44.1 kHz. Playback and export
614 /// both resample every other source
615 /// to whichever rate this resolves to, exactly as they already resample a
616 /// source shot at another rate than the timeline's -- an explicit choice
617 /// here only changes what that timeline's own rate *is*.
618 pub sample_rate: Option<u32>,
619 pub playhead: u32,
620 /// The active sequence's id and name, from the `seqactive` line (v45). `None` for a file
621 /// that holds one sequence, which is every dialect before v45.
622 pub seq_active: Option<(u32, String)>,
623 /// The tab order, from the `seqorder` line.
624 pub seq_order: Vec<u32>,
625 /// The other sequences, each a complete document of its own (`seq` ... `endseq`).
626 pub sequences: Vec<SeqDoc>,
627 /// The `mcam` lines (v47): a multicam source sequence's id and one angle's name each, in
628 /// angle order. Empty for a file with no multicam clip.
629 pub mcams: Vec<(u32, String)>,
630 /// The library's bins, from the `bin` lines (v51). Empty for a file with none.
631 pub bins: Vec<crate::project::Bin>,
632 /// The project notes, from the `notes` line (v52). Empty for a file with none, and for
633 /// every dialect before v52.
634 pub notes: String,
635 /// The length a still is placed at, from the `still` line (v52). `None` for a file that
636 /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s.
637 pub still_secs: Option<f64>,
638}
639
640/// A parked sequence read off a v45 file.
641#[derive(Debug)]
642pub struct SeqDoc {
643 pub id: u32,
644 pub name: String,
645 pub doc: Document,
646}
647
648/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
649/// already be orphan-free ([`crate::Project::without_orphan_sources`]);
650/// `gains` is one dB per lane in the same order the lanes are in
651/// ([`crate::Project::lane_gains`]) and `subs` is one list of placements per
652/// lane in that same order ([`crate::Project::lane_subs`]).
653///
654/// The same as [`save_flagged`] with every lane's switches clear, for the
655/// callers that have none to write.
656#[allow(clippy::too_many_arguments)]
657pub fn save(
658 path: &Path,
659 sources: &[Source],
660 lanes: &[(LaneKind, Vec<Clip>)],
661 gains: &[f32],
662 subs: &[Vec<SubClip>],
663 subtitles: &[SubtitleTrack],
664 eq: &[EqParams],
665 color: &[ColorParams],
666 transform: &[TransformParams],
667 resolution: (u32, u32),
668 fps: Option<f64>,
669 tone: crate::tonemap::Preset,
670 proxy: bool,
671 auto_proxy: bool,
672 encoder: crate::export::EncoderSeat,
673 limiter: Limiter,
674 sample_rate: Option<u32>,
675 playhead: u32,
676) -> crate::Result<()> {
677 save_flagged(
678 path,
679 sources,
680 lanes,
681 gains,
682 subs,
683 subtitles,
684 eq,
685 color,
686 transform,
687 resolution,
688 fps,
689 tone,
690 proxy,
691 auto_proxy,
692 encoder,
693 limiter,
694 sample_rate,
695 playhead,
696 &[],
697 &[],
698 &[],
699 &[],
700 &[],
701 &[],
702 &[],
703 &CaptionStyle::default(),
704 &[],
705 &[],
706 )
707}
708
709/// The bytes [`save_flagged`] writes, for a caller that assembles a file of several parts
710/// ([`sequenced`]). `dir` is the project's directory, which relative paths are written against.
711#[allow(clippy::too_many_arguments)]
712pub fn encode_flagged(
713 dir: &Path,
714 sources: &[Source],
715 lanes: &[(LaneKind, Vec<Clip>)],
716 gains: &[f32],
717 subs: &[Vec<SubClip>],
718 subtitles: &[SubtitleTrack],
719 eq: &[EqParams],
720 color: &[ColorParams],
721 transform: &[TransformParams],
722 resolution: (u32, u32),
723 fps: Option<f64>,
724 tone: crate::tonemap::Preset,
725 proxy: bool,
726 auto_proxy: bool,
727 encoder: crate::export::EncoderSeat,
728 limiter: Limiter,
729 sample_rate: Option<u32>,
730 playhead: u32,
731 flags: &[LaneFlags],
732 ducks: &[Vec<Duck>],
733 cue_edits: &[(usize, usize, String)],
734 cue_adds: &[crate::project::AddedCue],
735 titles: &[Title],
736 chapters: &[Chapter],
737 markers: &[Marker],
738 caption_style: &CaptionStyle,
739 voices: &[VoiceFx],
740 names: &[String],
741) -> Vec<u8> {
742 let mut bytes = emit(
743 dir,
744 sources,
745 lanes,
746 gains,
747 subs,
748 subtitles,
749 eq,
750 color,
751 transform,
752 resolution,
753 fps,
754 tone,
755 proxy,
756 auto_proxy,
757 encoder,
758 limiter,
759 sample_rate,
760 playhead,
761 );
762 // The cue overrides after the subtitle lines `emit` wrote, which
763 // they name; then the switches, which name lanes, as the gains do.
764 bytes.extend_from_slice(&cue_lines(cue_edits));
765 bytes.extend_from_slice(&cue_add_lines(cue_adds));
766 let cue_words = cue_word_lines(subtitles);
767 bytes.extend_from_slice(&flag_lines(lanes, flags));
768 bytes.extend_from_slice(&duck_lines(lanes, ducks));
769 bytes.extend_from_slice(&title_lines(titles));
770 // The chapters after the titles, and a file that has any is v34 whatever
771 // `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
772 // the one line `emit` wrote that these change, so it is swapped here,
773 // where the lines they need are.
774 let ramped = lanes
775 .iter()
776 .any(|(_, clips)| clips.iter().any(|c| !c.speed_keys.is_empty()));
777 let transitioned = lanes.iter().any(|(_, clips)| {
778 clips.iter().any(|c| c.transition_kind != TransitionKind::Dissolve)
779 });
780 let reversed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.reversed));
781 // ...and one with an opacity or colour animation, or a key easing beyond
782 // linear and `ease`, is v39.
783 let animated = lanes.iter().any(|(_, clips)| clips.iter().any(needs_v39));
784 // ...and one with a project caption style or cue word times is v40.
785 let captioned = *caption_style != CaptionStyle::default() || !cue_words.is_empty();
786 // ...and one with a lane's voice processor is v41.
787 let voiced = voices.iter().any(|v| !v.is_default());
788 // ...and one with a clip's effect is v42.
789 let effected = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.effects.is_empty()));
790 // ...and one with a grade's wheels, curves or LUT is v43.
791 let looked = color.iter().any(|p| p.look != crate::color::Look::default());
792 // ...and one with a stabilised clip is v44.
793 let steadied = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.stabilise.is_some()));
794 // ...and one with a named lane or a clip's deinterlace choice is v46.
795 let named = names.iter().any(|n| !n.is_empty());
796 let deinterlaced = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.deinterlace != Deinterlace::Frame));
797 // ...and one with a multicam clip's angle is v47.
798 let angled = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.angle.is_default()));
799 // ...and one with a generated source (a solid, a gradient, a countdown, bars, an adjustment
800 // layer), a clip's colour label or a switched-off clip is v48.
801 // ...and one with a title's colour, weight, alignment, position or box colour is v49.
802 let styled = titles.iter().any(|t| !title_look_is_default(&t.style));
803 // ...and one with a title's entrance or exit animation is v54.
804 let titled = titles.iter().any(|t| t.in_anim != TitleAnim::None || t.out_anim != TitleAnim::None);
805 let marked = sources.iter().any(|s| crate::generate::is_generated(&s.path))
806 || lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.mark.is_default()));
807 // ...and one with a clip pan or a lane pan is v50.
808 let panned = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pan != 0)) || flags.iter().any(|f| f.pan != 0.0);
809 // ...and one with a mask's keys is v53.
810 let masked = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty())));
811 // ...and one with a clip's pitch shift is v55.
812 let pitched = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch != 0));
813 if pitched || titled || masked || panned || styled || marked || angled || named || deinterlaced || steadied || looked || effected || voiced || captioned || animated || reversed || transitioned || ramped || !chapters.is_empty() || !markers.is_empty() {
814 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
815 let header = if pitched {
816 MAGIC
817 } else if titled {
818 MAGIC_V54
819 } else if masked {
820 MAGIC_V53
821 } else if panned {
822 MAGIC_V50
823 } else if styled {
824 MAGIC_V49
825 } else if marked {
826 MAGIC_V48
827 } else if angled {
828 MAGIC_V47
829 } else if named || deinterlaced {
830 MAGIC_V46
831 } else if steadied {
832 MAGIC_V44
833 } else if looked {
834 MAGIC_V43
835 } else if effected {
836 MAGIC_V42
837 } else if voiced {
838 MAGIC_V41
839 } else if captioned {
840 MAGIC_V40
841 } else if animated {
842 MAGIC_V39
843 } else if reversed {
844 MAGIC_V38
845 } else if transitioned {
846 MAGIC_V37
847 } else if !markers.is_empty() {
848 MAGIC_V36
849 } else if ramped {
850 MAGIC_V35
851 } else {
852 MAGIC_V34
853 };
854 bytes.splice(..first_end, header.iter().copied());
855 }
856 bytes.extend_from_slice(&chapter_lines(chapters));
857 bytes.extend_from_slice(&marker_lines(markers));
858 bytes.extend_from_slice(&capstyle_line(caption_style));
859 bytes.extend_from_slice(&cue_words);
860 bytes.extend_from_slice(&voice_lines(lanes, voices));
861 bytes.extend_from_slice(&clip_gain_lines(lanes));
862 bytes.extend_from_slice(&gain_key_lines(lanes));
863 bytes.extend_from_slice(&tkey_lines(lanes));
864 bytes.extend_from_slice(&speed_key_lines(lanes));
865 bytes.extend_from_slice(&transition_lines(lanes));
866 bytes.extend_from_slice(&reverse_lines(lanes));
867 bytes.extend_from_slice(&opacity_key_lines(lanes));
868 bytes.extend_from_slice(&color_key_lines(lanes));
869 bytes.extend_from_slice(&effect_lines(lanes));
870 bytes.extend_from_slice(&mask_key_lines(lanes));
871 bytes.extend_from_slice(&look_lines(color, dir));
872 bytes.extend_from_slice(&stab_lines(lanes));
873 bytes.extend_from_slice(&deint_lines(lanes));
874 bytes.extend_from_slice(&lane_name_lines(lanes, names));
875 bytes.extend_from_slice(&angle_lines(lanes));
876 bytes.extend_from_slice(&mark_lines(lanes));
877 bytes.extend_from_slice(&pan_lines(lanes, flags));
878 bytes.extend_from_slice(&pitch_lines(lanes));
879 bytes
880}
881
882/// `main` (a document as [`encode_flagged`] wrote it) with the library's lines after it (v51):
883/// `bin <id> <parent> <name>` for each bin, `srcbin <source> <bin>` for each filed source and
884/// `srcfav <source>` for each starred one. A library with none of these is `main` untouched, so
885/// such a project is the bytes it was before v51.
886/// `current` (a file's first line, without its newline) with `candidate` in its place when
887/// `candidate` is a newer dialect, else `current` untouched. The library and notes lines raise
888/// the header to what they need and never lower it, so a file with mask keys (v53) keeps v53.
889fn raise_header(current: &[u8], candidate: &[u8]) -> Vec<u8> {
890 let version = |h: &[u8]| {
891 std::str::from_utf8(h).ok().and_then(|l| l.strip_prefix("edith ")).and_then(|n| n.parse::<u32>().ok()).unwrap_or(0)
892 };
893 if version(candidate) > version(current) { candidate.to_vec() } else { current.to_vec() }
894}
895
896pub fn binned(mut main: Vec<u8>, sources: &[Source], bins: &[crate::project::Bin]) -> Vec<u8> {
897 let mut lines = Vec::new();
898 for b in bins {
899 lines.extend_from_slice(format!("bin {} {} ", b.id, b.parent).as_bytes());
900 escape_text(&b.name, &mut lines);
901 lines.push(b'\n');
902 }
903 for (i, s) in sources.iter().enumerate() {
904 if s.bin != 0 {
905 lines.extend_from_slice(format!("srcbin {i} {}\n", s.bin).as_bytes());
906 }
907 if s.fav {
908 lines.extend_from_slice(format!("srcfav {i}\n").as_bytes());
909 }
910 }
911 if lines.is_empty() {
912 return main;
913 }
914 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
915 let header = raise_header(&main[..first_end], MAGIC_V51);
916 main.splice(..first_end, header);
917 if main.last() != Some(&b'\n') {
918 main.push(b'\n');
919 }
920 main.extend_from_slice(&lines);
921 main
922}
923
924/// `main` with the project notes and the still length after it (v52): a `notes` line when there
925/// are notes, a `still` line when the length is not the default. A project with neither is `main`
926/// untouched, so it keeps the bytes it had before v52.
927pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64) -> Vec<u8> {
928 let mut lines = Vec::new();
929 if !notes.is_empty() {
930 lines.extend_from_slice(b"notes ");
931 escape_text(notes, &mut lines);
932 lines.push(b'\n');
933 }
934 if still_secs != STILL_DEFAULT_SECS {
935 lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes());
936 }
937 if lines.is_empty() {
938 return main;
939 }
940 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
941 let header = raise_header(&main[..first_end], MAGIC_V52);
942 main.splice(..first_end, header);
943 if main.last() != Some(&b'\n') {
944 main.push(b'\n');
945 }
946 main.extend_from_slice(&lines);
947 main
948}
949
950/// [`save`], with each lane's switches -- `flags` is one entry per lane in the
951/// same order as `lanes`, as `gains` is ([`crate::Project::lane_flags`]).
952#[allow(clippy::too_many_arguments)]
953pub fn save_flagged(
954 path: &Path,
955 sources: &[Source],
956 lanes: &[(LaneKind, Vec<Clip>)],
957 gains: &[f32],
958 subs: &[Vec<SubClip>],
959 subtitles: &[SubtitleTrack],
960 eq: &[EqParams],
961 color: &[ColorParams],
962 transform: &[TransformParams],
963 resolution: (u32, u32),
964 fps: Option<f64>,
965 tone: crate::tonemap::Preset,
966 proxy: bool,
967 auto_proxy: bool,
968 encoder: crate::export::EncoderSeat,
969 limiter: Limiter,
970 sample_rate: Option<u32>,
971 playhead: u32,
972 flags: &[LaneFlags],
973 ducks: &[Vec<Duck>],
974 cue_edits: &[(usize, usize, String)],
975 cue_adds: &[crate::project::AddedCue],
976 titles: &[Title],
977 chapters: &[Chapter],
978 markers: &[Marker],
979 caption_style: &CaptionStyle,
980 voices: &[VoiceFx],
981 names: &[String],
982) -> crate::Result<()> {
983 let dir = project_dir(path);
984 let bytes = encode_flagged(
985 &dir,
986 sources,
987 lanes,
988 gains,
989 subs,
990 subtitles,
991 eq,
992 color,
993 transform,
994 resolution,
995 fps,
996 tone,
997 proxy,
998 auto_proxy,
999 encoder,
1000 limiter,
1001 sample_rate,
1002 playhead,
1003 flags,
1004 ducks,
1005 cue_edits,
1006 cue_adds,
1007 titles,
1008 chapters,
1009 markers,
1010 caption_style,
1011 voices,
1012 names,
1013 );
1014 write_atomic(path, &bytes)
1015}
1016
1017/// One parked sequence as a file holds it: a whole standalone document of its own.
1018pub struct SeqBlock {
1019 pub id: u32,
1020 pub name: String,
1021 pub bytes: Vec<u8>,
1022}
1023
1024/// `main` (the active sequence, as [`encode_flagged`] wrote it) with the other sequences after
1025/// it, as a v45 file: the `seqactive` and `seqorder` lines, then each parked sequence between
1026/// `seq <id> <name>` and `endseq`. The body of each block is a complete document, so its lines
1027/// read exactly as a project file's do.
1028pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[SeqBlock], mcam: &[(u32, Vec<String>)]) -> Vec<u8> {
1029 let mut bytes = main;
1030 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
1031 // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46
1032 // when a part is v46; a newer-only line under an older header is refused.
1033 let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n');
1034 let v55 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1035 let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54));
1036 let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53));
1037 let v52 = v53 || is(&bytes, MAGIC_V52) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V52));
1038 let v51 = v52 || is(&bytes, MAGIC_V51) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V51));
1039 let v50 = v51 || is(&bytes, MAGIC_V50) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V50));
1040 let v49 = v50 || is(&bytes, MAGIC_V49) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V49));
1041 let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48));
1042 let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47));
1043 let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46));
1044 let header = if v55 { MAGIC } 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 };
1045 bytes.splice(..first_end, header.iter().copied());
1046 bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes());
1047 escape_text(active.1, &mut bytes);
1048 bytes.push(b'\n');
1049 let ids: Vec<String> = order.iter().map(u32::to_string).collect();
1050 bytes.extend_from_slice(format!("seqorder {}\n", ids.join(" ")).as_bytes());
1051 for (id, names) in mcam {
1052 for name in names {
1053 bytes.extend_from_slice(format!("mcam {id} ").as_bytes());
1054 escape_text(name, &mut bytes);
1055 bytes.push(b'\n');
1056 }
1057 }
1058 for b in blocks {
1059 bytes.extend_from_slice(format!("seq {} ", b.id).as_bytes());
1060 escape_text(&b.name, &mut bytes);
1061 bytes.push(b'\n');
1062 bytes.extend_from_slice(&b.bytes);
1063 if bytes.last() != Some(&b'\n') {
1064 bytes.push(b'\n');
1065 }
1066 bytes.extend_from_slice(b"endseq\n");
1067 }
1068 bytes
1069}
1070
1071/// Writes `bytes` to `path` atomically: a `.part` file beside it, synced, renamed over it, and the
1072/// directory synced, so until the rename the old file is still the whole truth.
1073pub fn write_atomic(path: &Path, bytes: &[u8]) -> crate::Result<()> {
1074 let dir = project_dir(path);
1075 let mut part = path.to_path_buf().into_os_string();
1076 part.push(".part");
1077 let part = PathBuf::from(part);
1078 let result = std::fs::File::create(&part)
1079 .and_then(|mut f| {
1080 f.write_all(bytes)?;
1081 f.sync_all()
1082 })
1083 .and_then(|()| std::fs::rename(&part, path))
1084 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
1085 if result.is_err() {
1086 let _ = std::fs::remove_file(&part);
1087 }
1088 result.map_err(Into::into)
1089}
1090
1091pub fn load(path: &Path) -> crate::Result<Document> {
1092 let data = std::fs::read(path)?;
1093 // Relative lines are joined to the directory the project was opened
1094 // through, so the file is reached the way the project was opened; the
1095 // save side compares canonically (`written_path`), so whichever way it
1096 // was opened, a saved source is written relative.
1097 parse(&data, path.parent().unwrap_or(Path::new("")))
1098}
1099
1100/// The form a source or subtitle path is written in: relative to the project's
1101/// directory when the file is inside it, however the path was spelled -- a
1102/// `..` or a symlink on the way in is resolved before the comparison -- and as
1103/// it is otherwise. This is the one rule every save follows.
1104fn written_path(path: &Path, dir: &Path) -> PathBuf {
1105 if let Ok(rel) = path.strip_prefix(dir) {
1106 return rel.to_path_buf();
1107 }
1108 if let Ok(real) = path.canonicalize()
1109 && let Ok(rel) = real.strip_prefix(dir)
1110 {
1111 return rel.to_path_buf();
1112 }
1113 path.to_path_buf()
1114}
1115
1116/// The directory a project file's relative source lines are measured from, in
1117/// the same canonical form [`crate::Project`] keeps its sources in -- without
1118/// that the prefix simply never matches and every line comes out absolute,
1119/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
1120/// a bare filename is `""`). Canonicalizing fails only if the directory does
1121/// not exist, and then the write is about to fail anyway.
1122pub(crate) fn project_dir(path: &Path) -> PathBuf {
1123 let dir = path
1124 .parent()
1125 .filter(|p| !p.as_os_str().is_empty())
1126 .unwrap_or(Path::new("."));
1127 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
1128}
1129
1130/// The `cue` lines: one per retyped cue, after the `subtitle` lines that name
1131/// their tracks. Only a cue somebody has retyped has one, so an unedited project
1132/// is the bytes it was.
1133fn cue_lines(edits: &[(usize, usize, String)]) -> Vec<u8> {
1134 let mut out = Vec::new();
1135 for (track, cue, text) in edits {
1136 out.extend_from_slice(format!("cue {track} {cue} ").as_bytes());
1137 escape_text(text, &mut out);
1138 out.push(b'\n');
1139 }
1140 out
1141}
1142
1143/// The `cuewords` lines (v40): `cuewords <track> <cue> <start_us> <end_us> <word> ...` for each
1144/// cue that has word times, the cue by its position in the track as it stands when saved. The
1145/// times are on the track's own clock; a word has no whitespace, so a space separates fields.
1146fn cue_word_lines(subtitles: &[SubtitleTrack]) -> Vec<u8> {
1147 let mut out = Vec::new();
1148 for (t, track) in subtitles.iter().enumerate() {
1149 for (c, cue) in track.cues.iter().enumerate().filter(|(_, c)| !c.words.is_empty()) {
1150 out.extend_from_slice(format!("cuewords {t} {c}").as_bytes());
1151 for (start, end, word) in &cue.words {
1152 out.extend_from_slice(format!(" {start} {end} ").as_bytes());
1153 escape_text(word, &mut out);
1154 }
1155 out.push(b'\n');
1156 }
1157 }
1158 out
1159}
1160
1161/// The `cueadd` lines: one per cue added to a track, after the `cue` lines, as
1162/// `cueadd <track> <start_us> <end_us> <text>`, the text escaped as a `cue` line's is.
1163fn cue_add_lines(adds: &[crate::project::AddedCue]) -> Vec<u8> {
1164 let mut out = Vec::new();
1165 for a in adds {
1166 out.extend_from_slice(format!("cueadd {} {} {} ", a.track, a.start_us, a.end_us).as_bytes());
1167 escape_text(&a.text, &mut out);
1168 out.push(b'\n');
1169 }
1170 out
1171}
1172
1173/// The `duck` lines: one per duck, in lane order and then in the order the lane
1174/// holds them, the key named as the lanes are (1-based), so a project with none
1175/// is the bytes a v24 one was bar the version line.
1176fn duck_lines(lanes: &[(LaneKind, Vec<Clip>)], ducks: &[Vec<Duck>]) -> Vec<u8> {
1177 let mut out = Vec::new();
1178 let mut audio = 0u32;
1179 for ((kind, _), lane_ducks) in lanes.iter().zip(ducks) {
1180 if *kind != LaneKind::Audio {
1181 continue;
1182 }
1183 audio += 1;
1184 for d in lane_ducks {
1185 out.extend_from_slice(
1186 format!(
1187 "duck audio {audio} {} {:?} {:?} {:?} {:?}\n",
1188 d.under + 1,
1189 d.depth_db,
1190 d.threshold_db,
1191 d.attack_ms,
1192 d.release_ms
1193 )
1194 .as_bytes(),
1195 );
1196 }
1197 }
1198 out
1199}
1200
1201/// The `voice` lines: `voice audio <ord> <processor> <fields>...`, one per processor of an
1202/// audio lane that is not at its default (so a lane nobody has cleaned writes none, and a
1203/// project with none is the bytes a v36 one was bar the version line). The processors:
1204/// `gate <on> <threshold> <attack> <release> <hold> <range>`, `nr <on> <strength> <floor>
1205/// <profile>` (the profile a comma-separated list of dB, or `-`), `comp <on> <threshold>
1206/// <ratio> <attack> <release> <knee> <makeup> <auto>` and `deess <on> <threshold> <amount>
1207/// <lo> <hi>`; `<on>` and `<auto>` are `0` or `1`.
1208fn voice_lines(lanes: &[(LaneKind, Vec<Clip>)], voices: &[VoiceFx]) -> Vec<u8> {
1209 let mut out = String::new();
1210 let mut audio = 0u32;
1211 for ((kind, _), v) in lanes.iter().zip(voices) {
1212 if *kind != LaneKind::Audio {
1213 continue;
1214 }
1215 audio += 1;
1216 let b = |x: bool| u8::from(x);
1217 if v.gate != Gate::DEFAULT {
1218 let g = &v.gate;
1219 out += &format!(
1220 "voice audio {audio} gate {} {:?} {:?} {:?} {:?} {:?}\n",
1221 b(g.on), g.threshold_db, g.attack_ms, g.release_ms, g.hold_ms, g.range_db
1222 );
1223 }
1224 if v.nr != NoiseReduction::default() {
1225 let n = &v.nr;
1226 let profile = if n.profile.is_empty() {
1227 "-".to_string()
1228 } else {
1229 n.profile.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>().join(",")
1230 };
1231 out += &format!("voice audio {audio} nr {} {:?} {:?} {profile}\n", b(n.on), n.strength, n.floor_db);
1232 }
1233 if v.comp != Compressor::DEFAULT {
1234 let c = &v.comp;
1235 out += &format!(
1236 "voice audio {audio} comp {} {:?} {:?} {:?} {:?} {:?} {:?} {}\n",
1237 b(c.on), c.threshold_db, c.ratio, c.attack_ms, c.release_ms, c.knee_db, c.makeup_db, b(c.auto_makeup)
1238 );
1239 }
1240 if v.deess != DeEsser::DEFAULT {
1241 let d = &v.deess;
1242 out += &format!(
1243 "voice audio {audio} deess {} {:?} {:?} {:?} {:?}\n",
1244 b(d.on), d.threshold_db, d.amount, d.lo_hz, d.hi_hz
1245 );
1246 }
1247 }
1248 out.into_bytes()
1249}
1250
1251/// The pan lines (v50): `clippan audio <ord> <index> <pan>` for each audio clip that is not in the
1252/// middle, and `lanepan audio <ord> <pan>` for each audio lane that is not.
1253fn pan_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1254 let mut out = Vec::new();
1255 let mut audio = 0u32;
1256 for (n, (kind, clips)) in lanes.iter().enumerate() {
1257 if *kind != LaneKind::Audio {
1258 continue;
1259 }
1260 audio += 1;
1261 if let Some(f) = flags.get(n).filter(|f| f.pan != 0.0) {
1262 out.extend_from_slice(format!("lanepan audio {audio} {}\n", f.pan).as_bytes());
1263 }
1264 for (idx, c) in clips.iter().enumerate() {
1265 if c.pan != 0 {
1266 out.extend_from_slice(format!("clippan audio {audio} {idx} {}\n", c.pan_value()).as_bytes());
1267 }
1268 }
1269 }
1270 out
1271}
1272
1273/// The pitch lines (v55): `pitch audio <ord> <index> <semitones>` for each audio clip whose
1274/// pitch shift is not `0`.
1275fn pitch_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1276 let mut out = Vec::new();
1277 let mut audio = 0u32;
1278 for (kind, clips) in lanes {
1279 if *kind != LaneKind::Audio {
1280 continue;
1281 }
1282 audio += 1;
1283 for (idx, c) in clips.iter().enumerate() {
1284 if c.pitch != 0 {
1285 out.extend_from_slice(format!("pitch audio {audio} {idx} {}\n", c.pitch).as_bytes());
1286 }
1287 }
1288 }
1289 out
1290}
1291
1292/// The `clipgain` lines: one per clip whose own gain is not unity, as
1293/// `clipgain <kind> <ord> <index> <db>`. `index` counts the lane's clips from
1294/// `0`, in lane order. Written after the lanes they name, and only for a clip
1295/// somebody has turned, so a project with none is the bytes a v26 one was bar
1296/// the version line.
1297fn clip_gain_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1298 let mut out = Vec::new();
1299 let (mut video, mut audio) = (0u32, 0u32);
1300 for (kind, clips) in lanes {
1301 let (keyword, ord) = match kind {
1302 LaneKind::Video => {
1303 video += 1;
1304 ("video", video)
1305 }
1306 LaneKind::Audio => {
1307 audio += 1;
1308 ("audio", audio)
1309 }
1310 LaneKind::Subtitle => continue,
1311 };
1312 for (idx, c) in clips.iter().enumerate() {
1313 if c.gain_db != 0.0 {
1314 out.extend_from_slice(
1315 format!("clipgain {keyword} {ord} {idx} {}\n", c.gain_db).as_bytes(),
1316 );
1317 }
1318 }
1319 }
1320 out
1321}
1322
1323/// The `gainkeys` lines: one per clip with a volume envelope, as
1324/// `gainkeys <kind> <ord> <index> <at>:<db> ...`, the points in source order.
1325/// `kind` and `ord` name the lane the way [`clip_gain_lines`] does; `index`
1326/// counts the lane's clips from `0`. Written after the lanes they name, and
1327/// only for a clip with points, so a project with none is the bytes a v27 one
1328/// was bar the version line.
1329fn gain_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1330 let mut out = Vec::new();
1331 let (mut video, mut audio) = (0u32, 0u32);
1332 for (kind, clips) in lanes {
1333 let (keyword, ord) = match kind {
1334 LaneKind::Video => {
1335 video += 1;
1336 ("video", video)
1337 }
1338 LaneKind::Audio => {
1339 audio += 1;
1340 ("audio", audio)
1341 }
1342 LaneKind::Subtitle => continue,
1343 };
1344 for (idx, c) in clips.iter().enumerate() {
1345 if c.gain_keys.is_empty() {
1346 continue;
1347 }
1348 let points: String = c
1349 .gain_keys
1350 .iter()
1351 .map(|k| match k.ease {
1352 KeyEase::Linear => format!(" {}:{}", k.at, k.db),
1353 ease => format!(" {}:{}:{}", k.at, k.db, ease.token()),
1354 })
1355 .collect();
1356 out.extend_from_slice(format!("gainkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1357 }
1358 }
1359 out
1360}
1361
1362/// The `tkeys` lines: one per clip with a placement animation, as
1363/// `speedkeys <kind> <ord> <index> <at>:<permille> ...`, the keys in frame order. The
1364/// speeds are thousandths, as a clip's own `speed` field is, so they read back exactly.
1365/// Only a clip with keys gets a line, and such a project is a v35 one.
1366fn speed_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1367 let mut out = Vec::new();
1368 let (mut video, mut audio) = (0u32, 0u32);
1369 for (kind, clips) in lanes {
1370 let (keyword, ord) = match kind {
1371 LaneKind::Video => {
1372 video += 1;
1373 ("video", video)
1374 }
1375 LaneKind::Audio => {
1376 audio += 1;
1377 ("audio", audio)
1378 }
1379 LaneKind::Subtitle => continue,
1380 };
1381 for (idx, c) in clips.iter().enumerate() {
1382 if c.speed_keys.is_empty() {
1383 continue;
1384 }
1385 let points: String = c
1386 .speed_keys
1387 .iter()
1388 .map(|k| format!(" {}:{}", k.at, k.speed.permille()))
1389 .collect();
1390 out.extend_from_slice(format!("speedkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1391 }
1392 }
1393 out
1394}
1395
1396/// The `transition` lines: one per clip whose transition is not a dissolve, as
1397/// `transition <kind> <ord> <index> <name>`. Such a project is a v37 one.
1398fn transition_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1399 let mut out = Vec::new();
1400 let (mut video, mut audio) = (0u32, 0u32);
1401 for (kind, clips) in lanes {
1402 let (keyword, ord) = match kind {
1403 LaneKind::Video => {
1404 video += 1;
1405 ("video", video)
1406 }
1407 LaneKind::Audio => {
1408 audio += 1;
1409 ("audio", audio)
1410 }
1411 LaneKind::Subtitle => continue,
1412 };
1413 for (idx, c) in clips.iter().enumerate() {
1414 if c.transition_kind != TransitionKind::Dissolve {
1415 out.extend_from_slice(
1416 format!("transition {keyword} {ord} {idx} {}\n", c.transition_kind.name()).as_bytes(),
1417 );
1418 }
1419 }
1420 }
1421 out
1422}
1423
1424/// Whether a clip needs the v39 dialect: an opacity or colour animation, or a
1425/// key easing that v35 has no word for (`in`, `out`, `hold` on a placement key,
1426/// anything but linear on a volume point).
1427fn needs_v39(c: &Clip) -> bool {
1428 !c.opacity_keys.is_empty()
1429 || !c.color_keys.is_empty()
1430 || c.gain_keys.iter().any(|k| k.ease != KeyEase::Linear)
1431 || c.transform_keys
1432 .iter()
1433 .any(|k| matches!(k.ease, KeyEase::EaseIn | KeyEase::EaseOut | KeyEase::Hold))
1434}
1435
1436/// One line per video clip that `points` returns something for, as
1437/// `<name> video <ord> <index>{points}`: the shape of the `okeys` and `ckeys` lines.
1438fn video_key_lines(
1439 lanes: &[(LaneKind, Vec<Clip>)],
1440 name: &str,
1441 points: impl Fn(&Clip) -> String,
1442) -> Vec<u8> {
1443 let mut out = Vec::new();
1444 let mut video = 0u32;
1445 for (kind, clips) in lanes {
1446 if *kind != LaneKind::Video {
1447 continue;
1448 }
1449 video += 1;
1450 for (idx, c) in clips.iter().enumerate() {
1451 let points = points(c);
1452 if !points.is_empty() {
1453 out.extend_from_slice(format!("{name} video {video} {idx}{points}\n").as_bytes());
1454 }
1455 }
1456 }
1457 out
1458}
1459
1460/// The `reverse` lines: one per clip that plays backwards, as `reverse <kind> <ord>
1461/// <index>`. Only a reversed clip gets a line, and such a project is a v38 one.
1462fn reverse_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1463 let mut out = Vec::new();
1464 let (mut video, mut audio) = (0u32, 0u32);
1465 for (kind, clips) in lanes {
1466 let (keyword, ord) = match kind {
1467 LaneKind::Video => {
1468 video += 1;
1469 ("video", video)
1470 }
1471 LaneKind::Audio => {
1472 audio += 1;
1473 ("audio", audio)
1474 }
1475 LaneKind::Subtitle => continue,
1476 };
1477 for (idx, _) in clips.iter().enumerate().filter(|(_, c)| c.reversed) {
1478 out.extend_from_slice(format!("reverse {keyword} {ord} {idx}\n").as_bytes());
1479 }
1480 }
1481 out
1482}
1483
1484/// `deint video <ord> <index> <mode>`: one per clip whose mode is not `frame`, and such a
1485/// project is a v46 one.
1486fn deint_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1487 video_key_lines(lanes, "deint", |c| match c.deinterlace {
1488 Deinterlace::Frame => String::new(),
1489 d => format!(" {}", d.name()),
1490 })
1491}
1492
1493/// `lanename <kind> <ord> <name>`: one per lane that has a name.
1494fn lane_name_lines(lanes: &[(LaneKind, Vec<Clip>)], names: &[String]) -> Vec<u8> {
1495 let mut out = Vec::new();
1496 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
1497 for ((kind, _), name) in lanes.iter().zip(names) {
1498 let (keyword, ord) = match kind {
1499 LaneKind::Video => {
1500 video += 1;
1501 ("video", video)
1502 }
1503 LaneKind::Audio => {
1504 audio += 1;
1505 ("audio", audio)
1506 }
1507 LaneKind::Subtitle => {
1508 sub += 1;
1509 ("sub", sub)
1510 }
1511 };
1512 if !name.is_empty() {
1513 out.extend_from_slice(format!("lanename {keyword} {ord} ").as_bytes());
1514 escape_text(name, &mut out);
1515 out.push(b'\n');
1516 }
1517 }
1518 out
1519}
1520
1521/// `stab video <ord> <index> <strength> <crop>`: one per stabilised clip, and such a
1522/// project is a v44 one.
1523fn stab_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1524 video_key_lines(lanes, "stab", |c| {
1525 c.stabilise.map_or(String::new(), |st| format!(" {} {}", st.amount(), st.crop().name()))
1526 })
1527}
1528
1529/// The `mark` lines: one per clip that has a colour label or is switched off, as `mark <kind>
1530/// <ord> <index> <label> <on|off>` with the label 0 to 8. Only such a clip gets a line, and such a
1531/// project is a v48 one.
1532fn mark_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1533 let mut out = Vec::new();
1534 let (mut video, mut audio) = (0u32, 0u32);
1535 for (kind, clips) in lanes {
1536 let (keyword, ord) = match kind {
1537 LaneKind::Video => {
1538 video += 1;
1539 ("video", video)
1540 }
1541 LaneKind::Audio => {
1542 audio += 1;
1543 ("audio", audio)
1544 }
1545 LaneKind::Subtitle => continue,
1546 };
1547 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.mark.is_default()) {
1548 let state = if c.mark.off { "off" } else { "on" };
1549 out.extend_from_slice(format!("mark {keyword} {ord} {idx} {} {state}\n", c.mark.label).as_bytes());
1550 }
1551 }
1552 out
1553}
1554
1555/// The `angle` lines: one per clip that shows another angle than the first, as `angle <kind> <ord>
1556/// <index> <picture> <sound>` with angles counted from 1 and `-` for a sound that follows the
1557/// picture. Only such a clip gets a line, and such a project is a v47 one.
1558fn angle_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1559 let mut out = Vec::new();
1560 let (mut video, mut audio) = (0u32, 0u32);
1561 for (kind, clips) in lanes {
1562 let (keyword, ord) = match kind {
1563 LaneKind::Video => {
1564 video += 1;
1565 ("video", video)
1566 }
1567 LaneKind::Audio => {
1568 audio += 1;
1569 ("audio", audio)
1570 }
1571 LaneKind::Subtitle => continue,
1572 };
1573 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.angle.is_default()) {
1574 let sound = c.angle.audio.map_or("-".to_string(), |a| (u32::from(a) + 1).to_string());
1575 out.extend_from_slice(format!("angle {keyword} {ord} {idx} {} {sound}\n", u32::from(c.angle.video) + 1).as_bytes());
1576 }
1577 }
1578 out
1579}
1580
1581/// `okeys video <ord> <index> <at>:<ease>:<opacity> ...`, the opacity keys in
1582/// source order. Only a clip with keys gets a line, and such a project is a v39 one.
1583fn opacity_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1584 video_key_lines(lanes, "okeys", |c| {
1585 c.opacity_keys
1586 .iter()
1587 .map(|k| format!(" {}:{}:{}", k.at, k.ease.token(), k.opacity))
1588 .collect()
1589 })
1590}
1591
1592/// `ckeys video <ord> <index> <at>:<ease>:<brightness>,<contrast>,<saturation>,<tint> ...`,
1593/// the colour keys in source order. Only a clip with keys gets a line, and such
1594/// a project is a v39 one.
1595fn color_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1596 video_key_lines(lanes, "ckeys", |c| {
1597 c.color_keys
1598 .iter()
1599 .map(|k| {
1600 let p = &k.params;
1601 format!(
1602 " {}:{}:{},{},{},{}",
1603 k.at,
1604 k.ease.token(),
1605 p.brightness,
1606 p.contrast,
1607 p.saturation,
1608 p.tint
1609 )
1610 })
1611 .collect()
1612 })
1613}
1614
1615/// The `effect` lines (v42): `effect video <ord> <index> <kind> <on> <value>...`, one per
1616/// effect of a clip's stack, in stack order. Only a clip with effects gets any.
1617fn effect_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1618 let mut out = String::new();
1619 let mut video = 0u32;
1620 for (kind, clips) in lanes {
1621 if *kind != LaneKind::Video {
1622 continue;
1623 }
1624 video += 1;
1625 for (idx, c) in clips.iter().enumerate() {
1626 for e in &c.effects {
1627 out += &format!("effect video {video} {idx} {} {}", e.kind.name(), u8::from(e.on));
1628 for v in &e.values[..e.kind.params().len()] {
1629 out += &format!(" {v}");
1630 }
1631 out.push('\n');
1632 }
1633 }
1634 }
1635 out.into_bytes()
1636}
1637
1638/// The `mkeys` lines (v53): `mkeys video <ord> <index> <slot> <at>:<ease>:<x>,<y>,<w>,<h>,<feather> ...`,
1639/// the keys of the rect or ellipse mask at stack position `slot`, in source order. Only a
1640/// mask with keys gets a line.
1641fn mask_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1642 let mut out = String::new();
1643 let mut video = 0u32;
1644 for (kind, clips) in lanes {
1645 if *kind != LaneKind::Video {
1646 continue;
1647 }
1648 video += 1;
1649 for (idx, c) in clips.iter().enumerate() {
1650 for (slot, e) in c.effects.iter().enumerate() {
1651 if e.keys.is_empty() {
1652 continue;
1653 }
1654 out += &format!("mkeys video {video} {idx} {slot}");
1655 for k in &e.keys {
1656 out += &format!(" {}:{}:{},{},{},{},{}", k.at, k.ease.token(), k.x, k.y, k.width, k.height, k.feather);
1657 }
1658 out.push('\n');
1659 }
1660 }
1661 }
1662 out.into_bytes()
1663}
1664
1665/// The v43 look lines, one group per colour line that has one, named by the
1666/// colour line's position:
1667///
1668/// * `wheels <color> <lift> <gamma> <gain>`, each `<master>:<red>:<green>:<blue>`,
1669/// * `curve <color> <channel> <x>:<y>,<x>:<y>...`, one per channel (`master`,
1670/// `red`, `green`, `blue`) that holds points,
1671/// * `lut <color> <mix> <path>`, the path written as a source's is (relative
1672/// when inside the project's folder) and running to the end of the line.
1673fn look_lines(color: &[ColorParams], dir: &Path) -> Vec<u8> {
1674 let quad = |q: &[f32; 4]| format!("{:?}:{:?}:{:?}:{:?}", q[0], q[1], q[2], q[3]);
1675 let mut out = Vec::new();
1676 for (i, p) in color.iter().enumerate() {
1677 let look = &p.look;
1678 if look.wheels != crate::color::Wheels::default() {
1679 let w = &look.wheels;
1680 out.extend_from_slice(
1681 format!("wheels {i} {} {} {}\n", quad(&w.lift), quad(&w.gamma), quad(&w.gain)).as_bytes(),
1682 );
1683 }
1684 for (c, curve) in look.curves.iter().enumerate() {
1685 if curve.points().is_empty() {
1686 continue;
1687 }
1688 let pts: Vec<String> = curve.points().iter().map(|q| format!("{:?}:{:?}", q[0], q[1])).collect();
1689 out.extend_from_slice(
1690 format!("curve {i} {} {}\n", crate::color::CHANNELS[c], pts.join(",")).as_bytes(),
1691 );
1692 }
1693 if let Some(lut) = look.lut {
1694 out.extend_from_slice(format!("lut {i} {:?} ", look.lut_mix).as_bytes());
1695 escape(&written_path(&lut.path(), dir), &mut out);
1696 out.push(b'\n');
1697 }
1698 }
1699 out
1700}
1701
1702/// A `wheels`, `curve` or `lut` line (v43): see [`look_lines`]. A LUT file that is
1703/// missing or broken still loads -- the clip plays without it and
1704/// [`crate::Project::lut_problems`] names it -- but a malformed line is refused.
1705fn parse_look(head: &[u8], rest: &[u8], n: usize, dir: &Path, doc: &mut Document) -> crate::Result<()> {
1706 let sp = rest.iter().position(|&b| b == b' ').unwrap_or(rest.len());
1707 let at = number(&rest[..sp], n)? as usize;
1708 let rest = rest.get(sp + 1..).unwrap_or(&[]);
1709 let what = String::from_utf8_lossy(head).into_owned();
1710 if at >= doc.color.len() {
1711 return Err(format!("line {n}: {what} names color {at}, and there are {}", doc.color.len()).into());
1712 }
1713 let look = &mut doc.color[at].look;
1714 match head {
1715 b"wheels" => {
1716 let f = fields(rest, 3, "wheels", n)?;
1717 let mut q = [[0f32; 4]; 3];
1718 for (k, field) in f.iter().enumerate() {
1719 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
1720 if parts.len() != 4 {
1721 return Err(format!("line {n}: a wheel wants 4 values").into());
1722 }
1723 for (c, part) in parts.iter().enumerate() {
1724 let v = float(part, n)?;
1725 if !(-1.0..=1.0).contains(&v) {
1726 return Err(format!("line {n}: wheels has a value outside -1..1").into());
1727 }
1728 q[k][c] = v;
1729 }
1730 }
1731 look.wheels = crate::color::Wheels { lift: q[0], gamma: q[1], gain: q[2] };
1732 }
1733 b"curve" => {
1734 let f = fields(rest, 2, "curve", n)?;
1735 let channel = crate::color::CHANNELS
1736 .iter()
1737 .position(|c| c.as_bytes() == f[0])
1738 .ok_or_else(|| format!("line {n}: curve channel {:?} is not master, red, green or blue", String::from_utf8_lossy(f[0])))?;
1739 let mut pts = Vec::new();
1740 for pair in f[1].split(|&b| b == b',') {
1741 let xy: Vec<&[u8]> = pair.split(|&b| b == b':').collect();
1742 if xy.len() != 2 {
1743 return Err(format!("line {n}: a curve point is <x>:<y>").into());
1744 }
1745 pts.push([float(xy[0], n)?, float(xy[1], n)?]);
1746 }
1747 look.curves[channel] = crate::color::Curve::new(&pts).map_err(|e| format!("line {n}: {e}"))?;
1748 }
1749 _ => {
1750 let sp = rest.iter().position(|&b| b == b' ').ok_or_else(|| format!("line {n}: lut wants <mix> <path>"))?;
1751 let mix = float(&rest[..sp], n)?;
1752 if !(0.0..=1.0).contains(&mix) {
1753 return Err(format!("line {n}: lut mix must be 0..=1").into());
1754 }
1755 let path = unescape(&rest[sp + 1..], n)?;
1756 if path.as_os_str().is_empty() {
1757 return Err(format!("line {n}: lut without a path").into());
1758 }
1759 let path = if path.is_absolute() { path } else { dir.join(path) };
1760 look.lut = Some(crate::cube::LutRef::open(&path));
1761 look.lut_mix = mix;
1762 }
1763 }
1764 Ok(())
1765}
1766
1767/// `tkeys <kind> <ord> <index> <at>:<ease>:<pos_x>,<pos_y>,<scale>,<rotate>,<crop_l>,<crop_r>,<crop_t>,<crop_b>,<opacity> ...`,
1768/// the keys in source order. `ease` is `lin` or `ease`. Floats are written the
1769/// way the `transform` table writes them, `{}`, which reads back exactly. Only a
1770/// clip with keys gets a line, and such a project is a v32 one.
1771fn tkey_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1772 let mut out = Vec::new();
1773 let (mut video, mut audio) = (0u32, 0u32);
1774 for (kind, clips) in lanes {
1775 let (keyword, ord) = match kind {
1776 LaneKind::Video => {
1777 video += 1;
1778 ("video", video)
1779 }
1780 LaneKind::Audio => {
1781 audio += 1;
1782 ("audio", audio)
1783 }
1784 LaneKind::Subtitle => continue,
1785 };
1786 for (idx, c) in clips.iter().enumerate() {
1787 if c.transform_keys.is_empty() {
1788 continue;
1789 }
1790 let points: String = c
1791 .transform_keys
1792 .iter()
1793 .map(|k| {
1794 let p = &k.params;
1795 let ease = k.ease.token();
1796 format!(
1797 " {}:{ease}:{},{},{},{},{},{},{},{},{}",
1798 k.at,
1799 p.pos_x,
1800 p.pos_y,
1801 p.scale,
1802 p.rotate,
1803 p.crop_l,
1804 p.crop_r,
1805 p.crop_t,
1806 p.crop_b,
1807 p.opacity
1808 )
1809 })
1810 .collect();
1811 out.extend_from_slice(format!("tkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1812 }
1813 }
1814 out
1815}
1816
1817/// The `chapter` lines: one per chapter, in frame order, as [`save_flagged`]
1818/// writes them after the titles. A project with none writes nothing.
1819fn chapter_lines(chapters: &[Chapter]) -> Vec<u8> {
1820 let mut out = Vec::new();
1821 for c in chapters {
1822 out.extend_from_slice(format!("chapter {} ", c.frame).as_bytes());
1823 escape_text(&c.title, &mut out);
1824 out.push(b'\n');
1825 }
1826 out
1827}
1828
1829/// The `marker` lines, one per marker in frame order, then a `marknote` line for each one
1830/// that has a note, as [`save_flagged`] writes them after the chapters. None for a project with none.
1831/// The `capstyle` line, `capstyle <animation> <rrggbb> <box 0|1> <uppercase 0|1> <words per
1832/// line>`: how burned captions animate. None for the default style, so a project that never
1833/// touched it is the bytes it was before v40, bar the version line.
1834fn capstyle_line(cs: &CaptionStyle) -> Vec<u8> {
1835 if *cs == CaptionStyle::default() {
1836 return Vec::new();
1837 }
1838 let [r, g, b] = cs.highlight;
1839 format!(
1840 "capstyle {} {r:02x}{g:02x}{b:02x} {} {} {}\n",
1841 cs.anim.name(),
1842 u8::from(cs.hl_box),
1843 u8::from(cs.uppercase),
1844 cs.words_per_line
1845 )
1846 .into_bytes()
1847}
1848
1849fn marker_lines(markers: &[Marker]) -> Vec<u8> {
1850 let mut out = Vec::new();
1851 for m in markers {
1852 out.extend_from_slice(format!("marker {} {} {} ", m.frame, m.length, m.color.name()).as_bytes());
1853 escape_text(&m.name, &mut out);
1854 out.push(b'\n');
1855 }
1856 for (i, m) in markers.iter().enumerate().filter(|(_, m)| !m.note.is_empty()) {
1857 out.extend_from_slice(format!("marknote {i} ").as_bytes());
1858 escape_text(&m.note, &mut out);
1859 out.push(b'\n');
1860 }
1861 out
1862}
1863
1864/// The `title` lines: one per title, in list order, as [`save_flagged`] writes
1865/// them. A project with none is the bytes a v25 one was bar the version line.
1866fn title_lines(titles: &[Title]) -> Vec<u8> {
1867 let mut out = Vec::new();
1868 for t in titles {
1869 let outline = match t.style.outline {
1870 Outline::None => "none",
1871 Outline::Thin => "thin",
1872 Outline::Thick => "thick",
1873 };
1874 let place = match t.style.place {
1875 Place::Bottom => "bottom",
1876 Place::Top => "top",
1877 Place::Centre => "centre",
1878 };
1879 out.extend_from_slice(
1880 format!(
1881 "title {} {} {} {} {} {outline} {} {place} ",
1882 t.start,
1883 t.frames,
1884 t.fade_in,
1885 t.fade_out,
1886 t.style.size,
1887 u8::from(t.style.boxed)
1888 )
1889 .as_bytes(),
1890 );
1891 escape_text(&t.text, &mut out);
1892 out.push(b'\n');
1893 }
1894 // A title's colour, weight, alignment, position and box colour, one line per title that has
1895 // any of them off the default, so a project without them is the bytes it was.
1896 for (i, t) in titles.iter().enumerate() {
1897 let st = &t.style;
1898 if title_look_is_default(st) {
1899 continue;
1900 }
1901 let hplace = match st.hplace {
1902 HPlace::Centre => "centre",
1903 HPlace::Left => "left",
1904 HPlace::Right => "right",
1905 };
1906 let align = match st.align {
1907 Align::Centre => "centre",
1908 Align::Left => "left",
1909 Align::Right => "right",
1910 };
1911 let weight = match st.weight {
1912 Weight::Regular => "regular",
1913 Weight::Bold => "bold",
1914 };
1915 let [r, g, b] = st.ink;
1916 let [br, bg, bb, ba] = st.box_color;
1917 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());
1918 }
1919 // A title's entrance and exit, one line per title that has either.
1920 for (i, t) in titles.iter().enumerate() {
1921 if t.in_anim == TitleAnim::None && t.out_anim == TitleAnim::None {
1922 continue;
1923 }
1924 out.extend_from_slice(format!("titleanim {i} {} {} {}\n", t.in_anim.name(), t.out_anim.name(), t.anim_frames).as_bytes());
1925 }
1926 out
1927}
1928
1929/// Whether a style has none of the v49 title looks: white, regular, centred, on the black box.
1930fn title_look_is_default(st: &TextStyle) -> bool {
1931 let d = TextStyle::default();
1932 st.hplace == d.hplace && st.align == d.align && st.weight == d.weight && st.ink == d.ink && st.box_color == d.box_color
1933}
1934
1935/// The `flags` lines: one per lane that has a switch set, in lane order. Only a
1936/// lane somebody has switched gets one, so a project with none is the bytes a
1937/// v23 one was bar the version line.
1938fn flag_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1939 let mut out = Vec::new();
1940 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
1941 for ((kind, _), f) in lanes.iter().zip(flags) {
1942 let (keyword, ord) = match kind {
1943 LaneKind::Video => {
1944 video += 1;
1945 ("video", video)
1946 }
1947 LaneKind::Audio => {
1948 audio += 1;
1949 ("audio", audio)
1950 }
1951 LaneKind::Subtitle => {
1952 sub += 1;
1953 ("sub", sub)
1954 }
1955 };
1956 let words: Vec<&str> = [
1957 (f.hidden, "hidden"),
1958 (f.muted, "muted"),
1959 (f.locked, "locked"),
1960 ]
1961 .into_iter()
1962 .filter_map(|(on, word)| on.then_some(word))
1963 .collect();
1964 if !words.is_empty() {
1965 out.extend_from_slice(
1966 format!("flags {keyword} {ord} {}\n", words.join(" ")).as_bytes(),
1967 );
1968 }
1969 }
1970 out
1971}
1972
1973#[allow(clippy::too_many_arguments)]
1974fn emit(
1975 dir: &Path,
1976 sources: &[Source],
1977 lanes: &[(LaneKind, Vec<Clip>)],
1978 gains: &[f32],
1979 subs: &[Vec<SubClip>],
1980 subtitles: &[SubtitleTrack],
1981 eq: &[EqParams],
1982 color: &[ColorParams],
1983 transform: &[TransformParams],
1984 resolution: (u32, u32),
1985 fps: Option<f64>,
1986 tone: crate::tonemap::Preset,
1987 proxy: bool,
1988 auto_proxy: bool,
1989 encoder: crate::export::EncoderSeat,
1990 limiter: Limiter,
1991 sample_rate: Option<u32>,
1992 playhead: u32,
1993) -> Vec<u8> {
1994 let mut out = Vec::new();
1995 // The file says which dialect it is by whether it needs the newest one:
1996 // a transform's opacity is the only thing v31 adds, so a project without
1997 // one is the bytes a v30 project always was, bar none, and an older reader
1998 // still opens it.
1999 // The newest dialect is only for a project that has placement keys
2000 // (`tkeys` lines, [`tkeys_lines`]); one with opacity alone is still v31.
2001 let needs_v33 = subtitles.iter().any(|t| !t.language.is_empty());
2002 let needs_v32 = lanes
2003 .iter()
2004 .any(|(_, clips)| clips.iter().any(|c| !c.transform_keys.is_empty()));
2005 let needs_v31 = transform.iter().any(|p| p.opacity != 1.0);
2006 out.extend_from_slice(if needs_v33 {
2007 MAGIC_V33
2008 } else if needs_v32 {
2009 MAGIC_V32
2010 } else if needs_v31 {
2011 MAGIC_V31
2012 } else {
2013 MAGIC_V30
2014 });
2015 out.push(b'\n');
2016 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
2017 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
2018 // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read
2019 // back as the very number, or every clip on it lands on another frame.
2020 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
2021 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
2022 }
2023 // Beside it, and by the same rule: a project nobody chose a sound rate for
2024 // is the mix the source's own probe always gave it, which is what leaving
2025 // this line out still means.
2026 if let Some(rate) = sample_rate.filter(|&r| (1_000..=384_000).contains(&r)) {
2027 out.extend_from_slice(format!("samplerate {rate}\n").as_bytes());
2028 }
2029 // Beside the rate, and written only when it is not the default: a project
2030 // holding no HDR media has nothing to say here, and saying nothing is what
2031 // a v10 file already said.
2032 if tone != crate::tonemap::Preset::default() {
2033 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
2034 }
2035 // Beside it and by the same rule: a project cut on the films themselves --
2036 // every project before there were stand-ins -- says nothing here.
2037 if proxy {
2038 out.extend_from_slice(b"proxy on\n");
2039 }
2040 // Beside it and by the same rule the other way up: making them by itself is
2041 // what every project before this line did, so only a project told to stop
2042 // has anything to say here.
2043 if !auto_proxy {
2044 out.extend_from_slice(b"autoproxy off\n");
2045 }
2046 // ...and which encoder writes the picture, by the same rule again: `auto`
2047 // is what every project before this line did, so only a project whose owner
2048 // picked a seat says anything here.
2049 if encoder != crate::export::EncoderSeat::default() {
2050 out.extend_from_slice(format!("encoder {}\n", encoder.name()).as_bytes());
2051 }
2052 // Written only when it is not the default, so a project nobody has limited
2053 // is the same bytes it was in v8 bar the version line.
2054 if limiter != Limiter::default() {
2055 out.extend_from_slice(
2056 format!(
2057 "limiter {:?} {}\n",
2058 limiter.ceiling_db,
2059 match limiter.on {
2060 true => "on",
2061 false => "off",
2062 }
2063 )
2064 .as_bytes(),
2065 );
2066 }
2067 for s in sources {
2068 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
2069 escape(&written_path(&s.path, dir), &mut out);
2070 out.push(b'\n');
2071 }
2072 // The subtitle tracks, by reference: which track of which file, and never
2073 // the cues (see the module docs). Beside the sources because that is what
2074 // they are -- a file this project reads from -- although nothing indexes
2075 // them and their order is only the order they were added in.
2076 for t in subtitles {
2077 let track = t.track.map_or("-".to_string(), |n| n.to_string());
2078 out.extend_from_slice(format!("subtitle {track} ").as_bytes());
2079 escape(&written_path(&t.path, dir), &mut out);
2080 out.push(b'\n');
2081 }
2082 // The language of each track that has one, as `sublang` lines after the
2083 // subtitle lines they name: a standalone file's is set by an import or a
2084 // retype, and an embedded track's is its container's until a retype
2085 // replaces it. Only a track with one is written, and the header only says
2086 // v33 when one is, so a project with none is written exactly as before.
2087 for (track, t) in subtitles.iter().enumerate() {
2088 if t.language.is_empty() {
2089 continue;
2090 }
2091 out.extend_from_slice(format!("sublang {track} ").as_bytes());
2092 escape_text(&t.language, &mut out);
2093 out.push(b'\n');
2094 }
2095 // Before the clips, for the reason the sources are: a clip names one by the
2096 // position of its line, so the line has to be there first.
2097 for params in eq {
2098 out.extend_from_slice(b"eq");
2099 for b in &params.bands {
2100 // `{:?}` rather than `{}`: it is the formatting that promises the
2101 // shortest string parsing back to this exact f32, and it never
2102 // prints a bare integer, which would read as another field's shape.
2103 let kind = match b.kind {
2104 BandKind::LowShelf => "ls",
2105 BandKind::Peak => "pk",
2106 BandKind::HighShelf => "hs",
2107 BandKind::LowCut => "lc",
2108 BandKind::HighCut => "hc",
2109 };
2110 out.extend_from_slice(
2111 format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
2112 );
2113 }
2114 out.push(b'\n');
2115 }
2116 // ...and the colour table, for the same reason and by the same rules.
2117 for p in color {
2118 out.extend_from_slice(
2119 format!(
2120 "color {:?}:{:?}:{:?}:{:?}\n",
2121 p.brightness, p.contrast, p.saturation, p.tint
2122 )
2123 .as_bytes(),
2124 );
2125 }
2126 // ...and the transform table, for the same reason and by the same rules.
2127 for p in transform {
2128 let mut line = format!(
2129 "transform {:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}",
2130 p.pos_x, p.pos_y, p.scale, p.rotate, p.crop_l, p.crop_r, p.crop_t, p.crop_b
2131 );
2132 // The ninth field only where it says something: an opacity of 1 is the
2133 // eight-field line every dialect since v20 wrote.
2134 if p.opacity != 1.0 {
2135 line.push_str(&format!(":{:?}", p.opacity));
2136 }
2137 line.push('\n');
2138 out.extend_from_slice(line.as_bytes());
2139 }
2140 // Lane by lane rather than interleaved by time: a lane reads as a list, the
2141 // parser gets its sortedness check for free from the order it is in, and
2142 // the lanes come back out in the order they are displayed in.
2143 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
2144 for (at, (kind, clips)) in lanes.iter().enumerate() {
2145 let (keyword, ord) = match kind {
2146 LaneKind::Video => {
2147 video += 1;
2148 ("video", video)
2149 }
2150 LaneKind::Audio => {
2151 audio += 1;
2152 ("audio", audio)
2153 }
2154 LaneKind::Subtitle => {
2155 subtitle += 1;
2156 ("sub", subtitle)
2157 }
2158 };
2159 // A subtitle lane holds no `Clip` at all ([`LaneKind::Subtitle`]): what
2160 // is on it is in `subs`, one list per lane and in step with this one,
2161 // and it is written here so the lane comes back in its place among the
2162 // others.
2163 if *kind == LaneKind::Subtitle {
2164 let placed = subs.get(at).map_or(&[][..], Vec::as_slice);
2165 if placed.is_empty() {
2166 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2167 }
2168 for s in placed {
2169 // The group field only when the caption is in one, for the
2170 // clip line's reason: a project nobody grouped a caption in is
2171 // the same bytes it was in v15.
2172 let link = s.link.map_or(String::new(), |l| format!(" {l}"));
2173 out.extend_from_slice(
2174 format!(
2175 "{keyword} {ord} {} {} {} {} {}{link}\n",
2176 s.start, s.frames, s.track, s.in_us, s.out_us
2177 )
2178 .as_bytes(),
2179 );
2180 }
2181 continue;
2182 }
2183 // A lane is declared by its clips; one holding nothing has to say so on
2184 // a line of its own, or the lane itself would not survive the round trip.
2185 if clips.is_empty() {
2186 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2187 }
2188 for c in clips {
2189 let link = c.link.map_or("-".to_string(), |l| l.to_string());
2190 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
2191 let color = c.color.map_or("-".to_string(), |e| e.to_string());
2192 let transform = c.transform.map_or("-".to_string(), |e| e.to_string());
2193 out.extend_from_slice(
2194 format!(
2195 "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {} {} {transform} {} {}\n",
2196 c.start,
2197 c.in_frame,
2198 c.out_frame,
2199 c.source,
2200 fit_name(c.fit),
2201 c.speed.permille(),
2202 c.fade_in,
2203 c.fade_out,
2204 c.transition_out,
2205 c.visualizer,
2206 c.viz_paint,
2207 )
2208 .as_bytes(),
2209 );
2210 }
2211 }
2212 // After the lanes, not before them: a gain line names a lane that has to be
2213 // there already, and a lane is declared by its own lines. Only the lanes
2214 // somebody has turned get one.
2215 let (mut video, mut audio) = (0, 0);
2216 for ((kind, _), &db) in lanes.iter().zip(gains) {
2217 let (keyword, ord) = match kind {
2218 LaneKind::Video => {
2219 video += 1;
2220 ("video", video)
2221 }
2222 LaneKind::Audio => {
2223 audio += 1;
2224 ("audio", audio)
2225 }
2226 // In the list -- the two are zipped, so it has to be -- and never
2227 // written: a subtitle lane has no volume at all
2228 // (`Project::set_lane_gain_db` refuses one), so its entry is the
2229 // `0.0` no lane writes a line for.
2230 LaneKind::Subtitle => continue,
2231 };
2232 if db != 0.0 {
2233 out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes());
2234 }
2235 }
2236 out
2237}
2238
2239fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
2240 // One trailing newline is the line terminator of the last line, not an
2241 // empty line -- any further one is, and is refused below.
2242 let body = data.strip_suffix(b"\n").unwrap_or(data);
2243 let mut lines = body.split(|&b| b == b'\n').enumerate();
2244 let (_, first) = lines.next().unwrap_or((0, &[]));
2245 let v1 = first == MAGIC_V1;
2246 // The dialects that wrote a source line without its stream field. Reading
2247 // one is the whole of what "an old project still opens" means here.
2248 let streamless = v1 || first == MAGIC_V2;
2249 // The one that carries a clip's volume envelope, as `gainkeys` lines...
2250 // The one that lets a lane be ducked under several keys, as several `duck`
2251 // lines naming one lane; a v29 reader refuses it by name.
2252 // The one that carries a transform's opacity, as a ninth field on a
2253 // `transform` line; a v30 reader refuses it by its field count.
2254 // The one that carries a clip's placement animation, as `tkeys` lines...
2255 // The one that carries a clip's stabilisation, as `stab` lines...
2256 // The one that carries a clip's pitch shift, as `pitch` lines...
2257 let v55 = first == MAGIC;
2258 let v54 = v55 || first == MAGIC_V54;
2259 let v53 = v54 || first == MAGIC_V53;
2260 let v52 = v53 || first == MAGIC_V52;
2261 let v51 = v52 || first == MAGIC_V51;
2262 let v50 = v51 || first == MAGIC_V50;
2263 let v49 = v50 || first == MAGIC_V49;
2264 let v48 = v49 || first == MAGIC_V48;
2265 let v47 = v48 || first == MAGIC_V47;
2266 let v46 = v47 || first == MAGIC_V46;
2267 let v45 = v46 || first == MAGIC_V45;
2268 let v44 = v45 || first == MAGIC_V44;
2269 let v43 = v44 || first == MAGIC_V43;
2270 let v42 = v43 || first == MAGIC_V42;
2271 let v41 = v42 || first == MAGIC_V41;
2272 let v40 = v41 || first == MAGIC_V40;
2273 let v39 = v40 || first == MAGIC_V39;
2274 let v38 = v39 || first == MAGIC_V38;
2275 let v37 = v38 || first == MAGIC_V37;
2276 let v36 = v37 || first == MAGIC_V36;
2277 let v35 = v36 || first == MAGIC_V35;
2278 let v34 = v35 || first == MAGIC_V34;
2279 let v33 = v34 || first == MAGIC_V33;
2280 let v32 = v33 || first == MAGIC_V32;
2281 let v31 = v32 || first == MAGIC_V31;
2282 let v30 = v31 || first == MAGIC_V30;
2283 let v29 = v30 || first == MAGIC_V29;
2284 let v28 = v29 || first == MAGIC_V28;
2285 // The one that carries a clip's own gain in dB, as `clipgain` lines...
2286 let v27 = v28 || first == MAGIC_V27;
2287 // The one that carries the title cards and text overlays...
2288 let v26 = v27 || first == MAGIC_V26;
2289 // The one that says which lanes are ducked under which...
2290 let v25 = v26 || first == MAGIC_V25;
2291 // The one that says which lanes are hidden, muted or locked...
2292 let v24 = v25 || first == MAGIC_V24;
2293 // The one that carries a strand colour of its own above the packed
2294 // visualizer paint (hue/sat, with the top bit as the flag)...
2295 let v23 = v24 || first == MAGIC_V23;
2296 // The one that carries packed visualizer paint (hue/sat/strands/glow)...
2297 let v22 = v23 || first == MAGIC_V22;
2298 // The one that carries per-clip visualizer flags...
2299 let v21 = v22 || first == MAGIC_V21;
2300 // The one that carries a per-clip transform (position/scale/rotate/crop)...
2301 let v20 = v21 || first == MAGIC_V20;
2302 // ...the one that carries a per-clip cross-dissolve into its successor...
2303 let v19 = v20 || first == MAGIC_V19;
2304 // ...the one that carries a per-clip fade envelope...
2305 let v18 = v19 || first == MAGIC_V18;
2306 // ...the one that carries an explicit sound rate...
2307 let v17 = v18 || first == MAGIC_V17;
2308 // ...the one whose captions may carry a group id...
2309 let v16 = v17 || first == MAGIC_V16;
2310 // ...the one that places the words it names...
2311 let v15 = v16 || first == MAGIC_V15;
2312 // ...the ones that say which encoder an export takes...
2313 let v14 = v15 || first == MAGIC_V14;
2314 // ...the ones that say whether the stand-ins are made by themselves...
2315 let v13 = v14 || first == MAGIC_V13;
2316 // ...the ones that say whether it is cut on stand-ins...
2317 let v12 = v13 || first == MAGIC_V12;
2318 // ...the ones that carry an HDR rendition...
2319 let v11 = v12 || first == MAGIC_V11;
2320 // ...the ones that carry subtitle tracks...
2321 let v10 = v11 || first == MAGIC_V10;
2322 // ...the ones that carry the mix -- lane volumes, the master limiter and
2323 // the rate the timeline was cut at...
2324 let v9 = v10 || first == MAGIC_V9;
2325 // ...the ones that carry a per-clip speed...
2326 let v8 = v9 || first == MAGIC_V8;
2327 // ...the ones that carry a project resolution and per-clip fit policies...
2328 let v7 = v8 || first == MAGIC_V7;
2329 // ...the ones that carry colour grades...
2330 let v6 = v7 || first == MAGIC_V6;
2331 // ...the ones that carry equalizer settings...
2332 let v5 = v6 || first == MAGIC_V5;
2333 // ...and the ones that number their lanes. Every older one held two.
2334 let numbered = v5 || first == MAGIC_V4;
2335 if !numbered && !streamless && first != MAGIC_V3 {
2336 return Err(match first.strip_prefix(b"edith ") {
2337 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
2338 None => "line 1: not an edith file".to_string(),
2339 }
2340 .into());
2341 }
2342
2343 let mut doc = Document {
2344 sources: Vec::new(),
2345 // v4 on declares its lanes as they come; every dialect before it held
2346 // exactly `V1` and `A1`, either of which could be empty.
2347 lanes: if numbered {
2348 Vec::new()
2349 } else {
2350 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
2351 },
2352 // Resized to the lanes as they arrive, and once more at the end, so a
2353 // caller may zip the two exactly as it zips the gains. Nothing before
2354 // v15 places a word anywhere: those projects have the palette and no
2355 // subtitle lane to put any of it on.
2356 subs: Vec::new(),
2357 // Nothing before v5 equalizes anything, and nothing before v6 grades.
2358 eq: Vec::new(),
2359 color: Vec::new(),
2360 // Nothing before v20 places any clip anywhere but its fit policy's own
2361 // spot: the identity transform is what leaving a clip's index out
2362 // still means.
2363 transform: Vec::new(),
2364 // Nothing before v7 has a resolution of its own: source 0's picture is
2365 // what those projects were, and `None` is how the loader is told so.
2366 resolution: None,
2367 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
2368 // no limiter, and the rate inferred from the scaffold as it always was.
2369 gains: Vec::new(),
2370 // Nothing before v24 could hide, mute or lock a lane: every lane is
2371 // showing, audible and unlocked, which is what leaving a line out means.
2372 flags: Vec::new(),
2373 // Nothing before v25 ducks a lane under another: every lane plays at
2374 // its own level, which is what leaving a line out means.
2375 ducks: Vec::new(),
2376 titles: Vec::new(),
2377 chapters: Vec::new(),
2378 markers: Vec::new(),
2379 caption_style: CaptionStyle::default(),
2380 voices: Vec::new(),
2381 names: Vec::new(),
2382 // Nothing before v10 shows a subtitle, and nothing before v11 was shown
2383 // in any rendition but the published one.
2384 subtitles: Vec::new(),
2385 sub_langs: Vec::new(),
2386 cue_edits: Vec::new(),
2387 cue_adds: Vec::new(),
2388 cue_words: Vec::new(),
2389 limiter: Limiter::default(),
2390 tone: crate::tonemap::Preset::default(),
2391 proxy: false,
2392 // ...and nothing before v13 could be told *not* to make one: an import
2393 // that wanted a stand-in got one, which is what leaving the line out
2394 // still means.
2395 auto_proxy: true,
2396 // ...and nothing before v14 could be told *which* encoder: an export
2397 // took the seat this machine had, which is what leaving the line out
2398 // still means.
2399 encoder: crate::export::EncoderSeat::default(),
2400 fps: None,
2401 // Nothing before v17 chose a sound rate: the source's own probe is
2402 // still what the mix is cut at, which is what `None` means everywhere
2403 // else it reaches (`PlaybackSession::open_project`).
2404 sample_rate: None,
2405 playhead: 0,
2406 seq_active: None,
2407 seq_order: Vec::new(),
2408 sequences: Vec::new(),
2409 mcams: Vec::new(),
2410 bins: Vec::new(),
2411 notes: String::new(),
2412 still_secs: None,
2413 };
2414 // The block of a parked sequence being read: its id, name and the lines so far.
2415 let mut block: Option<(u32, String, Vec<u8>)> = None;
2416 let mut playhead_seen = false;
2417 // Where the next v1 clip is placed: that dialect had no `start` field, the
2418 // clips simply queued up.
2419 let mut queued = 0u32;
2420 for (i, line) in lines {
2421 let n = i + 1;
2422 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
2423 Some(at) => (&line[..at], &line[at + 1..]),
2424 None => (line, &line[line.len()..]),
2425 };
2426 if let Some((id, name, buf)) = block.as_mut() {
2427 if line == b"endseq" {
2428 if doc.sequences.len() >= MAX_SEQUENCES {
2429 return Err(format!("line {n}: a project holds at most {MAX_SEQUENCES} sequences").into());
2430 }
2431 let sub = parse(buf, dir).map_err(|e| format!("sequence \"{name}\": {e}"))?;
2432 doc.sequences.push(SeqDoc { id: *id, name: std::mem::take(name), doc: sub });
2433 block = None;
2434 } else {
2435 buf.extend_from_slice(line);
2436 buf.push(b'\n');
2437 }
2438 continue;
2439 }
2440 match keyword {
2441 b"seqactive" if v45 => {
2442 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2443 let id = number(id, n)?;
2444 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2445 doc.seq_active = Some((id, name));
2446 }
2447 b"seqorder" if v45 => {
2448 for f in rest.split(|&b| b == b' ').filter(|f| !f.is_empty()) {
2449 if doc.seq_order.len() >= MAX_SEQUENCES {
2450 return Err(format!("line {n}: seqorder names more than {MAX_SEQUENCES} sequences").into());
2451 }
2452 doc.seq_order.push(number(f, n)?);
2453 }
2454 }
2455 b"seq" if v45 => {
2456 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2457 let id = number(id, n)?;
2458 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2459 block = Some((id, name, Vec::new()));
2460 }
2461 b"playhead" => {
2462 if playhead_seen || !doc.sources.is_empty() {
2463 return Err(
2464 format!("line {n}: playhead belongs once, before the sources").into(),
2465 );
2466 }
2467 doc.playhead = number(rest, n)?;
2468 playhead_seen = true;
2469 }
2470 b"resolution" if v7 => {
2471 if doc.resolution.is_some() || !doc.sources.is_empty() {
2472 return Err(
2473 format!("line {n}: resolution belongs once, before the sources").into(),
2474 );
2475 }
2476 let f = fields(rest, 2, "resolution", n)?;
2477 let (width, height) = (number(f[0], n)?, number(f[1], n)?);
2478 // The same bound the keystroke has (`crate::is_resolution`):
2479 // unbounded here, this line reached `open_black` and panicked
2480 // the open with a capacity overflow.
2481 if !crate::is_resolution(width, height) {
2482 return Err(format!("line {n}: {width}x{height} is not a picture").into());
2483 }
2484 doc.resolution = Some((width, height));
2485 }
2486 b"fps" if v9 => {
2487 if doc.fps.is_some() || !doc.sources.is_empty() {
2488 return Err(format!("line {n}: fps belongs once, before the sources").into());
2489 }
2490 let f = fields(rest, 1, "fps", n)?;
2491 let fps = std::str::from_utf8(f[0])
2492 .ok()
2493 .and_then(|s| s.parse::<f64>().ok())
2494 .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0)
2495 .ok_or_else(|| {
2496 format!(
2497 "line {n}: {:?} is not a frame rate",
2498 String::from_utf8_lossy(f[0])
2499 )
2500 })?;
2501 doc.fps = Some(fps);
2502 }
2503 b"samplerate" if v17 => {
2504 if doc.sample_rate.is_some() || !doc.sources.is_empty() {
2505 return Err(
2506 format!("line {n}: samplerate belongs once, before the sources").into(),
2507 );
2508 }
2509 let f = fields(rest, 1, "samplerate", n)?;
2510 let rate = number(f[0], n)?;
2511 if !(1_000..=384_000).contains(&rate) {
2512 return Err(format!("line {n}: {rate} Hz is not a sound rate").into());
2513 }
2514 doc.sample_rate = Some(rate);
2515 }
2516 b"tonemap" if v11 => {
2517 if !doc.sources.is_empty() {
2518 return Err(
2519 format!("line {n}: tonemap belongs once, before the sources").into(),
2520 );
2521 }
2522 let f = fields(rest, 1, "tonemap", n)?;
2523 doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| {
2524 format!(
2525 "line {n}: {:?} is not a tone map",
2526 String::from_utf8_lossy(f[0])
2527 )
2528 })?;
2529 }
2530 b"proxy" if v12 => {
2531 if !doc.sources.is_empty() {
2532 return Err(format!("line {n}: proxy belongs once, before the sources").into());
2533 }
2534 let f = fields(rest, 1, "proxy", n)?;
2535 doc.proxy = match f[0] {
2536 b"on" => true,
2537 b"off" => false,
2538 other => {
2539 return Err(format!(
2540 "line {n}: proxy is on or off, not {:?}",
2541 String::from_utf8_lossy(other)
2542 )
2543 .into());
2544 }
2545 };
2546 }
2547 b"autoproxy" if v13 => {
2548 if !doc.sources.is_empty() {
2549 return Err(
2550 format!("line {n}: autoproxy belongs once, before the sources").into(),
2551 );
2552 }
2553 let f = fields(rest, 1, "autoproxy", n)?;
2554 doc.auto_proxy = match f[0] {
2555 b"on" => true,
2556 b"off" => false,
2557 other => {
2558 return Err(format!(
2559 "line {n}: autoproxy is on or off, not {:?}",
2560 String::from_utf8_lossy(other)
2561 )
2562 .into());
2563 }
2564 };
2565 }
2566 b"encoder" if v14 => {
2567 if !doc.sources.is_empty() {
2568 return Err(
2569 format!("line {n}: encoder belongs once, before the sources").into(),
2570 );
2571 }
2572 let f = fields(rest, 1, "encoder", n)?;
2573 doc.encoder = crate::export::EncoderSeat::from_name(f[0]).ok_or_else(|| {
2574 format!(
2575 "line {n}: encoder is auto, hardware or software, not {:?}",
2576 String::from_utf8_lossy(f[0])
2577 )
2578 })?;
2579 }
2580 b"limiter" if v9 => {
2581 if !doc.sources.is_empty() {
2582 return Err(
2583 format!("line {n}: limiter belongs once, before the sources").into(),
2584 );
2585 }
2586 let f = fields(rest, 2, "limiter", n)?;
2587 let on = match f[1] {
2588 b"on" => true,
2589 b"off" => false,
2590 other => {
2591 return Err(format!(
2592 "line {n}: limiter is on or off, not {:?}",
2593 String::from_utf8_lossy(other)
2594 )
2595 .into());
2596 }
2597 };
2598 // Through the same clamp a nudge goes through: a hand-written
2599 // ceiling above full scale is a ceiling that limits nothing.
2600 doc.limiter = Limiter {
2601 on,
2602 ..Limiter::default()
2603 }
2604 .with_ceiling(float(f[0], n)?);
2605 }
2606 // After the lanes it names, which is where `emit` writes it: a lane
2607 // is declared by its own lines, and a gain declares nothing.
2608 b"gain" if v9 => {
2609 let f = fields(rest, 3, "gain", n)?;
2610 let kind = match f[0] {
2611 b"video" => LaneKind::Video,
2612 b"audio" => LaneKind::Audio,
2613 other => {
2614 return Err(format!(
2615 "line {n}: gain names {:?}, not a lane kind",
2616 String::from_utf8_lossy(other)
2617 )
2618 .into());
2619 }
2620 };
2621 let ord = number(f[1], n)?;
2622 let at = doc
2623 .lanes
2624 .iter()
2625 .enumerate()
2626 .filter(|(_, (k, _))| *k == kind)
2627 .nth(ord.saturating_sub(1) as usize)
2628 .map(|(at, _)| at)
2629 .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?;
2630 doc.gains.resize(doc.lanes.len(), 0.0);
2631 doc.gains[at] = float(f[2], n)?;
2632 }
2633 // After the lanes, for the reason a gain is: it names one. A line
2634 // carries the switches that are set, in any order and each once, and
2635 // a switch the kind of lane cannot have is refused by name.
2636 // After the lanes, for the reason a gain is: it names one, and the key
2637 // it names is checked once the whole file is read.
2638 b"duck" if v25 => {
2639 let f = fields(rest, 7, "duck", n)?;
2640 if f[0] != b"audio" {
2641 return Err(format!(
2642 "line {n}: duck names {:?}, not an audio lane",
2643 String::from_utf8_lossy(f[0])
2644 )
2645 .into());
2646 }
2647 let ord = number(f[1], n)?;
2648 let at = doc
2649 .lanes
2650 .iter()
2651 .enumerate()
2652 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2653 .nth(ord.saturating_sub(1) as usize)
2654 .map(|(at, _)| at)
2655 .ok_or_else(|| format!("line {n}: duck names a lane that is not there"))?;
2656 // 1-based in the file, as a gain's lane is; 0-based in the struct.
2657 let under = number(f[2], n)?;
2658 let duck = Duck {
2659 under: under.checked_sub(1).ok_or_else(|| {
2660 format!("line {n}: duck names audio lane 0, and lanes count from 1")
2661 })? as usize,
2662 depth_db: float(f[3], n)?,
2663 threshold_db: float(f[4], n)?,
2664 attack_ms: float(f[5], n)?,
2665 release_ms: float(f[6], n)?,
2666 };
2667 let in_range = (MIN_DEPTH_DB..=MAX_DEPTH_DB).contains(&duck.depth_db)
2668 && (MIN_THRESHOLD_DB..=MAX_THRESHOLD_DB).contains(&duck.threshold_db)
2669 && duck.attack_ms >= MIN_TIME_MS
2670 && duck.attack_ms <= MAX_ATTACK_MS
2671 && duck.release_ms >= MIN_TIME_MS
2672 && duck.release_ms <= MAX_RELEASE_MS;
2673 if !in_range {
2674 return Err(format!("line {n}: duck has a number out of its range").into());
2675 }
2676 doc.ducks.resize(doc.lanes.len(), Vec::new());
2677 // Several keys for one lane are a v30 dialect; before it a lane
2678 // had one duck, and a second line for it is a file that says
2679 // something its dialect cannot.
2680 if !v30 && !doc.ducks[at].is_empty() {
2681 return Err(format!("line {n}: duck names a lane twice").into());
2682 }
2683 if doc.ducks[at].iter().any(|d| d.under == duck.under) {
2684 return Err(format!("line {n}: duck names the same key twice").into());
2685 }
2686 doc.ducks[at].push(duck);
2687 }
2688 b"voice" if v41 => parse_voice(rest, n, &mut doc)?,
2689 b"effect" if v42 => parse_effect(rest, n, &mut doc)?,
2690 b"wheels" | b"curve" | b"lut" if v43 => parse_look(keyword, rest, n, dir, &mut doc)?,
2691 // After the lanes, which is where `clip_gain_lines` writes it: a line
2692 // names a clip, and a clip is declared by its lane's lines. Only audio
2693 // clips take one, the setter's own rule.
2694 b"lanepan" | b"clippan" if v50 => {
2695 let clip = keyword == b"clippan";
2696 let f = fields(rest, if clip { 4 } else { 3 }, if clip { "clippan" } else { "lanepan" }, n)?;
2697 if f[0] != b"audio" {
2698 return Err(format!("line {n}: pan names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2699 }
2700 let ord = number(f[1], n)?;
2701 let at = doc
2702 .lanes
2703 .iter()
2704 .enumerate()
2705 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2706 .nth(ord.saturating_sub(1) as usize)
2707 .map(|(at, _)| at)
2708 .ok_or_else(|| format!("line {n}: pan names a lane that is not there"))?;
2709 let pan = float(f[if clip { 3 } else { 2 }], n)?;
2710 if !(-1.0..=1.0).contains(&pan) {
2711 return Err(format!("line {n}: pan has a number out of its range").into());
2712 }
2713 if clip {
2714 let idx = number(f[2], n)? as usize;
2715 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;
2716 } else {
2717 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
2718 doc.flags[at].pan = pan;
2719 }
2720 }
2721 // After the lanes, which is where `pitch_lines` writes it, as `clippan` is.
2722 b"pitch" if v55 => {
2723 let f = fields(rest, 4, "pitch", n)?;
2724 if f[0] != b"audio" {
2725 return Err(format!("line {n}: pitch names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2726 }
2727 let ord = number(f[1], n)?;
2728 let at = doc
2729 .lanes
2730 .iter()
2731 .enumerate()
2732 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2733 .nth(ord.saturating_sub(1) as usize)
2734 .map(|(at, _)| at)
2735 .ok_or_else(|| format!("line {n}: pitch names a lane that is not there"))?;
2736 let idx = number(f[2], n)? as usize;
2737 let semitones = std::str::from_utf8(f[3]).ok().and_then(|s| s.parse::<i8>().ok());
2738 let semitones = match semitones {
2739 Some(v) if (crate::project::MIN_CLIP_PITCH..=crate::project::MAX_CLIP_PITCH).contains(&v) => v,
2740 _ => return Err(format!("line {n}: pitch has a number out of its range").into()),
2741 };
2742 doc.lanes[at]
2743 .1
2744 .get_mut(idx)
2745 .ok_or_else(|| format!("line {n}: pitch names clip {idx}, which the lane does not have"))?
2746 .pitch = semitones;
2747 }
2748 b"clipgain" if v27 => {
2749 let f = fields(rest, 4, "clipgain", n)?;
2750 if f[0] != b"audio" {
2751 return Err(format!(
2752 "line {n}: clipgain names {:?}, not an audio lane",
2753 String::from_utf8_lossy(f[0])
2754 )
2755 .into());
2756 }
2757 let ord = number(f[1], n)?;
2758 let at = doc
2759 .lanes
2760 .iter()
2761 .enumerate()
2762 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2763 .nth(ord.saturating_sub(1) as usize)
2764 .map(|(at, _)| at)
2765 .ok_or_else(|| format!("line {n}: clipgain names a lane that is not there"))?;
2766 let idx = number(f[2], n)? as usize;
2767 let db = float(f[3], n)?;
2768 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&db) {
2769 return Err(format!("line {n}: clipgain has a number out of its range").into());
2770 }
2771 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2772 format!("line {n}: clipgain names clip {idx}, which the lane does not have")
2773 })?;
2774 clip.gain_db = db;
2775 }
2776 // After the lanes, which is where `tkey_lines` writes it: a placement
2777 // key is source-ordered and unique by source frame, at most
2778 // `MAX_TRANSFORM_KEYS` of them, each a finite placement with an opacity
2779 // in `0..=1`. Only a video clip can carry them.
2780 b"tkeys" if v32 => {
2781 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2782 if f.len() < 4 {
2783 return Err(format!("line {n}: tkeys wants a clip and a key").into());
2784 }
2785 let lane_kind = match f[0] {
2786 b"video" => LaneKind::Video,
2787 other => {
2788 return Err(format!(
2789 "line {n}: tkeys names {:?}, not a video lane",
2790 String::from_utf8_lossy(other)
2791 )
2792 .into())
2793 }
2794 };
2795 let ord = number(f[1], n)?;
2796 let at = doc
2797 .lanes
2798 .iter()
2799 .enumerate()
2800 .filter(|(_, (k, _))| *k == lane_kind)
2801 .nth(ord.saturating_sub(1) as usize)
2802 .map(|(at, _)| at)
2803 .ok_or_else(|| format!("line {n}: tkeys names a lane that is not there"))?;
2804 let idx = number(f[2], n)? as usize;
2805 let points = &f[3..];
2806 if points.len() > MAX_TRANSFORM_KEYS {
2807 return Err(
2808 format!("line {n}: tkeys has more than {MAX_TRANSFORM_KEYS} keys").into(),
2809 );
2810 }
2811 let mut keys: Vec<TransformKey> = Vec::with_capacity(points.len());
2812 for point in points {
2813 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
2814 if parts.len() != 3 {
2815 return Err(format!("line {n}: tkeys key wants at:ease:values").into());
2816 }
2817 let ease = KeyEase::from_token(parts[1])
2818 .filter(|e| v39 || matches!(e, KeyEase::Linear | KeyEase::Ease))
2819 .ok_or_else(|| format!("line {n}: tkeys ease is lin, in, out, ease or hold"))?;
2820 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
2821 if v.len() != 9 {
2822 return Err(format!("line {n}: tkeys key wants 9 values").into());
2823 }
2824 let params = TransformParams {
2825 pos_x: float(v[0], n)?,
2826 pos_y: float(v[1], n)?,
2827 scale: float(v[2], n)?,
2828 rotate: float(v[3], n)?,
2829 crop_l: float(v[4], n)?,
2830 crop_r: float(v[5], n)?,
2831 crop_t: float(v[6], n)?,
2832 crop_b: float(v[7], n)?,
2833 opacity: float(v[8], n)?,
2834 };
2835 if !(0.0..=1.0).contains(&params.opacity) {
2836 return Err(format!("line {n}: tkeys opacity must be 0..=1").into());
2837 }
2838 let key = TransformKey {
2839 at: number(parts[0], n)?,
2840 params,
2841 ease,
2842 };
2843 if keys.last().is_some_and(|k| k.at >= key.at) {
2844 return Err(
2845 format!("line {n}: tkeys keys are not in source order").into()
2846 );
2847 }
2848 keys.push(key);
2849 }
2850 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2851 format!("line {n}: tkeys names clip {idx}, which the lane does not have")
2852 })?;
2853 clip.transform_keys = keys;
2854 }
2855 // After the lanes, which is where `opacity_key_lines` and `color_key_lines`
2856 // write them: a video clip's opacity (`0..=1`) and colour animation,
2857 // source-ordered and unique by source frame, at most `MAX_TRANSFORM_KEYS`
2858 // and `MAX_COLOR_KEYS` of them, each in range.
2859 // A stabilised video clip, named as an `okeys` line names its clip.
2860 b"deint" if v46 => {
2861 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2862 if f.len() != 4 || f[0] != b"video" {
2863 return Err(format!("line {n}: deint wants a video clip and a mode").into());
2864 }
2865 let ord = number(f[1], n)?;
2866 let at = doc
2867 .lanes
2868 .iter()
2869 .enumerate()
2870 .filter(|(_, (k, _))| *k == LaneKind::Video)
2871 .nth(ord.saturating_sub(1) as usize)
2872 .map(|(at, _)| at)
2873 .ok_or_else(|| format!("line {n}: deint names a lane that is not there"))?;
2874 let idx = number(f[2], n)? as usize;
2875 let mode = std::str::from_utf8(f[3])
2876 .ok()
2877 .and_then(Deinterlace::from_name)
2878 .ok_or_else(|| format!("line {n}: deint mode must be frame, field or off"))?;
2879 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2880 format!("line {n}: deint names clip {idx}, which the lane does not have")
2881 })?;
2882 clip.deinterlace = mode;
2883 }
2884 b"lanename" if v46 => {
2885 let mut parts = rest.splitn(3, |&b| b == b' ');
2886 let kind = match parts.next().unwrap_or_default() {
2887 b"video" => LaneKind::Video,
2888 b"audio" => LaneKind::Audio,
2889 b"sub" => LaneKind::Subtitle,
2890 other => {
2891 return Err(format!("line {n}: lanename names {:?}, not a lane kind", String::from_utf8_lossy(other)).into());
2892 }
2893 };
2894 let ord = number(parts.next().unwrap_or_default(), n)?;
2895 let at = doc
2896 .lanes
2897 .iter()
2898 .enumerate()
2899 .filter(|(_, (k, _))| *k == kind)
2900 .nth(ord.saturating_sub(1) as usize)
2901 .map(|(at, _)| at)
2902 .ok_or_else(|| format!("line {n}: lanename names a lane that is not there"))?;
2903 let name = unescape_text(parts.next().unwrap_or_default(), n)?;
2904 if name.is_empty() || name.chars().count() > crate::project::MAX_LANE_NAME_CHARS || name.chars().any(char::is_control) {
2905 return Err(format!("line {n}: a lane name is 1 to {} characters", crate::project::MAX_LANE_NAME_CHARS).into());
2906 }
2907 doc.names.resize(doc.lanes.len(), String::new());
2908 doc.names[at] = name;
2909 }
2910 b"stab" if v44 => {
2911 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2912 if f.len() != 5 || f[0] != b"video" {
2913 return Err(format!("line {n}: stab wants a video clip, a strength and a crop").into());
2914 }
2915 let ord = number(f[1], n)?;
2916 let at = doc
2917 .lanes
2918 .iter()
2919 .enumerate()
2920 .filter(|(_, (k, _))| *k == LaneKind::Video)
2921 .nth(ord.saturating_sub(1) as usize)
2922 .map(|(at, _)| at)
2923 .ok_or_else(|| format!("line {n}: stab names a lane that is not there"))?;
2924 let idx = number(f[2], n)? as usize;
2925 let strength = std::str::from_utf8(f[3])
2926 .ok()
2927 .and_then(|v| v.parse::<f32>().ok())
2928 .filter(|v| (0.0..=1.0).contains(v))
2929 .ok_or_else(|| format!("line {n}: stab strength must be a number from 0 to 1"))?;
2930 let crop = std::str::from_utf8(f[4])
2931 .ok()
2932 .and_then(crate::stabilise::Crop::from_name)
2933 .ok_or_else(|| format!("line {n}: stab crop must be zoom or full"))?;
2934 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2935 format!("line {n}: stab names clip {idx}, which the lane does not have")
2936 })?;
2937 clip.stabilise = Some(crate::stabilise::Stabilise::new(strength, crop));
2938 }
2939 b"mkeys" if v53 => {
2940 use crate::effects::{EffectKind, MaskKey};
2941 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2942 if f.len() < 5 || f[0] != b"video" {
2943 return Err(format!("line {n}: mkeys wants a video clip, a slot and a key").into());
2944 }
2945 let ord = number(f[1], n)?;
2946 let at = doc
2947 .lanes
2948 .iter()
2949 .enumerate()
2950 .filter(|(_, (k, _))| *k == LaneKind::Video)
2951 .nth(ord.saturating_sub(1) as usize)
2952 .map(|(at, _)| at)
2953 .ok_or_else(|| format!("line {n}: mkeys names a lane that is not there"))?;
2954 let idx = number(f[2], n)? as usize;
2955 let slot = number(f[3], n)? as usize;
2956 let points = &f[4..];
2957 if points.len() > MAX_TRANSFORM_KEYS {
2958 return Err(format!("line {n}: mkeys has more than {MAX_TRANSFORM_KEYS} keys").into());
2959 }
2960 let r = EffectKind::RectMask.params();
2961 let mut keys: Vec<MaskKey> = Vec::new();
2962 for point in points {
2963 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
2964 if parts.len() != 3 {
2965 return Err(format!("line {n}: mkeys key wants at:ease:values").into());
2966 }
2967 let at_frame = number(parts[0], n)?;
2968 let ease = KeyEase::from_token(parts[1])
2969 .ok_or_else(|| format!("line {n}: mkeys ease is lin, in, out, ease or hold"))?;
2970 if keys.last().is_some_and(|k| k.at >= at_frame) {
2971 return Err(format!("line {n}: mkeys keys are not in source order").into());
2972 }
2973 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
2974 if v.len() != 5 {
2975 return Err(format!("line {n}: mkeys key wants 5 values").into());
2976 }
2977 let mut val = [0.0f32; 5];
2978 for (i, (x, field)) in val.iter_mut().zip(&v).enumerate() {
2979 *x = float(field, n)?;
2980 if !(r[i].min..=r[i].max).contains(x) {
2981 return Err(format!("line {n}: mkeys {} is out of its range", r[i].name).into());
2982 }
2983 }
2984 let [x, y, width, height, feather] = val;
2985 keys.push(MaskKey { at: at_frame, x, y, width, height, feather, ease });
2986 }
2987 let clip = doc.lanes[at]
2988 .1
2989 .get_mut(idx)
2990 .ok_or_else(|| format!("line {n}: mkeys names clip {idx}, which the lane does not have"))?;
2991 let effect = clip
2992 .effects
2993 .get_mut(slot)
2994 .filter(|e| matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask))
2995 .ok_or_else(|| format!("line {n}: mkeys names an effect that is not a mask"))?;
2996 effect.keys = keys;
2997 }
2998 b"okeys" | b"ckeys" if v39 => {
2999 let colour = keyword == b"ckeys";
3000 let name = if colour { "ckeys" } else { "okeys" };
3001 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3002 if f.len() < 4 || f[0] != b"video" {
3003 return Err(format!("line {n}: {name} wants a video clip and a key").into());
3004 }
3005 let ord = number(f[1], n)?;
3006 let at = doc
3007 .lanes
3008 .iter()
3009 .enumerate()
3010 .filter(|(_, (k, _))| *k == LaneKind::Video)
3011 .nth(ord.saturating_sub(1) as usize)
3012 .map(|(at, _)| at)
3013 .ok_or_else(|| format!("line {n}: {name} names a lane that is not there"))?;
3014 let idx = number(f[2], n)? as usize;
3015 let points = &f[3..];
3016 let cap = if colour { MAX_COLOR_KEYS } else { MAX_TRANSFORM_KEYS };
3017 if points.len() > cap {
3018 return Err(format!("line {n}: {name} has more than {cap} keys").into());
3019 }
3020 let mut okeys: Vec<OpacityKey> = Vec::new();
3021 let mut ckeys: Vec<ColorKey> = Vec::new();
3022 for point in points {
3023 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3024 if parts.len() != 3 {
3025 return Err(format!("line {n}: {name} key wants at:ease:values").into());
3026 }
3027 let at_frame = number(parts[0], n)?;
3028 let ease = KeyEase::from_token(parts[1])
3029 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease or hold"))?;
3030 let last = if colour { ckeys.last().map(|k| k.at) } else { okeys.last().map(|k| k.at) };
3031 if last.is_some_and(|l| l >= at_frame) {
3032 return Err(format!("line {n}: {name} keys are not in source order").into());
3033 }
3034 if colour {
3035 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3036 if v.len() != 4 {
3037 return Err(format!("line {n}: ckeys key wants 4 values").into());
3038 }
3039 let params = ColorParams {
3040 brightness: float(v[0], n)?,
3041 contrast: float(v[1], n)?,
3042 saturation: float(v[2], n)?,
3043 tint: float(v[3], n)?,
3044 ..Default::default()
3045 };
3046 if !((-1.0..=1.0).contains(&params.brightness)
3047 && (0.0..=2.0).contains(&params.contrast)
3048 && (0.0..=2.0).contains(&params.saturation)
3049 && (-1.0..=1.0).contains(&params.tint))
3050 {
3051 return Err(format!("line {n}: ckeys has a value out of its range").into());
3052 }
3053 ckeys.push(ColorKey { at: at_frame, params, ease });
3054 } else {
3055 let opacity = float(parts[2], n)?;
3056 if !(0.0..=1.0).contains(&opacity) {
3057 return Err(format!("line {n}: okeys opacity must be 0..=1").into());
3058 }
3059 okeys.push(OpacityKey { at: at_frame, opacity, ease });
3060 }
3061 }
3062 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3063 format!("line {n}: {name} names clip {idx}, which the lane does not have")
3064 })?;
3065 if colour {
3066 clip.color_keys = ckeys;
3067 } else {
3068 clip.opacity_keys = okeys;
3069 }
3070 }
3071 // After the lanes, which is where `gain_key_lines` writes it: a line
3072 // names a clip, and a clip is declared by its lane's lines. Its points
3073 // are source-ordered and unique by source frame, as the setters keep
3074 // them, and at most `MAX_GAIN_KEYS` of them, each in range.
3075 b"gainkeys" if v28 => {
3076 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3077 if f.len() < 4 {
3078 return Err(format!("line {n}: gainkeys wants a clip and a point").into());
3079 }
3080 let kind = match f[0] {
3081 b"audio" => LaneKind::Audio,
3082 b"video" => LaneKind::Video,
3083 other => {
3084 return Err(format!(
3085 "line {n}: gainkeys names {:?}, not a lane kind",
3086 String::from_utf8_lossy(other)
3087 )
3088 .into());
3089 }
3090 };
3091 let ord = number(f[1], n)?;
3092 let at = doc
3093 .lanes
3094 .iter()
3095 .enumerate()
3096 .filter(|(_, (k, _))| *k == kind)
3097 .nth(ord.saturating_sub(1) as usize)
3098 .map(|(at, _)| at)
3099 .ok_or_else(|| format!("line {n}: gainkeys names a lane that is not there"))?;
3100 let idx = number(f[2], n)? as usize;
3101 let points = &f[3..];
3102 if points.len() > MAX_GAIN_KEYS {
3103 return Err(
3104 format!("line {n}: gainkeys has more than {MAX_GAIN_KEYS} points").into(),
3105 );
3106 }
3107 let mut keys = Vec::with_capacity(points.len());
3108 for point in points {
3109 let colon = point
3110 .iter()
3111 .position(|&b| b == b':')
3112 .ok_or_else(|| format!("line {n}: gainkeys point wants at:db"))?;
3113 let (a, d) = (&point[..colon], &point[colon + 1..]);
3114 // A v39 point may end in the ease of the segment that leaves it.
3115 let (d, ease) = match d.iter().position(|&b| b == b':') {
3116 Some(c) if v39 => (
3117 &d[..c],
3118 KeyEase::from_token(&d[c + 1..])
3119 .ok_or_else(|| format!("line {n}: gainkeys ease is lin, in, out, ease or hold"))?,
3120 ),
3121 _ => (d, KeyEase::Linear),
3122 };
3123 let key = GainKey {
3124 at: number(a, n)?,
3125 db: float(d, n)?,
3126 ease,
3127 };
3128 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&key.db) {
3129 return Err(format!("line {n}: gainkeys has a dB out of its range").into());
3130 }
3131 if keys.last().is_some_and(|k: &GainKey| k.at >= key.at) {
3132 return Err(
3133 format!("line {n}: gainkeys points are not in source order").into()
3134 );
3135 }
3136 keys.push(key);
3137 }
3138 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3139 format!("line {n}: gainkeys names clip {idx}, which the lane does not have")
3140 })?;
3141 clip.gain_keys = keys;
3142 }
3143 // After the lanes and the subtitle palette: a title names neither,
3144 // and its text is the rest of the line, so it is the ninth field.
3145 b"title" if v26 => {
3146 let f: Vec<&[u8]> = rest.splitn(9, |&b| b == b' ').collect();
3147 if f.len() != 9 {
3148 return Err(format!("line {n}: title wants 9 fields, found {}", f.len()).into());
3149 }
3150 let outline = match f[5] {
3151 b"none" => Outline::None,
3152 b"thin" => Outline::Thin,
3153 b"thick" => Outline::Thick,
3154 other => {
3155 return Err(format!(
3156 "line {n}: title outline {:?} is none, thin or thick",
3157 String::from_utf8_lossy(other)
3158 )
3159 .into());
3160 }
3161 };
3162 let boxed = match f[6] {
3163 b"0" => false,
3164 b"1" => true,
3165 other => {
3166 return Err(format!(
3167 "line {n}: title boxed {:?} is 0 or 1",
3168 String::from_utf8_lossy(other)
3169 )
3170 .into());
3171 }
3172 };
3173 let place = match f[7] {
3174 b"bottom" => Place::Bottom,
3175 b"top" => Place::Top,
3176 b"centre" => Place::Centre,
3177 other => {
3178 return Err(format!(
3179 "line {n}: title place {:?} is bottom, top or centre",
3180 String::from_utf8_lossy(other)
3181 )
3182 .into());
3183 }
3184 };
3185 let title = Title {
3186 start: number(f[0], n)?,
3187 frames: number(f[1], n)?,
3188 text: unescape_text(f[8], n)?,
3189 style: TextStyle {
3190 size: number(f[4], n)?,
3191 outline,
3192 boxed,
3193 place,
3194 ..TextStyle::default()
3195 },
3196 fade_in: number(f[2], n)?,
3197 fade_out: number(f[3], n)?,
3198 in_anim: TitleAnim::None,
3199 out_anim: TitleAnim::None,
3200 anim_frames: 0,
3201 };
3202 check_title(&title).map_err(|e| format!("line {n}: {e}"))?;
3203 doc.titles.push(title);
3204 }
3205 // A chapter is a frame and a name: the name is the rest of the line, escaped
3206 // as a `cue` line's is. Written in frame order, one per frame.
3207 // A clip's speed ramp, as `speedkeys` lines, after the lanes they name.
3208 // Its keys are clip-relative and sorted, at most `MAX_SPEED_KEYS` of them, each
3209 // speed in range; the clip's footprint grows with the ramp, so the lane is
3210 // checked again here, where the ramp lands.
3211 b"speedkeys" if v35 => {
3212 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3213 if f.len() < 4 {
3214 return Err(format!("line {n}: speedkeys wants a clip and a point").into());
3215 }
3216 let kind = match f[0] {
3217 b"audio" => LaneKind::Audio,
3218 b"video" => LaneKind::Video,
3219 other => {
3220 return Err(format!(
3221 "line {n}: speedkeys names {:?}, not a lane kind",
3222 String::from_utf8_lossy(other)
3223 )
3224 .into());
3225 }
3226 };
3227 let ord = number(f[1], n)?;
3228 let at = doc
3229 .lanes
3230 .iter()
3231 .enumerate()
3232 .filter(|(_, (k, _))| *k == kind)
3233 .nth(ord.saturating_sub(1) as usize)
3234 .map(|(at, _)| at)
3235 .ok_or_else(|| format!("line {n}: speedkeys names a lane that is not there"))?;
3236 let idx = number(f[2], n)? as usize;
3237 let points = &f[3..];
3238 if points.len() > MAX_SPEED_KEYS {
3239 return Err(format!("line {n}: speedkeys has more than {MAX_SPEED_KEYS} points").into());
3240 }
3241 let mut keys = Vec::with_capacity(points.len());
3242 for point in points {
3243 let colon = point
3244 .iter()
3245 .position(|&b| b == b':')
3246 .ok_or_else(|| format!("line {n}: speedkeys point wants at:permille"))?;
3247 let (a, p) = (&point[..colon], &point[colon + 1..]);
3248 let permille = number(p, n)?;
3249 if permille < u32::from(Speed::MIN.permille())
3250 || permille > u32::from(Speed::MAX.permille())
3251 {
3252 return Err(format!("line {n}: speedkeys speed {permille} is out of range").into());
3253 }
3254 let key = SpeedKey {
3255 at: number(a, n)?,
3256 speed: Speed::from_permille(permille as u16),
3257 };
3258 if keys.last().is_some_and(|k: &SpeedKey| k.at >= key.at) {
3259 return Err(format!("line {n}: speedkeys points are not in frame order").into());
3260 }
3261 keys.push(key);
3262 }
3263 let lane = &mut doc.lanes[at].1;
3264 let clip = lane.get_mut(idx).ok_or_else(|| {
3265 format!("line {n}: speedkeys names clip {idx}, which the lane does not have")
3266 })?;
3267 clip.speed_keys = keys;
3268 let end = clip.start.checked_add(clip.frames()).ok_or_else(|| {
3269 format!("line {n}: speed ramp runs past the last frame there is")
3270 })?;
3271 if lane.get(idx + 1).is_some_and(|next| next.start < end) {
3272 return Err(format!("line {n}: speed ramp runs into the next clip on its lane").into());
3273 }
3274 }
3275 // How a clip's transition is drawn, after the lanes it names.
3276 b"transition" if v37 => {
3277 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3278 if f.len() != 4 {
3279 return Err(format!("line {n}: transition wants a clip and a kind").into());
3280 }
3281 let kind = match f[0] {
3282 b"audio" => LaneKind::Audio,
3283 b"video" => LaneKind::Video,
3284 other => {
3285 return Err(format!(
3286 "line {n}: transition names {:?}, not a lane kind",
3287 String::from_utf8_lossy(other)
3288 )
3289 .into());
3290 }
3291 };
3292 let ord = number(f[1], n)?;
3293 let at = doc
3294 .lanes
3295 .iter()
3296 .enumerate()
3297 .filter(|(_, (k, _))| *k == kind)
3298 .nth(ord.saturating_sub(1) as usize)
3299 .map(|(at, _)| at)
3300 .ok_or_else(|| format!("line {n}: transition names a lane that is not there"))?;
3301 let idx = number(f[2], n)? as usize;
3302 let name = String::from_utf8_lossy(f[3]);
3303 let kind = TransitionKind::parse(&name)
3304 .ok_or_else(|| format!("line {n}: transition kind {name:?} is not one"))?;
3305 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3306 format!("line {n}: transition names clip {idx}, which the lane does not have")
3307 })?;
3308 clip.transition_kind = kind;
3309 }
3310 // A reversed clip: named like a `speedkeys` line names its clip. The
3311 // window, speed and ramp are the clip's own lines; this is the direction.
3312 b"reverse" if v38 => {
3313 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3314 if f.len() != 3 {
3315 return Err(format!("line {n}: reverse wants a lane and a clip").into());
3316 }
3317 let kind = match f[0] {
3318 b"audio" => LaneKind::Audio,
3319 b"video" => LaneKind::Video,
3320 other => {
3321 return Err(format!(
3322 "line {n}: reverse names {:?}, not a lane kind",
3323 String::from_utf8_lossy(other)
3324 )
3325 .into());
3326 }
3327 };
3328 let ord = number(f[1], n)?;
3329 let at = doc
3330 .lanes
3331 .iter()
3332 .enumerate()
3333 .filter(|(_, (k, _))| *k == kind)
3334 .nth(ord.saturating_sub(1) as usize)
3335 .map(|(at, _)| at)
3336 .ok_or_else(|| format!("line {n}: reverse names a lane that is not there"))?;
3337 let idx = number(f[2], n)? as usize;
3338 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3339 format!("line {n}: reverse names clip {idx}, which the lane does not have")
3340 })?;
3341 clip.reversed = true;
3342 }
3343 b"angle" if v47 => {
3344 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3345 if f.len() != 5 {
3346 return Err(format!("line {n}: angle wants a lane, a clip, a picture angle and a sound angle").into());
3347 }
3348 let kind = match f[0] {
3349 b"audio" => LaneKind::Audio,
3350 b"video" => LaneKind::Video,
3351 _ => return Err(format!("line {n}: angle names a lane kind that is not video or audio").into()),
3352 };
3353 let ord = number(f[1], n)?;
3354 let at = doc
3355 .lanes
3356 .iter()
3357 .enumerate()
3358 .filter(|(_, (k, _))| *k == kind)
3359 .nth(ord.saturating_sub(1) as usize)
3360 .map(|(at, _)| at)
3361 .ok_or_else(|| format!("line {n}: angle names a lane that is not there"))?;
3362 let idx = number(f[2], n)? as usize;
3363 let one_based = |f: &[u8]| -> crate::Result<u8> {
3364 let v = number(f, n)?;
3365 u8::try_from(v.wrapping_sub(1))
3366 .ok()
3367 .filter(|a| usize::from(*a) < crate::project::MAX_ANGLES)
3368 .ok_or_else(|| format!("line {n}: an angle is a number from 1 to {}", crate::project::MAX_ANGLES).into())
3369 };
3370 let video = one_based(f[3])?;
3371 let audio = if f[4] == b"-" { None } else { Some(one_based(f[4])?) };
3372 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3373 format!("line {n}: angle names clip {idx}, which the lane does not have")
3374 })?;
3375 clip.angle = crate::project::Angle { video, audio };
3376 }
3377 // A title's look: which title (by its position in the list), where its block sits,
3378 // how its lines line up, its weight, its colour and its box colour.
3379 b"titlestyle" if v49 => {
3380 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3381 if f.len() != 6 {
3382 return Err(format!("line {n}: titlestyle wants a title, a position, an alignment, a weight and two colours").into());
3383 }
3384 let idx = number(f[0], n)? as usize;
3385 let side = |b: &[u8], what: &str| -> crate::Result<u8> {
3386 match b {
3387 b"centre" => Ok(0),
3388 b"left" => Ok(1),
3389 b"right" => Ok(2),
3390 other => Err(format!("line {n}: title {what} {:?} is centre, left or right", String::from_utf8_lossy(other)).into()),
3391 }
3392 };
3393 let hplace = match side(f[1], "position")? {
3394 1 => HPlace::Left,
3395 2 => HPlace::Right,
3396 _ => HPlace::Centre,
3397 };
3398 let align = match side(f[2], "alignment")? {
3399 1 => Align::Left,
3400 2 => Align::Right,
3401 _ => Align::Centre,
3402 };
3403 let weight = match f[3] {
3404 b"regular" => Weight::Regular,
3405 b"bold" => Weight::Bold,
3406 other => return Err(format!("line {n}: title weight {:?} is regular or bold", String::from_utf8_lossy(other)).into()),
3407 };
3408 let hex = |b: &[u8], len: usize| -> crate::Result<Vec<u8>> {
3409 let ok = b.len() == len * 2 && b.iter().all(u8::is_ascii_hexdigit);
3410 if !ok {
3411 return Err(format!("line {n}: a title colour is {} hex digits", len * 2).into());
3412 }
3413 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())
3414 };
3415 let c = hex(f[4], 3)?;
3416 let bc = hex(f[5], 4)?;
3417 let title = doc
3418 .titles
3419 .get_mut(idx)
3420 .ok_or_else(|| format!("line {n}: titlestyle names title {idx}, which the file does not have"))?;
3421 title.style.hplace = hplace;
3422 title.style.align = align;
3423 title.style.weight = weight;
3424 title.style.ink = [c[0], c[1], c[2]];
3425 title.style.box_color = [bc[0], bc[1], bc[2], bc[3]];
3426 }
3427 // A title's entrance and exit: which title (by its place in the list), the two animations
3428 // and how many frames each takes.
3429 b"titleanim" if v54 => {
3430 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3431 if f.len() != 4 {
3432 return Err(format!("line {n}: titleanim wants a title, an entrance, an exit and a length").into());
3433 }
3434 let idx = number(f[0], n)? as usize;
3435 let anim = |b: &[u8]| {
3436 let name = String::from_utf8_lossy(b).into_owned();
3437 TitleAnim::from_name(&name).ok_or_else(|| format!("line {n}: title animation {name:?} is not one of the known ones"))
3438 };
3439 let (in_anim, out_anim) = (anim(f[1])?, anim(f[2])?);
3440 let anim_frames = number(f[3], n)?;
3441 let title = doc
3442 .titles
3443 .get_mut(idx)
3444 .ok_or_else(|| format!("line {n}: titleanim names title {idx}, which the file does not have"))?;
3445 title.in_anim = in_anim;
3446 title.out_anim = out_anim;
3447 title.anim_frames = anim_frames;
3448 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3449 }
3450 b"mark" if v48 => {
3451 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3452 if f.len() != 5 {
3453 return Err(format!("line {n}: mark wants a lane, a clip, a label and on or off").into());
3454 }
3455 let kind = match f[0] {
3456 b"audio" => LaneKind::Audio,
3457 b"video" => LaneKind::Video,
3458 _ => return Err(format!("line {n}: mark names a lane kind that is not video or audio").into()),
3459 };
3460 let ord = number(f[1], n)?;
3461 let at = doc
3462 .lanes
3463 .iter()
3464 .enumerate()
3465 .filter(|(_, (k, _))| *k == kind)
3466 .nth(ord.saturating_sub(1) as usize)
3467 .map(|(at, _)| at)
3468 .ok_or_else(|| format!("line {n}: mark names a lane that is not there"))?;
3469 let idx = number(f[2], n)? as usize;
3470 let label = u8::try_from(number(f[3], n)?)
3471 .ok()
3472 .filter(|l| *l <= crate::project::LABEL_COUNT)
3473 .ok_or_else(|| format!("line {n}: a label is a number from 0 to {}", crate::project::LABEL_COUNT))?;
3474 let off = match f[4] {
3475 b"on" => false,
3476 b"off" => true,
3477 _ => return Err(format!("line {n}: mark ends with on or off").into()),
3478 };
3479 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3480 format!("line {n}: mark names clip {idx}, which the lane does not have")
3481 })?;
3482 clip.mark = crate::project::ClipMark { label, off };
3483 }
3484 // The library (v51): `bin <id> <parent> <name>`, then `srcbin <source> <bin>` and
3485 // `srcfav <source>` for the sources that are filed or starred.
3486 // The project notes (v52): one `notes` line, its text escaped as a cue's is, so a
3487 // note of several lines is one line in the file.
3488 b"notes" if v52 => {
3489 if !doc.notes.is_empty() {
3490 return Err(format!("line {n}: notes is given twice").into());
3491 }
3492 doc.notes = unescape_text(rest, n)?;
3493 }
3494 // The length a still is placed at (v52), in seconds, within the range the editor allows.
3495 b"still" if v52 => {
3496 let f = fields(rest, 1, "still", n)?;
3497 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"))?;
3498 if !(STILL_MIN_SECS..=STILL_MAX_SECS).contains(&secs) {
3499 return Err(format!("line {n}: a still is {STILL_MIN_SECS} to {STILL_MAX_SECS} s long, not {secs}").into());
3500 }
3501 doc.still_secs = Some(secs);
3502 }
3503 b"bin" if v51 => {
3504 let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect();
3505 if f.len() != 3 {
3506 return Err(format!("line {n}: bin wants an id, a parent and a name").into());
3507 }
3508 let id = number(f[0], n)?;
3509 let parent = number(f[1], n)?;
3510 let name = unescape_text(f[2], n)?;
3511 if id == 0 || doc.bins.iter().any(|b| b.id == id) {
3512 return Err(format!("line {n}: bin {id} is not a new id").into());
3513 }
3514 if parent != 0 && !doc.bins.iter().any(|b| b.id == parent && b.parent == 0) {
3515 return Err(format!("line {n}: bin {id} is inside bin {parent}, which is not a top-level bin before it").into());
3516 }
3517 let name = crate::project::clean_bin_name(&name).map_err(|e| format!("line {n}: {e}"))?;
3518 if doc.bins.iter().any(|b| b.parent == parent && b.name.eq_ignore_ascii_case(&name)) {
3519 return Err(format!("line {n}: two bins named {name} in one place").into());
3520 }
3521 if doc.bins.len() >= crate::project::MAX_BINS {
3522 return Err(format!("line {n}: a project holds at most {} bins", crate::project::MAX_BINS).into());
3523 }
3524 doc.bins.push(crate::project::Bin { id, parent, name });
3525 }
3526 b"srcbin" if v51 => {
3527 let f = fields(rest, 2, "srcbin", n)?;
3528 let (src, bin) = (number(f[0], n)? as usize, number(f[1], n)?);
3529 if !doc.bins.iter().any(|b| b.id == bin) {
3530 return Err(format!("line {n}: srcbin names bin {bin}, which is not defined before it").into());
3531 }
3532 doc.sources
3533 .get_mut(src)
3534 .ok_or_else(|| format!("line {n}: srcbin names source {src}, which the file does not have"))?
3535 .bin = bin;
3536 }
3537 b"srcfav" if v51 => {
3538 let f = fields(rest, 1, "srcfav", n)?;
3539 let src = number(f[0], n)? as usize;
3540 doc.sources
3541 .get_mut(src)
3542 .ok_or_else(|| format!("line {n}: srcfav names source {src}, which the file does not have"))?
3543 .fav = true;
3544 }
3545 b"mcam" if v47 => {
3546 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
3547 let id = number(id, n)?;
3548 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
3549 doc.mcams.push((id, name));
3550 }
3551 b"chapter" if v34 => {
3552 let mut fields = rest.splitn(2, |&b| b == b' ');
3553 let frame = number(fields.next().unwrap_or_default(), n)?;
3554 let title = unescape_text(fields.next().unwrap_or_default(), n)?;
3555 let chapter = Chapter { frame, title };
3556 check_chapter(&chapter).map_err(|e| format!("line {n}: {e}"))?;
3557 if doc.chapters.last().is_some_and(|c| c.frame >= frame) {
3558 return Err(format!("line {n}: chapter at frame {frame} is not after the one before it").into());
3559 }
3560 if doc.chapters.len() >= MAX_LIST_ENTRIES {
3561 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} chapters").into());
3562 }
3563 doc.chapters.push(chapter);
3564 }
3565 b"marker" if v36 => {
3566 let f: Vec<&[u8]> = rest.splitn(4, |&b| b == b' ').collect();
3567 if f.len() < 4 {
3568 return Err(format!("line {n}: marker wants a frame, a length, a colour and a name").into());
3569 }
3570 let color = std::str::from_utf8(f[2])
3571 .ok()
3572 .and_then(MarkerColor::from_name)
3573 .ok_or_else(|| format!("line {n}: marker names {:?}, not a colour", String::from_utf8_lossy(f[2])))?;
3574 let marker = Marker {
3575 frame: number(f[0], n)?,
3576 length: number(f[1], n)?,
3577 name: unescape_text(f[3], n)?,
3578 note: String::new(),
3579 color,
3580 };
3581 check_marker(&marker).map_err(|e| format!("line {n}: {e}"))?;
3582 if doc.markers.last().is_some_and(|m| m.frame > marker.frame) {
3583 return Err(format!("line {n}: marker at frame {} is before the one above it", marker.frame).into());
3584 }
3585 if doc.markers.len() >= MAX_LIST_ENTRIES {
3586 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} markers").into());
3587 }
3588 doc.markers.push(marker);
3589 }
3590 b"cuewords" if v40 => {
3591 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3592 if f.len() < 5 || !(f.len() - 2).is_multiple_of(3) {
3593 return Err(format!("line {n}: cuewords wants a track, a cue and whole (start, end, word) triples").into());
3594 }
3595 if (f.len() - 2) / 3 > MAX_CUE_WORDS {
3596 return Err(format!("line {n}: cuewords carries more than {MAX_CUE_WORDS} words").into());
3597 }
3598 let track = number(f[0], n)? as usize;
3599 if track >= doc.subtitles.len() {
3600 return Err(format!("line {n}: cuewords names subtitle track {track} of {}", doc.subtitles.len()).into());
3601 }
3602 let mut words = Vec::new();
3603 for w in f[2..].chunks(3) {
3604 let time = |b: &[u8]| -> crate::Result<i64> {
3605 std::str::from_utf8(b)
3606 .ok()
3607 .and_then(|t| t.parse::<i64>().ok())
3608 .ok_or_else(|| format!("line {n}: cuewords time is not a number").into())
3609 };
3610 words.push((time(w[0])?, time(w[1])?, unescape_text(w[2], n)?));
3611 }
3612 doc.cue_words.push((track, number(f[1], n)? as usize, words));
3613 }
3614 b"capstyle" if v40 => {
3615 let f: Vec<&str> = fields(rest, 5, "capstyle", n)?
3616 .into_iter()
3617 .map(|b| std::str::from_utf8(b).unwrap_or(""))
3618 .collect();
3619 let anim = CaptionAnim::from_name(f[0])
3620 .ok_or_else(|| format!("line {n}: capstyle names {:?}, not an animation", f[0]))?;
3621 let hex = f[1];
3622 let rgb = (hex.len() == 6)
3623 .then(|| u32::from_str_radix(hex, 16).ok())
3624 .flatten()
3625 .ok_or_else(|| format!("line {n}: capstyle colour {hex:?} is not six hex digits"))?;
3626 let flag = |s: &str| match s {
3627 "0" => Ok(false),
3628 "1" => Ok(true),
3629 other => Err(format!("line {n}: capstyle flag {other:?} is not 0 or 1")),
3630 };
3631 let words_per_line: u8 = f[4]
3632 .parse()
3633 .ok()
3634 .filter(|&w| w <= MAX_WORDS_PER_LINE)
3635 .ok_or_else(|| format!("line {n}: capstyle words per line {:?} is not 0 to {MAX_WORDS_PER_LINE}", f[4]))?;
3636 doc.caption_style = CaptionStyle {
3637 anim,
3638 highlight: [(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8],
3639 hl_box: flag(f[2])?,
3640 uppercase: flag(f[3])?,
3641 words_per_line,
3642 };
3643 }
3644 b"marknote" if v36 => {
3645 let mut fields = rest.splitn(2, |&b| b == b' ');
3646 let idx = number(fields.next().unwrap_or_default(), n)? as usize;
3647 let note = unescape_text(fields.next().unwrap_or_default(), n)?;
3648 let marker = doc
3649 .markers
3650 .get_mut(idx)
3651 .ok_or_else(|| format!("line {n}: marknote names marker {idx}, which the file does not have"))?;
3652 marker.note = note;
3653 check_marker(marker).map_err(|e| format!("line {n}: {e}"))?;
3654 }
3655 b"flags" if v24 => {
3656 let mut words = rest.split(|&b| b == b' ');
3657 let kind = match words.next().unwrap_or_default() {
3658 b"video" => LaneKind::Video,
3659 b"audio" => LaneKind::Audio,
3660 b"sub" => LaneKind::Subtitle,
3661 other => {
3662 return Err(format!(
3663 "line {n}: flags names {:?}, not a lane kind",
3664 String::from_utf8_lossy(other)
3665 )
3666 .into());
3667 }
3668 };
3669 let ord = number(words.next().unwrap_or_default(), n)?;
3670 let at = doc
3671 .lanes
3672 .iter()
3673 .enumerate()
3674 .filter(|(_, (k, _))| *k == kind)
3675 .nth(ord.saturating_sub(1) as usize)
3676 .map(|(at, _)| at)
3677 .ok_or_else(|| format!("line {n}: flags names a lane that is not there"))?;
3678 let mut set = LaneFlags::default();
3679 let mut any = false;
3680 for word in words {
3681 let (slot, name) = match word {
3682 b"hidden" if kind != LaneKind::Audio => (&mut set.hidden, "hidden"),
3683 b"muted" if kind == LaneKind::Audio => (&mut set.muted, "muted"),
3684 b"locked" => (&mut set.locked, "locked"),
3685 other => {
3686 return Err(format!(
3687 "line {n}: flags {:?} cannot be set on that lane",
3688 String::from_utf8_lossy(other)
3689 )
3690 .into());
3691 }
3692 };
3693 if std::mem::replace(slot, true) {
3694 return Err(format!("line {n}: flags names {name} twice").into());
3695 }
3696 any = true;
3697 }
3698 if !any {
3699 return Err(format!("line {n}: flags names no switch").into());
3700 }
3701 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
3702 set.pan = doc.flags[at].pan;
3703 doc.flags[at] = set;
3704 }
3705 // Beside the source lines and read the same way: fields first, the
3706 // path last, because a path runs to the end of the line.
3707 b"subtitle" if v10 => {
3708 let at = rest
3709 .iter()
3710 .position(|&b| b == b' ')
3711 .ok_or_else(|| format!("line {n}: subtitle without a path"))?;
3712 let track = match &rest[..at] {
3713 b"-" => None,
3714 field => Some(u64::from(number(field, n)?)),
3715 };
3716 let path = unescape(&rest[at + 1..], n)?;
3717 if path.as_os_str().is_empty() {
3718 return Err(format!("line {n}: subtitle without a path").into());
3719 }
3720 doc.subtitles.push((
3721 // Relative to the project file, as a source path is.
3722 if path.is_absolute() {
3723 path
3724 } else {
3725 dir.join(path)
3726 },
3727 track,
3728 ));
3729 }
3730 // After the subtitle lines, which declare the tracks it names. The
3731 // text is the rest of the line, so it may hold spaces: the track and
3732 // the cue are the two fields before it.
3733 b"cue" if v24 => {
3734 let mut fields = rest.splitn(3, |&b| b == b' ');
3735 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3736 let cue = number(
3737 fields
3738 .next()
3739 .ok_or_else(|| format!("line {n}: cue without a cue index"))?,
3740 n,
3741 )? as usize;
3742 let text = fields
3743 .next()
3744 .ok_or_else(|| format!("line {n}: cue without its text"))?;
3745 if track >= doc.subtitles.len() {
3746 return Err(format!(
3747 "line {n}: cue names subtitle track {track} of {}",
3748 doc.subtitles.len()
3749 )
3750 .into());
3751 }
3752 doc.cue_edits.push((track, cue, unescape_text(text, n)?));
3753 }
3754 // After the subtitle lines, which declare the tracks it names: the
3755 // track, then the language as the rest of the line, escaped as a cue's
3756 // text is. A language is one field to a reader, not a list of words.
3757 b"sublang" if v33 => {
3758 let mut fields = rest.splitn(2, |&b| b == b' ');
3759 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3760 let lang = fields
3761 .next()
3762 .ok_or_else(|| format!("line {n}: sublang without a language"))?;
3763 if track >= doc.subtitles.len() {
3764 return Err(format!(
3765 "line {n}: sublang names subtitle track {track} of {}",
3766 doc.subtitles.len()
3767 )
3768 .into());
3769 }
3770 let lang = unescape_text(lang, n)?;
3771 if lang.is_empty() {
3772 return Err(format!("line {n}: sublang without a language").into());
3773 }
3774 doc.sub_langs.push((track, lang));
3775 }
3776 // After the subtitle lines, which declare the tracks it names, and
3777 // the `cue` lines, so an added cue lands after the file's own cues.
3778 // The text is the rest of the line, as a `cue` line's is.
3779 b"cueadd" if v29 => {
3780 let mut fields = rest.splitn(4, |&b| b == b' ');
3781 let mut field = |what: &str| fields.next().ok_or_else(|| format!("line {n}: cueadd without {what}"));
3782 let track = number(field("a track")?, n)? as usize;
3783 let start_us = number64(field("a start")?, n)? as i64;
3784 let end_us = number64(field("an end")?, n)? as i64;
3785 let text = field("its text")?;
3786 if track >= doc.subtitles.len() {
3787 return Err(format!(
3788 "line {n}: cueadd names subtitle track {track} of {}",
3789 doc.subtitles.len()
3790 )
3791 .into());
3792 }
3793 if end_us <= start_us {
3794 return Err(format!("line {n}: cueadd ends at {end_us} µs, not after its start {start_us} µs").into());
3795 }
3796 doc.cue_adds.push(crate::project::AddedCue {
3797 track,
3798 start_us,
3799 end_us,
3800 text: unescape_text(text, n)?,
3801 });
3802 }
3803 b"source" => {
3804 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3805 return Err(format!("line {n}: source after a clip").into());
3806 }
3807 // The stream comes first and the path is everything after it,
3808 // spaces and all; an older dialect wrote no stream and meant 0.
3809 let (audio_stream, rest) = if streamless {
3810 (0, rest)
3811 } else {
3812 // No space at all still has to reach `number`, so a v2 line
3813 // in a v3 file is refused as the missing field it is rather
3814 // than as a missing path.
3815 let at = rest.iter().position(|&b| b == b' ');
3816 (
3817 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
3818 &rest[at.map_or(rest.len(), |at| at + 1)..],
3819 )
3820 };
3821 if rest.is_empty() {
3822 return Err(format!("line {n}: source without a path").into());
3823 }
3824 let path = unescape(rest, n)?;
3825 // Relative means "next to the project file", which is what
3826 // makes a whole folder relocatable.
3827 doc.sources.push(Source {
3828 path: if path.is_absolute() {
3829 path
3830 } else {
3831 dir.join(path)
3832 },
3833 audio_stream,
3834 ..Default::default()
3835 });
3836 }
3837 b"eq" if v5 => {
3838 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3839 return Err(format!("line {n}: eq after a clip").into());
3840 }
3841 // A bare `eq` is the empty cascade -- a setting that moves
3842 // nothing, which is not the same thing as no setting at all.
3843 if rest.split(|&b| b == b' ').count() > MAX_EQ_BANDS {
3844 return Err(format!("line {n}: an equalizer holds at most {MAX_EQ_BANDS} bands").into());
3845 }
3846 let bands = match rest.is_empty() {
3847 true => Vec::new(),
3848 false => rest
3849 .split(|&b| b == b' ')
3850 .map(|field| band(field, n))
3851 .collect::<crate::Result<Vec<Band>>>()?,
3852 };
3853 doc.eq.push(EqParams { bands });
3854 }
3855 b"color" if v6 => {
3856 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3857 return Err(format!("line {n}: color after a clip").into());
3858 }
3859 let f = fields(rest, 1, "color", n)?;
3860 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
3861 if parts.len() != 4 {
3862 return Err(
3863 format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
3864 );
3865 }
3866 doc.color.push(ColorParams {
3867 brightness: float(parts[0], n)?,
3868 contrast: float(parts[1], n)?,
3869 saturation: float(parts[2], n)?,
3870 tint: float(parts[3], n)?,
3871 ..Default::default()
3872 });
3873 }
3874 b"transform" if v20 => {
3875 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3876 return Err(format!("line {n}: transform after a clip").into());
3877 }
3878 let f = fields(rest, 1, "transform", n)?;
3879 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
3880 // v31 may add the opacity as a ninth field; an earlier dialect
3881 // has eight, and a ninth there is a line it never wrote.
3882 let want = if v31 { 8..=9 } else { 8..=8 };
3883 if !want.contains(&parts.len()) {
3884 return Err(format!(
3885 "line {n}: transform wants 8 fields, found {}",
3886 parts.len()
3887 )
3888 .into());
3889 }
3890 let opacity = match parts.get(8) {
3891 Some(p) => float(p, n)?,
3892 None => 1.0,
3893 };
3894 if !(0.0..=1.0).contains(&opacity) {
3895 return Err(format!("line {n}: transform opacity must be 0..=1").into());
3896 }
3897 doc.transform.push(TransformParams {
3898 pos_x: float(parts[0], n)?,
3899 pos_y: float(parts[1], n)?,
3900 scale: float(parts[2], n)?,
3901 rotate: float(parts[3], n)?,
3902 crop_l: float(parts[4], n)?,
3903 crop_r: float(parts[5], n)?,
3904 crop_t: float(parts[6], n)?,
3905 crop_b: float(parts[7], n)?,
3906 opacity,
3907 });
3908 }
3909 // v1: one lane, no placement, no groups. Every clip becomes one
3910 // grouped video+audio pair laid where the queue reached, which is
3911 // what the file always meant.
3912 b"clip" if v1 => {
3913 let f = fields(rest, 3, "clip", n)?;
3914 let clip = check(
3915 Clip {
3916 speed_keys: Vec::new(),
3917 reversed: false,
3918 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
3919 angle: Default::default(),
3920 fade_in: 0,
3921 fade_out: 0,
3922 transition_out: 0,
3923 transition_kind: Default::default(),
3924 visualizer: 0,
3925 viz_paint: 0,
3926 gain_db: 0.0,
3927 gain_keys: Vec::new(),
3928 pan: 0,
3929 transform_keys: Vec::new(),
3930 opacity_keys: Vec::new(),
3931 color_keys: Vec::new(),
3932 effects: Vec::new(),
3933 start: queued,
3934 in_frame: number(f[0], n)?,
3935 out_frame: number(f[1], n)?,
3936 source: number(f[2], n)? as usize,
3937 link: Some(doc.lanes[0].1.len() as u32),
3938 eq: None,
3939 color: None,
3940 transform: None,
3941 fit: FitPolicy::default(),
3942 speed: Speed::NORMAL,
3943 pitch: 0,
3944 },
3945 &doc,
3946 n,
3947 )?;
3948 queued = clip.end();
3949 doc.lanes[0].1.push(clip.clone());
3950 doc.lanes[1].1.push(clip);
3951 }
3952 // A lane line like the two below it, in its place among them, and
3953 // read into `subs` rather than into the clips: the lane holds
3954 // words, and no media path may ever meet one
3955 // ([`crate::project::LaneKind::Subtitle`]).
3956 b"sub" if v15 => {
3957 let at = rest.iter().position(|&b| b == b' ');
3958 let ord = number(&rest[..at.unwrap_or(rest.len())], n)?;
3959 let rest = &rest[at.map_or(rest.len(), |at| at + 1)..];
3960 let at = lane_of(&mut doc.lanes, LaneKind::Subtitle, ord, n)?;
3961 doc.subs.resize(doc.lanes.len(), Vec::new());
3962 // The bare line is the empty lane's whole existence, exactly as
3963 // it is for a video one.
3964 if rest.is_empty() {
3965 continue;
3966 }
3967 // v16 on may carry a sixth field -- the caption's group id, the
3968 // same spelling a clip's link takes (`-` for none). A v15 line
3969 // stops at five, and a sixth field in one is a file this parser
3970 // never wrote.
3971 let all: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3972 let ok = all.len() == 5 || (v16 && all.len() == 6);
3973 if !ok {
3974 return Err(format!(
3975 "line {n}: sub wants {} fields, found {}",
3976 if v16 { "5 or 6" } else { "5" },
3977 all.len()
3978 )
3979 .into());
3980 }
3981 let link = match all.get(5) {
3982 None => None,
3983 Some(f) if *f == b"-" => None,
3984 Some(f) => Some(number(f, n)?),
3985 };
3986 let f = &all;
3987 let sub = SubClip {
3988 start: number(f[0], n)?,
3989 frames: number(f[1], n)?,
3990 track: number(f[2], n)? as usize,
3991 in_us: micros(f[3], n)?,
3992 out_us: micros(f[4], n)?,
3993 link,
3994 };
3995 // The never-empty invariant at both clocks, which is what
3996 // [`crate::Project::place_sub`] refuses on the live timeline.
3997 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
3998 return Err(format!(
3999 "line {n}: caption at {} is empty: {} frames of [{}, {})",
4000 sub.start, sub.frames, sub.in_us, sub.out_us
4001 )
4002 .into());
4003 }
4004 // The width of that window, which the check above cannot see:
4005 // it asks whether the window is *open*, never how wide it is,
4006 // and a `sub` line is the one number in this format a hand (or
4007 // a hostile actor) can set to `i64::MAX` and have accepted.
4008 // Every cut, split, ripple and group trim re-derives the two
4009 // halves of the window by proportion
4010 // ([`crate::project::SubClip::window_at`]), a multiply that
4011 // overflowed on the first frame inside the caption -- a panic
4012 // on the UI thread the first time a hand ripple-deleted across
4013 // it, and in a release build a silently wrapped clock. The
4014 // same bound [`crate::is_resolution`] holds a `resolution`
4015 // line to, and for the same reason: refused by name at the
4016 // door rather than clamped into something nobody wrote.
4017 if sub.out_us - sub.in_us > crate::project::MAX_WINDOW_US {
4018 return Err(format!(
4019 "line {n}: caption at {} is a {}us window, past the {}us a caption can hold",
4020 sub.start,
4021 sub.out_us - sub.in_us,
4022 crate::project::MAX_WINDOW_US
4023 )
4024 .into());
4025 }
4026 // The palette bound, which is a clip's source bound for words:
4027 // the `subtitle` lines are written before these and a caption
4028 // names one of them by position.
4029 if sub.track >= doc.subtitles.len() {
4030 return Err(format!(
4031 "line {n}: caption names subtitle track {} of {}",
4032 sub.track,
4033 doc.subtitles.len()
4034 )
4035 .into());
4036 }
4037 if sub.start.checked_add(sub.frames).is_none() {
4038 return Err(format!(
4039 "line {n}: caption at {} runs past the last frame there is",
4040 sub.start
4041 )
4042 .into());
4043 }
4044 let lane = &mut doc.subs[at];
4045 if lane.last().is_some_and(|prev| prev.end() > sub.start) {
4046 return Err(format!(
4047 "line {n}: caption at {} overlaps the one before it, or comes before it",
4048 sub.start
4049 )
4050 .into());
4051 }
4052 lane.push(sub);
4053 }
4054 b"video" | b"audio" if !v1 => {
4055 let kind = match keyword {
4056 b"video" => LaneKind::Video,
4057 _ => LaneKind::Audio,
4058 };
4059 // v4 on names the lane, and a line naming nothing else is an
4060 // empty lane's whole existence. Older dialects had one lane per
4061 // kind.
4062 let (ord, rest) = if numbered {
4063 let at = rest.iter().position(|&b| b == b' ');
4064 (
4065 number(&rest[..at.unwrap_or(rest.len())], n)?,
4066 &rest[at.map_or(rest.len(), |at| at + 1)..],
4067 )
4068 } else {
4069 (1, rest)
4070 };
4071 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
4072 if numbered && rest.is_empty() {
4073 continue;
4074 }
4075 // v20 grew the transform field, v18 the two fade fields, v19
4076 // the transition one, v8 the speed one, v7 the fit one, v6
4077 // the colour one and v5 the eq one; every older dialect ends
4078 // at the link.
4079 let want = 5
4080 + usize::from(v5)
4081 + usize::from(v6)
4082 + usize::from(v7)
4083 + usize::from(v8)
4084 + 2 * usize::from(v18)
4085 + usize::from(v19)
4086 + usize::from(v20)
4087 + usize::from(v21)
4088 + usize::from(v22);
4089 let f = fields(rest, want, "clip", n)?;
4090 let in_frame = number(f[1], n)?;
4091 let out_frame = number(f[2], n)?;
4092 let speed = speed_of(f.get(8).copied(), n)?;
4093 // Clamped to the clip's own timeline length,
4094 // [`Project::set_fade_in`]'s rule: a crafted or hand-edited
4095 // file asking for more ramp than the clip has frames gets the
4096 // clip's whole length rather than a refusal.
4097 // A v35 clip's ramp comes on a later line and may lengthen it, so its
4098 // fades are clamped once the ramps are in (after the last line).
4099 let frames = if v35 {
4100 u32::MAX
4101 } else {
4102 speed.frames(out_frame.saturating_sub(in_frame))
4103 };
4104 let clip = check(
4105 Clip {
4106 speed_keys: Vec::new(),
4107 reversed: false,
4108 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4109 angle: Default::default(),
4110 fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames),
4111 fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames),
4112 transition_out: number(f.get(11).copied().unwrap_or(b"0"), n)?.min(frames),
4113 transition_kind: Default::default(),
4114 visualizer: flags_byte(f.get(13).copied().unwrap_or(b"0"), n)?,
4115 viz_paint: number64(f.get(14).copied().unwrap_or(b"0"), n)?,
4116 gain_db: 0.0,
4117 gain_keys: Vec::new(),
4118 pan: 0,
4119 transform_keys: Vec::new(),
4120 opacity_keys: Vec::new(),
4121 color_keys: Vec::new(),
4122 effects: Vec::new(),
4123 start: number(f[0], n)?,
4124 in_frame,
4125 out_frame,
4126 source: number(f[3], n)? as usize,
4127 link: match f[4] {
4128 b"-" => None,
4129 field => Some(number(field, n)?),
4130 },
4131 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
4132 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
4133 transform: table_index(
4134 f.get(12).copied(),
4135 doc.transform.len(),
4136 "transform",
4137 n,
4138 )?,
4139 fit: fit_policy(f.get(7).copied(), n)?,
4140 speed,
4141 pitch: 0,
4142 },
4143 &doc,
4144 n,
4145 )?;
4146 let lane = &mut doc.lanes[at].1;
4147 // The sorted, non-overlapping placement invariant, checked at
4148 // the only door untrusted clips come in through.
4149 // A v35 file's `speedkeys` lines follow the clips, so a ramped clip still
4150 // has its constant footprint here, which a shorter ramp undercuts: only
4151 // the order is checked at this door, and the footprints after the last line.
4152 let behind = |prev: &Clip| {
4153 if v35 {
4154 prev.start >= clip.start
4155 } else {
4156 prev.end() > clip.start
4157 }
4158 };
4159 if lane.last().is_some_and(behind) {
4160 return Err(format!(
4161 "line {n}: clip at {} overlaps the one before it, or comes before it",
4162 clip.start
4163 )
4164 .into());
4165 }
4166 lane.push(clip);
4167 }
4168 // Empty lines land here too: nothing in this format is optional
4169 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
4170 // is a file mixing dialects, and is refused the same way.
4171 _ => {
4172 return Err(format!(
4173 "line {n}: unknown keyword {:?}",
4174 String::from_utf8_lossy(keyword)
4175 )
4176 .into());
4177 }
4178 }
4179 }
4180 // The ramps are in now: every clip ends before the next one starts.
4181 if v35 {
4182 for (_, clips) in &mut doc.lanes {
4183 for c in clips.iter_mut() {
4184 let frames = c.frames();
4185 c.fade_in = c.fade_in.min(frames);
4186 c.fade_out = c.fade_out.min(frames);
4187 c.transition_out = c.transition_out.min(frames);
4188 }
4189 if let Some(w) = clips.windows(2).find(|w| w[0].end() > w[1].start) {
4190 return Err(format!("clip at {} overlaps the one before it", w[1].start).into());
4191 }
4192 }
4193 }
4194 if block.is_some() {
4195 return Err("a sequence block never ends: the file is cut short".into());
4196 }
4197 // One per lane whatever the file said, so a caller may zip the two -- and
4198 // the same for the placements, whose lanes are the very same list.
4199 doc.gains.resize(doc.lanes.len(), 0.0);
4200 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
4201 doc.ducks.resize(doc.lanes.len(), Vec::new());
4202 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4203 doc.names.resize(doc.lanes.len(), String::new());
4204 doc.subs.resize(doc.lanes.len(), Vec::new());
4205 // A key is another audio lane of this file, named by its position among
4206 // them, and never the lane it ducks: a file that says otherwise would ask
4207 // the mixer to duck under nothing.
4208 let audio_lanes = doc
4209 .lanes
4210 .iter()
4211 .filter(|(k, _)| *k == LaneKind::Audio)
4212 .count();
4213 for (i, lane_ducks) in doc.ducks.iter().enumerate() {
4214 let own_ord = doc.lanes[..i]
4215 .iter()
4216 .filter(|(k, _)| *k == LaneKind::Audio)
4217 .count();
4218 for duck in lane_ducks {
4219 if duck.under >= audio_lanes || duck.under == own_ord {
4220 return Err(format!(
4221 "duck names audio lane {}, which is not another audio lane of this project",
4222 duck.under + 1
4223 )
4224 .into());
4225 }
4226 }
4227 }
4228 // A file whose lanes are all empty *is* a project -- the emptied timeline,
4229 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
4230 // refuses that one, by the name it has there.
4231 Ok(doc)
4232}
4233
4234/// Where the lane a v4 line names sits, appending it if this is its first line.
4235/// Lanes arrive in display order, so a number that skips one of its kind is a
4236/// lane that was never declared, and is refused by the name it would have had.
4237fn lane_of(
4238 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
4239 kind: LaneKind,
4240 ord: u32,
4241 line: usize,
4242) -> crate::Result<usize> {
4243 let mut seen = 0;
4244 for (at, (k, _)) in lanes.iter().enumerate() {
4245 if *k == kind {
4246 seen += 1;
4247 if seen == ord {
4248 return Ok(at);
4249 }
4250 }
4251 }
4252 if ord != seen + 1 {
4253 return Err(match ord.checked_sub(1) {
4254 Some(prev) => format!(
4255 "line {line}: lane {} comes before {}",
4256 Lane::new(kind, prev as usize).label(),
4257 Lane::new(kind, seen as usize).label()
4258 ),
4259 None => format!("line {line}: lane numbers start at 1"),
4260 }
4261 .into());
4262 }
4263 lanes.push((kind, Vec::new()));
4264 Ok(lanes.len() - 1)
4265}
4266
4267/// Splits a line's fields, refusing the wrong count by name.
4268fn fields<'a>(
4269 rest: &'a [u8],
4270 want: usize,
4271 what: &str,
4272 line: usize,
4273) -> crate::Result<Vec<&'a [u8]>> {
4274 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4275 if fields.len() != want {
4276 return Err(format!(
4277 "line {line}: {what} wants {want} fields, found {}",
4278 fields.len()
4279 )
4280 .into());
4281 }
4282 Ok(fields)
4283}
4284
4285/// The per-clip structure checks both dialects share.
4286fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
4287 if clip.out_frame <= clip.in_frame {
4288 return Err(format!(
4289 "line {line}: clip [{}, {}) is empty",
4290 clip.in_frame, clip.out_frame
4291 )
4292 .into());
4293 }
4294 if clip.source >= doc.sources.len() && !crate::project::is_sequence_source(clip.source) {
4295 return Err(format!(
4296 "line {line}: clip names source {} of {}",
4297 clip.source,
4298 doc.sources.len()
4299 )
4300 .into());
4301 }
4302 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
4303 // adds `start + len` as plain `u32`, which panics in debug and wraps in
4304 // release on a crafted file. Bound it here, at the door.
4305 if clip.start.checked_add(clip.frames()).is_none() {
4306 return Err(format!(
4307 "line {line}: clip at {} runs past the last frame there is",
4308 clip.start
4309 )
4310 .into());
4311 }
4312 Ok(clip)
4313}
4314
4315/// A clip's `<speed>` field: thousandths of real time, as
4316/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A
4317/// dialect with no such field (everything before v8) means real time, which is
4318/// what such a project always played at. A number outside the range the editor
4319/// can set is *refused* rather than clamped: a project file is generated, so
4320/// that is a corrupt line and not a dialect.
4321fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result<Speed> {
4322 let Some(field) = field else {
4323 return Ok(Speed::NORMAL);
4324 };
4325 let permille = number(field, line)?;
4326 let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16);
4327 if u32::from(speed.permille()) != permille {
4328 return Err(format!(
4329 "line {line}: speed {permille} is outside {}-{} thousandths",
4330 Speed::MIN.permille(),
4331 Speed::MAX.permille()
4332 )
4333 .into());
4334 }
4335 Ok(speed)
4336}
4337
4338/// How a fit policy is spelled in the file. One word each, so a clip line stays
4339/// readable, and the same word the parser takes back.
4340fn fit_name(fit: FitPolicy) -> &'static str {
4341 match fit {
4342 FitPolicy::Fit => "fit",
4343 FitPolicy::Fill => "fill",
4344 FitPolicy::Stretch => "stretch",
4345 FitPolicy::Center => "center",
4346 }
4347}
4348
4349/// A clip's `<fit>` field. A dialect that has no such field at all means the
4350/// default -- those projects held one resolution, so no clip of theirs was ever
4351/// placed on anything.
4352fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
4353 let Some(field) = field else {
4354 return Ok(FitPolicy::default());
4355 };
4356 match field {
4357 b"fit" => Ok(FitPolicy::Fit),
4358 b"fill" => Ok(FitPolicy::Fill),
4359 b"stretch" => Ok(FitPolicy::Stretch),
4360 b"center" => Ok(FitPolicy::Center),
4361 other => Err(format!(
4362 "line {line}: {:?} is not a fit policy",
4363 String::from_utf8_lossy(other)
4364 )
4365 .into()),
4366 }
4367}
4368
4369/// An `effect` line (v42): see [`effect_lines`]. The kind must be one, the switch `0` or
4370/// `1`, every value in its range and a clip's stack no longer than
4371/// [`crate::effects::MAX_EFFECTS`].
4372fn parse_effect(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4373 use crate::effects::{Effect, EffectKind, MAX_EFFECTS, MAX_PARAMS};
4374 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4375 if f.len() < 5 || f[0] != b"video" {
4376 return Err(format!("line {n}: effect wants a video clip, a kind and a switch").into());
4377 }
4378 let ord = number(f[1], n)?;
4379 let at = doc
4380 .lanes
4381 .iter()
4382 .enumerate()
4383 .filter(|(_, (k, _))| *k == LaneKind::Video)
4384 .nth(ord.saturating_sub(1) as usize)
4385 .map(|(at, _)| at)
4386 .ok_or_else(|| format!("line {n}: effect names a lane that is not there"))?;
4387 let idx = number(f[2], n)? as usize;
4388 let name = String::from_utf8_lossy(f[3]);
4389 let kind = EffectKind::from_name(&name).ok_or_else(|| format!("line {n}: effect {name:?} is not one"))?;
4390 let on = match f[4] {
4391 b"1" => true,
4392 b"0" => false,
4393 _ => return Err(format!("line {n}: effect switch is not 0 or 1").into()),
4394 };
4395 let specs = kind.params();
4396 if f.len() - 5 != specs.len() {
4397 return Err(format!("line {n}: effect {name} wants {} values, found {}", specs.len(), f.len() - 5).into());
4398 }
4399 let mut values = [0.0; MAX_PARAMS];
4400 for ((v, field), spec) in values.iter_mut().zip(&f[5..]).zip(specs) {
4401 *v = float(field, n)?;
4402 if !(spec.min..=spec.max).contains(v) {
4403 return Err(format!("line {n}: effect {name} {} is out of its range", spec.name).into());
4404 }
4405 }
4406 let clip = doc.lanes[at]
4407 .1
4408 .get_mut(idx)
4409 .ok_or_else(|| format!("line {n}: effect names clip {idx}, which the lane does not have"))?;
4410 if clip.effects.len() >= MAX_EFFECTS {
4411 return Err(format!("line {n}: a clip holds at most {MAX_EFFECTS} effects").into());
4412 }
4413 clip.effects.push(Effect { kind, on, values, keys: Vec::new() });
4414 Ok(())
4415}
4416
4417/// A `voice` line (v41): see [`voice_lines`]. Every number is range-checked the way the
4418/// setter clamps it, and a noise reduction that is on must carry its profile.
4419fn parse_voice(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4420 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4421 if f.len() < 3 {
4422 return Err(format!("line {n}: voice wants a lane, a number and a processor").into());
4423 }
4424 if f[0] != b"audio" {
4425 return Err(format!("line {n}: voice names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
4426 }
4427 let ord = number(f[1], n)?;
4428 let at = doc
4429 .lanes
4430 .iter()
4431 .enumerate()
4432 .filter(|(_, (k, _))| *k == LaneKind::Audio)
4433 .nth(ord.saturating_sub(1) as usize)
4434 .map(|(at, _)| at)
4435 .ok_or_else(|| format!("line {n}: voice names a lane that is not there"))?;
4436 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4437 let flag = |field: &[u8]| match field {
4438 b"0" => Ok(false),
4439 b"1" => Ok(true),
4440 _ => Err(format!("line {n}: {:?} is not 0 or 1", String::from_utf8_lossy(field))),
4441 };
4442 let want = |count: usize, what: &str| {
4443 if f.len() == count + 3 {
4444 Ok(())
4445 } else {
4446 Err(format!("line {n}: voice {what} wants {count} fields, found {}", f.len() - 3))
4447 }
4448 };
4449 let range = || format!("line {n}: voice has a number out of its range");
4450 let voice = &mut doc.voices[at];
4451 match f[2] {
4452 b"gate" => {
4453 want(6, "gate")?;
4454 let g = Gate {
4455 on: flag(f[3])?,
4456 threshold_db: float(f[4], n)?,
4457 attack_ms: float(f[5], n)?,
4458 release_ms: float(f[6], n)?,
4459 hold_ms: float(f[7], n)?,
4460 range_db: float(f[8], n)?,
4461 };
4462 if g.clamped() != Some(g) {
4463 return Err(range().into());
4464 }
4465 voice.gate = g;
4466 }
4467 b"nr" => {
4468 want(4, "nr")?;
4469 let profile = match f[6] {
4470 b"-" => Vec::new(),
4471 list => list.split(|&b| b == b',').map(|v| float(v, n)).collect::<crate::Result<Vec<f32>>>()?,
4472 };
4473 let nr = NoiseReduction { on: flag(f[3])?, strength: float(f[4], n)?, floor_db: float(f[5], n)?, profile };
4474 if nr.clamped().as_ref() != Some(&nr) {
4475 return Err(range().into());
4476 }
4477 if nr.on && nr.profile.is_empty() {
4478 return Err(format!("line {n}: voice nr is on but has no noise profile").into());
4479 }
4480 voice.nr = nr;
4481 }
4482 b"comp" => {
4483 want(8, "comp")?;
4484 let c = Compressor {
4485 on: flag(f[3])?,
4486 threshold_db: float(f[4], n)?,
4487 ratio: float(f[5], n)?,
4488 attack_ms: float(f[6], n)?,
4489 release_ms: float(f[7], n)?,
4490 knee_db: float(f[8], n)?,
4491 makeup_db: float(f[9], n)?,
4492 auto_makeup: flag(f[10])?,
4493 };
4494 if c.clamped() != Some(c) {
4495 return Err(range().into());
4496 }
4497 voice.comp = c;
4498 }
4499 b"deess" => {
4500 want(5, "deess")?;
4501 let d = DeEsser {
4502 on: flag(f[3])?,
4503 threshold_db: float(f[4], n)?,
4504 amount: float(f[5], n)?,
4505 lo_hz: float(f[6], n)?,
4506 hi_hz: float(f[7], n)?,
4507 };
4508 if d.clamped() != Some(d) {
4509 return Err(range().into());
4510 }
4511 voice.deess = d;
4512 }
4513 other => {
4514 return Err(format!("line {n}: voice names {:?}, not a processor", String::from_utf8_lossy(other)).into());
4515 }
4516 }
4517 Ok(())
4518}
4519
4520/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
4521/// at all), or a line of a table that is already declared. Refused by the name
4522/// of what it points at, so the message reads as the file does.
4523fn table_index(
4524 field: Option<&[u8]>,
4525 len: usize,
4526 what: &str,
4527 line: usize,
4528) -> crate::Result<Option<u16>> {
4529 let field = match field {
4530 None | Some(b"-") => return Ok(None),
4531 Some(field) => field,
4532 };
4533 let i = number(field, line)?;
4534 if i as usize >= len || i > u32::from(u16::MAX) {
4535 return Err(format!("line {line}: clip names {what} {i} of {len}").into());
4536 }
4537 Ok(Some(i as u16))
4538}
4539
4540/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
4541fn band(field: &[u8], line: usize) -> crate::Result<Band> {
4542 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
4543 if parts.len() != 4 {
4544 return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
4545 }
4546 Ok(Band {
4547 freq_hz: float(parts[0], line)?,
4548 gain_db: float(parts[1], line)?,
4549 q: float(parts[2], line)?,
4550 kind: match parts[3] {
4551 b"ls" => BandKind::LowShelf,
4552 b"pk" => BandKind::Peak,
4553 b"hs" => BandKind::HighShelf,
4554 b"lc" => BandKind::LowCut,
4555 b"hc" => BandKind::HighCut,
4556 other => {
4557 return Err(format!(
4558 "line {line}: {:?} is not a band shape",
4559 String::from_utf8_lossy(other)
4560 )
4561 .into());
4562 }
4563 },
4564 })
4565}
4566
4567/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
4568/// and NaN are refused rather than carried -- they are the values a coefficient
4569/// cannot be built from, and the ones that would not compare equal to
4570/// themselves on the way back.
4571fn float(field: &[u8], line: usize) -> crate::Result<f32> {
4572 match std::str::from_utf8(field)
4573 .ok()
4574 .and_then(|s| s.parse::<f32>().ok())
4575 .filter(|f| f.is_finite())
4576 {
4577 Some(f) => Ok(f),
4578 None => Err(format!(
4579 "line {line}: {:?} is not a number",
4580 String::from_utf8_lossy(field)
4581 )
4582 .into()),
4583 }
4584}
4585
4586/// A clip's visualizer field: every bit of the byte is a flag
4587/// ([`crate::decode::VIZ_STYLE_FILL`]'s low bits, the fast bit, the ink
4588/// nibble), so a line naming one past what a byte holds is a look this
4589/// program does not have rather than a 300 that quietly loads as a 44.
4590fn flags_byte(field: &[u8], line: usize) -> crate::Result<u8> {
4591 let n = number(field, line)?;
4592 u8::try_from(n).map_err(|_| format!("line {line}: {n} is not a set of visualizer flags").into())
4593}
4594
4595fn number(field: &[u8], line: usize) -> crate::Result<u32> {
4596 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4597 Some(n) => Ok(n),
4598 None => Err(format!(
4599 "line {line}: {:?} is not a number",
4600 String::from_utf8_lossy(field)
4601 )
4602 .into()),
4603 }
4604}
4605
4606/// [`number`] for the one field wider than a `u32`: the clip's packed
4607/// visualizer look, whose strand-colour half needs the width (v23).
4608fn number64(field: &[u8], line: usize) -> crate::Result<u64> {
4609 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4610 Some(n) => Ok(n),
4611 None => Err(format!(
4612 "line {line}: {:?} is not a number",
4613 String::from_utf8_lossy(field)
4614 )
4615 .into()),
4616 }
4617}
4618
4619/// A `sub` line's window field: microseconds, which is the clock a cue is timed
4620/// in ([`crate::subtitle::Cue`]) and the one thing in this format counted in
4621/// something other than frames. Signed as the cues are, and the negative half
4622/// is refused by the never-empty check at the line, not here.
4623fn micros(field: &[u8], line: usize) -> crate::Result<i64> {
4624 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4625 Some(n) => Ok(n),
4626 None => Err(format!(
4627 "line {line}: {:?} is not a number",
4628 String::from_utf8_lossy(field)
4629 )
4630 .into()),
4631 }
4632}
4633
4634/// A `cue` line's text: the backslash that escapes it and the two line breaks,
4635/// which are the only bytes a line cannot hold (and `\r` is spelled too, so a
4636/// text ending in one does not look like a CRLF file to a hand-editor).
4637fn escape_text(text: &str, out: &mut Vec<u8>) {
4638 for c in text.chars() {
4639 match c {
4640 '\\' => out.extend_from_slice(b"\\\\"),
4641 '\n' => out.extend_from_slice(b"\\n"),
4642 '\r' => out.extend_from_slice(b"\\r"),
4643 c => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
4644 }
4645 }
4646}
4647
4648/// Undoes [`escape_text`]. Anything but the three escapes is refused by name,
4649/// so a hand-edited typo does not quietly become a different word.
4650fn unescape_text(field: &[u8], line: usize) -> crate::Result<String> {
4651 let mut out = Vec::with_capacity(field.len());
4652 let mut bytes = field.iter().copied();
4653 while let Some(b) = bytes.next() {
4654 if b != b'\\' {
4655 out.push(b);
4656 continue;
4657 }
4658 match bytes.next() {
4659 Some(b'\\') => out.push(b'\\'),
4660 Some(b'n') => out.push(b'\n'),
4661 Some(b'r') => out.push(b'\r'),
4662 _ => return Err(format!("line {line}: cue text has a bad escape").into()),
4663 }
4664 }
4665 String::from_utf8(out)
4666 .map_err(|_| -> crate::Error { format!("line {line}: cue text is not UTF-8").into() })
4667}
4668
4669/// The two bytes a line-based format cannot hold, and the escape byte itself.
4670fn escape(path: &Path, out: &mut Vec<u8>) {
4671 for &b in path.as_os_str().as_bytes() {
4672 match b {
4673 b'%' => out.extend_from_slice(b"%25"),
4674 b'\n' => out.extend_from_slice(b"%0A"),
4675 _ => out.push(b),
4676 }
4677 }
4678}
4679
4680/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
4681/// may spell a space or a quote that way, and there is no reason to refuse it.
4682fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
4683 let mut out = Vec::with_capacity(field.len());
4684 let mut i = 0;
4685 while i < field.len() {
4686 if field[i] != b'%' {
4687 out.push(field[i]);
4688 i += 1;
4689 continue;
4690 }
4691 let byte = field
4692 .get(i + 1..i + 3)
4693 .and_then(|h| std::str::from_utf8(h).ok())
4694 .and_then(|h| u8::from_str_radix(h, 16).ok())
4695 .ok_or_else(|| -> crate::Error {
4696 format!("line {line}: truncated % escape in the path").into()
4697 })?;
4698 out.push(byte);
4699 i += 3;
4700 }
4701 Ok(PathBuf::from(OsString::from_vec(out)))
4702}
4703
4704#[cfg(test)]
4705mod tests {
4706 use super::*;
4707
4708 /// [`super::emit`] for a project whose mix is flat: every lane at unity, no
4709 /// limiter, no rate written. Shadows the real one for the tests that were
4710 /// written before there was a mix to write -- the dialect they are about is
4711 /// the one this emits, and a v9 file with flat settings is a v8 file bar
4712 /// its version line, which is exactly what they assert.
4713 #[allow(clippy::too_many_arguments)]
4714 fn emit(
4715 dir: &Path,
4716 sources: &[Source],
4717 lanes: &[(LaneKind, Vec<Clip>)],
4718 eq: &[EqParams],
4719 color: &[ColorParams],
4720 resolution: (u32, u32),
4721 playhead: u32,
4722 ) -> Vec<u8> {
4723 super::emit(
4724 dir,
4725 sources,
4726 lanes,
4727 &[],
4728 &[],
4729 &[],
4730 eq,
4731 color,
4732 &[],
4733 resolution,
4734 None,
4735 crate::tonemap::Preset::default(),
4736 false,
4737 true,
4738 crate::export::EncoderSeat::default(),
4739 Limiter::default(),
4740 None,
4741 playhead,
4742 )
4743 }
4744
4745 /// A subtitle track as a save hands one over: the cues are not written and
4746 /// so are not here either.
4747 fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack {
4748 SubtitleTrack {
4749 path: PathBuf::from(path),
4750 track,
4751 language: String::new(),
4752 name: String::new(),
4753 label: String::new(),
4754 cues: Vec::new(),
4755 bitmap: false,
4756 refused: None,
4757 }
4758 }
4759
4760 /// The v24 `cue` line: a retyped cue's words escape the backslash and the
4761 /// two line breaks, come back exactly, and a line that names no track it
4762 /// has, or spells an escape it does not know, is refused by name.
4763 #[test]
4764 fn cue_lines_round_trip_their_text_and_refuse_what_they_cannot_name() {
4765 let dir = PathBuf::from("/proj");
4766 let doc = parse(
4767 b"edith 24\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
4768 cue 0 2 a \\\\ b\\nc\\r\\nd\ncue 0 0 \n",
4769 &dir,
4770 )
4771 .expect("two cue lines parse");
4772 assert_eq!(
4773 doc.cue_edits,
4774 [(0, 2, "a \\ b\nc\r\nd".to_string()), (0, 0, String::new())]
4775 );
4776
4777 // The writer's own spelling reads back as the same text, whatever is in it.
4778 let text = "back\\slash\nnew\rline \\n is not a newline";
4779 let mut out = Vec::new();
4780 escape_text(text, &mut out);
4781 assert_eq!(unescape_text(&out, 1).expect("its own escapes"), text);
4782
4783 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
4784 let head = b"edith 24\nsubtitle - subs.srt\n";
4785 let with = |line: &[u8]| [head.as_slice(), line].concat();
4786 assert!(refuse(&with(b"cue 1 0 x\n")).contains("names subtitle track 1 of 1"));
4787 assert!(refuse(&with(b"cue 0 0 \\q\n")).contains("bad escape"));
4788 assert!(refuse(&with(b"cue 0 0\n")).contains("without its text"));
4789 assert!(refuse(&with(b"cue 0\n")).contains("without a cue index"));
4790 assert!(
4791 refuse(b"edith 23\nsubtitle - subs.srt\ncue 0 0 x\n").contains("unknown keyword"),
4792 "a cue line before v24 is not a dialect"
4793 );
4794 }
4795
4796 /// The v10 line: which track of which file, written beside the sources and
4797 /// read back as the pair a load opens. And what a v9 file is -- one with no
4798 /// subtitles at all, which still opens and re-saves as v10.
4799 #[test]
4800 fn subtitles_round_trip_as_references_and_a_v9_file_has_none() {
4801 let dir = PathBuf::from("/proj");
4802 let (_, sources, lanes) = doc();
4803 let tracks = [
4804 subtitle("/proj/subs.srt", None),
4805 subtitle("/proj/a.mp4", Some(3)),
4806 subtitle("/elsewhere/od d name.ass", None),
4807 ];
4808 let bytes = super::emit(
4809 &dir,
4810 &sources,
4811 &lanes,
4812 &[],
4813 &[],
4814 &tracks,
4815 &[],
4816 &[],
4817 &[],
4818 (1280, 720),
4819 None,
4820 crate::tonemap::Preset::default(),
4821 false,
4822 true,
4823 crate::export::EncoderSeat::default(),
4824 Limiter::default(),
4825 None,
4826 0,
4827 );
4828 let text = String::from_utf8_lossy(&bytes);
4829 assert!(
4830 text.contains(
4831 "subtitle - subs.srt\n\
4832 subtitle 3 a.mp4\n\
4833 subtitle - /elsewhere/od d name.ass\n"
4834 ),
4835 "the path is relative where it can be, and runs to the end of its \
4836 line, spaces and all: {text}"
4837 );
4838 let back = parse(&bytes, &dir).expect("v10 parses");
4839 assert_eq!(
4840 back.subtitles,
4841 vec![
4842 (PathBuf::from("/proj/subs.srt"), None),
4843 (PathBuf::from("/proj/a.mp4"), Some(3)),
4844 (PathBuf::from("/elsewhere/od d name.ass"), None),
4845 ]
4846 );
4847
4848 // A v9 file is a project with no subtitles, and re-saving it writes v10.
4849 let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
4850 video 1 0 0 30 0 - - - fit 1000\n";
4851 let old = parse(v9, &dir).expect("v9 still loads");
4852 assert_eq!(old.subtitles, Vec::new());
4853 assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 30\n"));
4854 // ...and the line itself is not a v9 line: a dialect may not be mixed.
4855 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
4856 .unwrap_err()
4857 .to_string();
4858 assert_eq!(mixed, "line 3: unknown keyword \"subtitle\"");
4859 // A subtitle line with no path is refused, as a source with none is.
4860 for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] {
4861 let file = format!("edith 10\nsource 0 a.mp4\n{line}");
4862 assert!(
4863 parse(file.as_bytes(), &dir).is_err(),
4864 "{line:?} is not a subtitle line"
4865 );
4866 }
4867 }
4868
4869 /// The v33 `sublang` line: a track's language is written after the subtitle
4870 /// lines and comes back on that track. A project with no language writes no
4871 /// line and keeps its old header, and a line that names no track, has no
4872 /// language, or sits in a dialect before v33 is refused.
4873 #[test]
4874 fn sublang_lines_round_trip_and_a_project_with_none_is_unchanged() {
4875 let dir = PathBuf::from("/proj");
4876 let (_, sources, lanes) = doc();
4877 let save = |tracks: &[SubtitleTrack]| {
4878 super::emit(
4879 &dir,
4880 &sources,
4881 &lanes,
4882 &[],
4883 &[],
4884 tracks,
4885 &[],
4886 &[],
4887 &[],
4888 (1280, 720),
4889 None,
4890 crate::tonemap::Preset::default(),
4891 false,
4892 true,
4893 crate::export::EncoderSeat::default(),
4894 Limiter::default(),
4895 None,
4896 0,
4897 )
4898 };
4899 let mut eng = subtitle("/proj/subs.srt", None);
4900 eng.language = "eng".into();
4901 let mut fra = subtitle("/proj/a.mp4", Some(3));
4902 fra.language = "fra".into();
4903 let bytes = save(&[eng, fra]);
4904 let text = String::from_utf8_lossy(&bytes);
4905 assert!(text.starts_with("edith 33\n"), "a language makes it v33: {text}");
4906 assert!(
4907 text.contains("subtitle - subs.srt\nsubtitle 3 a.mp4\nsublang 0 eng\nsublang 1 fra\n"),
4908 "{text}"
4909 );
4910 let back = parse(&bytes, &dir).expect("v33 parses");
4911 assert_eq!(back.sub_langs, [(0, "eng".to_string()), (1, "fra".to_string())]);
4912
4913 // No language anywhere: no line, and the header is the one it was.
4914 let bare = save(&[subtitle("/proj/subs.srt", None)]);
4915 let text = String::from_utf8_lossy(&bare);
4916 assert!(!text.contains("sublang") && !text.starts_with("edith 33"), "{text}");
4917 assert!(parse(&bare, &dir).expect("parses").sub_langs.is_empty());
4918
4919 // A v32 file has no languages and loads as it did.
4920 let v32 = b"edith 32\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n";
4921 assert!(parse(v32, &dir).expect("v32 loads").sub_langs.is_empty());
4922
4923 // The refusals: a track that is not there, an empty language, and a
4924 // line in a dialect before v33.
4925 let head = "edith 33\nsource 0 a.mp4\nsubtitle - subs.srt\n";
4926 for line in ["sublang 1 eng\n", "sublang 0\n", "sublang x eng\n"] {
4927 assert!(
4928 parse(format!("{head}{line}").as_bytes(), &dir).is_err(),
4929 "{line:?} is not a sublang line"
4930 );
4931 }
4932 let old = b"edith 32\nsource 0 a.mp4\nsubtitle - subs.srt\nsublang 0 eng\n";
4933 assert_eq!(
4934 parse(old, &dir).unwrap_err().to_string(),
4935 "line 4: unknown keyword \"sublang\""
4936 );
4937 }
4938
4939 /// The caption's group field (v16): written only when the caption is in a
4940 /// group -- so a project nobody grouped a caption in is the same bytes it
4941 /// was in v15 -- read back as the id, and refused in an older dialect,
4942 /// which never wrote one.
4943 #[test]
4944 fn a_caption_group_round_trips_and_an_old_dialect_refuses_the_field() {
4945 let dir = PathBuf::from("/proj");
4946 let caption = |start: u32, frames: u32, link| SubClip {
4947 start,
4948 frames,
4949 track: 0,
4950 in_us: 0,
4951 out_us: i64::from(frames) * 1_000_000,
4952 link,
4953 };
4954 let lanes = vec![
4955 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(7))]),
4956 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(7))]),
4957 (LaneKind::Subtitle, Vec::new()),
4958 ];
4959 let subs = vec![
4960 vec![],
4961 vec![],
4962 vec![caption(0, 30, Some(7)), caption(40, 10, None)],
4963 ];
4964 let bytes = super::emit(
4965 &dir,
4966 &doc().1,
4967 &lanes,
4968 &[],
4969 &subs,
4970 &[subtitle("/proj/subs.srt", None)],
4971 &[],
4972 &[],
4973 &[],
4974 (1280, 720),
4975 None,
4976 crate::tonemap::Preset::default(),
4977 false,
4978 true,
4979 crate::export::EncoderSeat::default(),
4980 Limiter::default(),
4981 None,
4982 0,
4983 );
4984 let text = String::from_utf8_lossy(&bytes);
4985 assert!(
4986 text.contains("sub 1 0 30 0 0 30000000 7\n"),
4987 "the grouped caption carries its id: {text}"
4988 );
4989 assert!(
4990 text.contains("sub 1 40 10 0 0 10000000\n"),
4991 "a caption in no group writes no field: {text}"
4992 );
4993 let back = parse(&bytes, &dir).expect("v16 parses");
4994 assert_eq!(back.subs[2][0].link, Some(7));
4995 assert_eq!(back.subs[2][1].link, None);
4996
4997 // The older dialect never wrote a sixth field, and one claiming to be
4998 // it is a file this parser refuses by name.
4999 let v15 = parse(
5000 b"edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
5001 sub 1 0 30 0 0 30000000 7\n",
5002 &dir,
5003 )
5004 .unwrap_err()
5005 .to_string();
5006 assert_eq!(v15, "line 6: sub wants 5 fields, found 6");
5007 }
5008
5009 /// The v12 line: whether the project is cut on the stand-ins, written only
5010 /// when it is -- and the dialect before it, which had no stand-ins and
5011 /// whose bytes are therefore unchanged bar the version.
5012 #[test]
5013 fn the_proxy_switch_round_trips_and_a_v11_file_is_cut_on_its_films() {
5014 let dir = PathBuf::from("/proj");
5015 let (_, sources, lanes) = doc();
5016 let bytes = |proxy| {
5017 super::emit(
5018 &dir,
5019 &sources,
5020 &lanes,
5021 &[],
5022 &[],
5023 &[],
5024 &[],
5025 &[],
5026 &[],
5027 (1280, 720),
5028 None,
5029 crate::tonemap::Preset::default(),
5030 proxy,
5031 true,
5032 crate::export::EncoderSeat::default(),
5033 Limiter::default(),
5034 None,
5035 0,
5036 )
5037 };
5038 let on = bytes(true);
5039 assert!(
5040 String::from_utf8_lossy(&on).contains("proxy on\n"),
5041 "{}",
5042 String::from_utf8_lossy(&on)
5043 );
5044 assert!(parse(&on, &dir).expect("v12 parses").proxy);
5045 let off = bytes(false);
5046 assert!(
5047 !String::from_utf8_lossy(&off).contains("proxy"),
5048 "off is the line left out"
5049 );
5050 assert!(!parse(&off, &dir).expect("v12 parses").proxy);
5051
5052 // A v11 project is one cut on the films themselves, and it still loads.
5053 let v11 = b"edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5054 video 1 0 0 30 0 - - - fit 1000\n";
5055 let old = parse(v11, &dir).expect("v11 still loads");
5056 assert!(!old.proxy);
5057 assert_eq!(old.sources.len(), 1, "the rest of it came back too");
5058 // ...and the line is not a v11 line: a dialect may not be mixed.
5059 let mixed = parse(b"edith 11\nsource 0 a.mp4\nproxy on\n", &dir)
5060 .unwrap_err()
5061 .to_string();
5062 assert_eq!(mixed, "line 3: unknown keyword \"proxy\"");
5063 // Anything but on or off is a corrupt line, by name.
5064 for line in ["proxy\n", "proxy yes\n", "proxy On\n"] {
5065 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5066 assert!(
5067 parse(file.as_bytes(), &dir).is_err(),
5068 "{line:?} is not a proxy line"
5069 );
5070 }
5071 }
5072
5073 /// The v13 line: whether an import makes a stand-in by itself. Written the
5074 /// other way up from every other switch here -- on is the default and the
5075 /// line left out -- because that is what every dialect before it did, and a
5076 /// v12 file must come back doing it.
5077 #[test]
5078 fn the_auto_proxy_switch_round_trips_and_a_v12_file_makes_them_by_itself() {
5079 let dir = PathBuf::from("/proj");
5080 let (_, sources, lanes) = doc();
5081 let bytes = |proxy, auto| {
5082 super::emit(
5083 &dir,
5084 &sources,
5085 &lanes,
5086 &[],
5087 &[],
5088 &[],
5089 &[],
5090 &[],
5091 &[],
5092 (1280, 720),
5093 None,
5094 crate::tonemap::Preset::default(),
5095 proxy,
5096 auto,
5097 crate::export::EncoderSeat::default(),
5098 Limiter::default(),
5099 None,
5100 0,
5101 )
5102 };
5103 // The default is the line left out, and the two switches are two lines:
5104 // a project cut on stand-ins it does not make writes both.
5105 let on = bytes(false, true);
5106 assert!(
5107 !String::from_utf8_lossy(&on).contains("autoproxy"),
5108 "on is the line left out: {}",
5109 String::from_utf8_lossy(&on)
5110 );
5111 assert!(parse(&on, &dir).expect("v13 parses").auto_proxy);
5112 let off = bytes(true, false);
5113 let text = String::from_utf8_lossy(&off).to_string();
5114 assert!(text.contains("proxy on\nautoproxy off\n"), "{text}");
5115 let back = parse(&off, &dir).expect("v13 parses");
5116 assert!(back.proxy, "the other switch came back too");
5117 assert!(!back.auto_proxy);
5118
5119 // A v12 project made them by itself and could not be told otherwise.
5120 let v12 = b"edith 12\nplayhead 0\nresolution 1280 720\nproxy on\nsource 0 a.mp4\n\
5121 video 1 0 0 30 0 - - - fit 1000\n";
5122 let old = parse(v12, &dir).expect("v12 still loads");
5123 assert!(old.auto_proxy, "a v12 project made its stand-ins by itself");
5124 assert!(old.proxy, "the rest of it came back too");
5125 // ...and the line is not a v12 line: a dialect may not be mixed.
5126 let mixed = parse(b"edith 12\nsource 0 a.mp4\nautoproxy off\n", &dir)
5127 .unwrap_err()
5128 .to_string();
5129 assert_eq!(mixed, "line 3: unknown keyword \"autoproxy\"");
5130 // Anything but on or off is a corrupt line, by name.
5131 for line in ["autoproxy\n", "autoproxy no\n", "autoproxy Off\n"] {
5132 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5133 assert!(
5134 parse(file.as_bytes(), &dir).is_err(),
5135 "{line:?} is not an autoproxy line"
5136 );
5137 }
5138 }
5139
5140 /// The v14 line: which encoder an export writes the picture with, by name,
5141 /// read back as the very seat -- and the dialect before it, which had no
5142 /// way to say one and took whatever this machine had.
5143 #[test]
5144 fn the_encoder_seat_round_trips_by_name_and_a_v13_file_takes_the_machines() {
5145 use crate::export::EncoderSeat;
5146 let dir = PathBuf::from("/proj");
5147 let (_, sources, lanes) = doc();
5148 let bytes = |seat| {
5149 super::emit(
5150 &dir,
5151 &sources,
5152 &lanes,
5153 &[],
5154 &[],
5155 &[],
5156 &[],
5157 &[],
5158 &[],
5159 (1280, 720),
5160 None,
5161 crate::tonemap::Preset::default(),
5162 false,
5163 true,
5164 seat,
5165 Limiter::default(),
5166 None,
5167 0,
5168 )
5169 };
5170 // The default is the line left out, so a project nobody has picked a
5171 // seat for is the bytes a v13 file was bar the version line.
5172 let auto = bytes(EncoderSeat::Auto);
5173 assert!(
5174 !String::from_utf8_lossy(&auto).contains("encoder"),
5175 "auto is the line left out: {}",
5176 String::from_utf8_lossy(&auto)
5177 );
5178 assert_eq!(
5179 parse(&auto, &dir).expect("v14 parses").encoder,
5180 EncoderSeat::Auto
5181 );
5182 for seat in [EncoderSeat::Hardware, EncoderSeat::Software] {
5183 let written = bytes(seat);
5184 let text = String::from_utf8_lossy(&written).to_string();
5185 assert!(
5186 text.contains(&format!("encoder {}\n", seat.name())),
5187 "{text}"
5188 );
5189 assert_eq!(parse(&written, &dir).expect("v14 parses").encoder, seat);
5190 }
5191
5192 // A v13 project took the seat this machine had and could not be told
5193 // otherwise.
5194 let v13 = b"edith 13\nplayhead 0\nresolution 1280 720\nautoproxy off\nsource 0 a.mp4\n\
5195 video 1 0 0 30 0 - - - fit 1000\n";
5196 let old = parse(v13, &dir).expect("v13 still loads");
5197 assert_eq!(
5198 old.encoder,
5199 EncoderSeat::Auto,
5200 "a v13 project exported on whatever seat there was"
5201 );
5202 assert!(!old.auto_proxy, "the rest of it came back too");
5203 // ...and the line is not a v13 line: a dialect may not be mixed.
5204 let mixed = parse(b"edith 13\nsource 0 a.mp4\nencoder software\n", &dir)
5205 .unwrap_err()
5206 .to_string();
5207 assert_eq!(mixed, "line 3: unknown keyword \"encoder\"");
5208 // Anything but the three names is a corrupt line, by name.
5209 for line in ["encoder\n", "encoder gpu\n", "encoder Hardware\n"] {
5210 let file = format!("edith 15\nsource 0 a.mp4\n{line}");
5211 assert!(
5212 parse(file.as_bytes(), &dir).is_err(),
5213 "{line:?} is not an encoder line"
5214 );
5215 }
5216 }
5217
5218 /// The v17 line: an explicit sound rate, written only when picked and read
5219 /// back as the very number -- and a v16 file, which had no way to say one
5220 /// and meant the source's own probe, still opens with `None`.
5221 #[test]
5222 fn the_sample_rate_round_trips_and_a_v16_file_leaves_it_derived() {
5223 let dir = PathBuf::from("/proj");
5224 let (_, sources, lanes) = doc();
5225 let bytes = |rate| {
5226 super::emit(
5227 &dir,
5228 &sources,
5229 &lanes,
5230 &[],
5231 &[],
5232 &[],
5233 &[],
5234 &[],
5235 &[],
5236 (1280, 720),
5237 None,
5238 crate::tonemap::Preset::default(),
5239 false,
5240 true,
5241 crate::export::EncoderSeat::default(),
5242 Limiter::default(),
5243 rate,
5244 0,
5245 )
5246 };
5247 // Unset is the line left out, so a project nobody has chosen a rate for
5248 // is the bytes a v16 file was bar the version line.
5249 let unset = bytes(None);
5250 assert!(
5251 !String::from_utf8_lossy(&unset).contains("samplerate"),
5252 "no pick is the line left out: {}",
5253 String::from_utf8_lossy(&unset)
5254 );
5255 assert_eq!(parse(&unset, &dir).expect("v17 parses").sample_rate, None);
5256 for rate in [44_100, 48_000, 96_000] {
5257 let written = bytes(Some(rate));
5258 let text = String::from_utf8_lossy(&written).to_string();
5259 assert!(text.contains(&format!("samplerate {rate}\n")), "{text}");
5260 assert_eq!(
5261 parse(&written, &dir).expect("v17 parses").sample_rate,
5262 Some(rate)
5263 );
5264 }
5265 // A v16 project had no rate of its own to say: the field comes back
5266 // `None`, which is what "derive it from the source" already meant.
5267 let v16 = b"edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5268 video 1 0 0 30 0 - - - fit 1000\n";
5269 assert_eq!(parse(v16, &dir).expect("v16 still loads").sample_rate, None);
5270 // ...and the line is not a v16 line: a dialect may not be mixed.
5271 let mixed = parse(b"edith 16\nsource 0 a.mp4\nsamplerate 48000\n", &dir)
5272 .unwrap_err()
5273 .to_string();
5274 assert_eq!(mixed, "line 3: unknown keyword \"samplerate\"");
5275 // A number out of a sound rate's range is a corrupt line, by name.
5276 for line in ["samplerate 0\n", "samplerate 500000\n", "samplerate nope\n"] {
5277 let file = format!("edith 18\nsource 0 a.mp4\n{line}");
5278 assert!(
5279 parse(file.as_bytes(), &dir).is_err(),
5280 "{line:?} is not a sound rate line"
5281 );
5282 }
5283 }
5284
5285 /// The v11 line: the HDR rendition, written by name, read back as the very
5286 /// preset -- and the dialect before it, which had no way to say one and
5287 /// meant the published conversion.
5288 #[test]
5289 fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
5290 let dir = PathBuf::from("/proj");
5291 let (_, sources, lanes) = doc();
5292 for preset in crate::tonemap::Preset::ALL {
5293 let bytes = super::emit(
5294 &dir,
5295 &sources,
5296 &lanes,
5297 &[],
5298 &[],
5299 &[],
5300 &[],
5301 &[],
5302 &[],
5303 (1280, 720),
5304 None,
5305 preset,
5306 false,
5307 true,
5308 crate::export::EncoderSeat::default(),
5309 Limiter::default(),
5310 None,
5311 0,
5312 );
5313 let text = String::from_utf8_lossy(&bytes).to_string();
5314 assert_eq!(
5315 text.contains(&format!("tonemap {}\n", preset.name())),
5316 preset != crate::tonemap::Preset::default(),
5317 "the default is the line left out: {text}"
5318 );
5319 assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
5320 }
5321
5322 // A v10 file is a project shown the published way, and re-saving it
5323 // writes v11 with nothing more in it.
5324 let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5325 video 1 0 0 30 0 - - - fit 1000\n";
5326 let old = parse(v10, &dir).expect("v10 still loads");
5327 assert_eq!(old.tone, crate::tonemap::Preset::Reference);
5328 // ...and the line itself is not a v10 line: a dialect may not be mixed.
5329 let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
5330 .unwrap_err()
5331 .to_string();
5332 assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
5333 // A rendition nobody wrote is a corrupt line, by name -- not a silent
5334 // fall back to another picture.
5335 for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
5336 let file = format!("edith 11\nsource 0 a.mp4\n{line}");
5337 assert!(
5338 parse(file.as_bytes(), &dir).is_err(),
5339 "{line:?} is not a tonemap line"
5340 );
5341 }
5342 }
5343
5344 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
5345 Clip {
5346 speed_keys: Vec::new(),
5347 reversed: false,
5348 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5349 angle: Default::default(),
5350 fade_in: 0,
5351 fade_out: 0,
5352 transition_out: 0,
5353 transition_kind: Default::default(),
5354 visualizer: 0,
5355 viz_paint: 0,
5356 gain_db: 0.0,
5357 gain_keys: Vec::new(),
5358 pan: 0,
5359 transform_keys: Vec::new(),
5360 opacity_keys: Vec::new(),
5361 color_keys: Vec::new(),
5362 effects: Vec::new(),
5363 start,
5364 in_frame,
5365 out_frame,
5366 source,
5367 link,
5368 eq: None,
5369 color: None,
5370 transform: None,
5371 fit: FitPolicy::default(),
5372 speed: Speed::NORMAL,
5373 pitch: 0,
5374 }
5375 }
5376
5377 /// [`emit`] for a timeline that equalizes nothing, which is every case that
5378 /// predates the eq lines.
5379 fn flat(
5380 dir: &Path,
5381 sources: &[Source],
5382 lanes: &[(LaneKind, Vec<Clip>)],
5383 playhead: u32,
5384 ) -> Vec<u8> {
5385 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
5386 }
5387
5388 /// Two sources, one under the project's own directory and one not, a clip
5389 /// from each on the video lane, and an audio lane with a gap in the middle
5390 /// -- the shape every case below starts from.
5391 fn source(path: &str, audio_stream: usize) -> Source {
5392 Source {
5393 path: PathBuf::from(path),
5394 audio_stream,
5395 ..Default::default()
5396 }
5397 }
5398
5399 /// Lanes in display order, as [`Document::lanes`] holds them.
5400 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
5401
5402 /// `V1` then `A1`, the shape every dialect before v4 held.
5403 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
5404 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5405 }
5406
5407 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
5408 (
5409 PathBuf::from("/proj"),
5410 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
5411 two(
5412 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
5413 vec![clip(0, 0, 30, 0, Some(0))],
5414 ),
5415 )
5416 }
5417
5418 #[test]
5419 fn relative_and_absolute_paths_round_trip() {
5420 let (dir, sources, lanes) = doc();
5421 let bytes = flat(&dir, &sources, &lanes, 12);
5422 assert_eq!(
5423 String::from_utf8_lossy(&bytes),
5424 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
5425 source 2 /elsewhere/b.mp4\n\
5426 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\
5427 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
5428 "the file under the project directory is written relative to it, \
5429 each with the audio stream it plays"
5430 );
5431 let back = parse(&bytes, &dir).expect("parse");
5432 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
5433 assert_eq!(
5434 back.lanes, lanes,
5435 "both lanes, in display order; the trailing gap needs no line"
5436 );
5437 assert_eq!(back.playhead, 12);
5438 // ...and emitting the parsed document reproduces the same bytes.
5439 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5440 }
5441
5442 /// The whole of the bump: a project of any number of lanes writes and reads
5443 /// back, in display order, empty lanes and cross-lane groups included.
5444 #[test]
5445 fn any_number_of_lanes_round_trips() {
5446 let dir = PathBuf::from("/proj");
5447 let sources = vec![source("/proj/a.mp4", 0)];
5448 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
5449 // shows, not video-then-audio -- with one take grouped across V1 and A2
5450 // (no paired ord, the lanes between them empty of it) and an A1 holding
5451 // nothing at all.
5452 let lanes = vec![
5453 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
5454 (LaneKind::Audio, Vec::new()),
5455 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
5456 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
5457 ];
5458 let bytes = flat(&dir, &sources, &lanes, 7);
5459 assert_eq!(
5460 String::from_utf8_lossy(&bytes),
5461 "edith 30\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
5462 video 1 0 0 30 0 4 - - fit 1000 0 0 0 - 0 0\naudio 1\n\
5463 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",
5464 "an empty lane is a line of its own; everything else is its clips"
5465 );
5466 let back = parse(&bytes, &dir).expect("parse");
5467 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
5468 assert_eq!(back.playhead, 7);
5469 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5470
5471 // A lane number may not skip one of its kind: that lane was declared by
5472 // nothing, and the refusal names it.
5473 for (file, want) in [
5474 (
5475 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
5476 "line 3: lane V2 comes before V1",
5477 ),
5478 (
5479 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
5480 "line 4: lane A3 comes before A1",
5481 ),
5482 (
5483 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
5484 "line 3: lane numbers start at 1",
5485 ),
5486 // The clip fields are still the clip fields, one lane number on.
5487 (
5488 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
5489 "line 3: clip wants 5 fields, found 4",
5490 ),
5491 // ...and a v4 line in a v3 file reads as the garbled clip it is.
5492 (
5493 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
5494 "line 3: clip wants 5 fields, found 6",
5495 ),
5496 ] {
5497 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
5498 }
5499 // Lanes and nothing on them is the emptied timeline, saved: a project.
5500 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
5501 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
5502 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
5503 }
5504
5505 /// One band, spelled the way an eq line spells it.
5506 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
5507 Band {
5508 freq_hz,
5509 gain_db,
5510 q,
5511 kind,
5512 }
5513 }
5514
5515 /// The whole of the v5 bump: the clips name a shared equalizer table, the
5516 /// bytes are the ones documented at the top of this file, and every f32 in
5517 /// them comes back *bit* for bit -- which is what makes a re-save of a
5518 /// loaded project produce the same file rather than a drifting one.
5519 #[test]
5520 fn equalizers_round_trip_bit_exactly_and_are_shared() {
5521 let dir = PathBuf::from("/proj");
5522 let sources = vec![source("/proj/a.mp4", 0)];
5523 let eq = vec![
5524 EqParams {
5525 bands: vec![
5526 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
5527 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
5528 ],
5529 },
5530 // The awkward ones: a value needing all 24 mantissa bits, one whose
5531 // shortest spelling is exponential, a subnormal, and a negative
5532 // zero -- plus the empty cascade, which is a setting like any other.
5533 EqParams {
5534 bands: vec![band_of(
5535 16_777_215.0,
5536 -0.1,
5537 f32::MIN_POSITIVE / 3.0,
5538 BandKind::HighShelf,
5539 )],
5540 },
5541 EqParams { bands: Vec::new() },
5542 ];
5543 // Two clips share entry 0, so it is written once; one clip plays flat.
5544 let lanes = two(
5545 vec![
5546 Clip {
5547 fade_in: 0,
5548 fade_out: 0,
5549 transition_out: 0,
5550 transition_kind: Default::default(),
5551 visualizer: 0,
5552 viz_paint: 0,
5553 gain_db: 0.0,
5554 eq: Some(0),
5555 ..clip(0, 0, 30, 0, Some(0))
5556 },
5557 Clip {
5558 fade_in: 0,
5559 fade_out: 0,
5560 transition_out: 0,
5561 transition_kind: Default::default(),
5562 visualizer: 0,
5563 viz_paint: 0,
5564 gain_db: 0.0,
5565 eq: Some(1),
5566 ..clip(30, 10, 20, 0, None)
5567 },
5568 ],
5569 vec![
5570 Clip {
5571 fade_in: 0,
5572 fade_out: 0,
5573 transition_out: 0,
5574 transition_kind: Default::default(),
5575 visualizer: 0,
5576 viz_paint: 0,
5577 gain_db: 0.0,
5578 eq: Some(0),
5579 ..clip(0, 0, 30, 0, Some(0))
5580 },
5581 Clip {
5582 fade_in: 0,
5583 fade_out: 0,
5584 transition_out: 0,
5585 transition_kind: Default::default(),
5586 visualizer: 0,
5587 viz_paint: 0,
5588 gain_db: 0.0,
5589 eq: Some(2),
5590 ..clip(30, 0, 10, 0, None)
5591 },
5592 ],
5593 );
5594 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
5595 assert_eq!(
5596 String::from_utf8_lossy(&bytes),
5597 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5598 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
5599 eq 16777215.0:-0.1:3.918315e-39:hs\n\
5600 eq\n\
5601 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\
5602 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",
5603 "the table comes before the clips, and a clip names a line of it"
5604 );
5605
5606 let back = parse(&bytes, &dir).expect("parse");
5607 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
5608 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
5609 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
5610 assert_eq!(
5611 (
5612 got.freq_hz.to_bits(),
5613 got.gain_db.to_bits(),
5614 got.q.to_bits(),
5615 got.kind
5616 ),
5617 (
5618 want.freq_hz.to_bits(),
5619 want.gain_db.to_bits(),
5620 want.q.to_bits(),
5621 want.kind
5622 ),
5623 "eq {i} band {b} came back as other bits"
5624 );
5625 }
5626 }
5627 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
5628 assert_eq!(
5629 emit(
5630 &dir,
5631 &back.sources,
5632 &back.lanes,
5633 &back.eq,
5634 &back.color,
5635 (1280, 720),
5636 0
5637 ),
5638 bytes
5639 );
5640 }
5641
5642 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
5643 /// colour table, the bytes are the ones documented at the top of this file,
5644 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
5645 #[test]
5646 fn colours_round_trip_bit_exactly_and_are_shared() {
5647 let dir = PathBuf::from("/proj");
5648 let sources = vec![source("/proj/a.mp4", 0)];
5649 let color = vec![
5650 ColorParams {
5651 brightness: 0.1,
5652 contrast: 1.2,
5653 saturation: 0.9,
5654 tint: -0.3,
5655 ..Default::default()
5656 },
5657 // The awkward ones again: all 24 mantissa bits, an exponential
5658 // spelling, a subnormal and a negative zero -- and the identity,
5659 // which is a setting like any other.
5660 ColorParams {
5661 brightness: -0.000_000_1,
5662 contrast: 16_777_215.0,
5663 saturation: f32::MIN_POSITIVE / 3.0,
5664 tint: -0.0,
5665 ..Default::default()
5666 },
5667 ColorParams::default(),
5668 ];
5669 // Two clips share entry 0, so it is written once; one clip is ungraded.
5670 let lanes = two(
5671 vec![
5672 Clip {
5673 fade_in: 0,
5674 fade_out: 0,
5675 transition_out: 0,
5676 transition_kind: Default::default(),
5677 visualizer: 0,
5678 viz_paint: 0,
5679 gain_db: 0.0,
5680 color: Some(0),
5681 fit: FitPolicy::default(),
5682 speed: Speed::NORMAL,
5683 ..clip(0, 0, 30, 0, Some(0))
5684 },
5685 Clip {
5686 fade_in: 0,
5687 fade_out: 0,
5688 transition_out: 0,
5689 transition_kind: Default::default(),
5690 visualizer: 0,
5691 viz_paint: 0,
5692 gain_db: 0.0,
5693 color: Some(1),
5694 fit: FitPolicy::default(),
5695 speed: Speed::NORMAL,
5696 ..clip(30, 10, 20, 0, None)
5697 },
5698 ],
5699 vec![
5700 Clip {
5701 fade_in: 0,
5702 fade_out: 0,
5703 transition_out: 0,
5704 transition_kind: Default::default(),
5705 visualizer: 0,
5706 viz_paint: 0,
5707 gain_db: 0.0,
5708 color: Some(0),
5709 fit: FitPolicy::default(),
5710 speed: Speed::NORMAL,
5711 ..clip(0, 0, 30, 0, Some(0))
5712 },
5713 Clip {
5714 fade_in: 0,
5715 fade_out: 0,
5716 transition_out: 0,
5717 transition_kind: Default::default(),
5718 visualizer: 0,
5719 viz_paint: 0,
5720 gain_db: 0.0,
5721 color: Some(2),
5722 fit: FitPolicy::default(),
5723 speed: Speed::NORMAL,
5724 ..clip(30, 0, 10, 0, None)
5725 },
5726 ],
5727 );
5728 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
5729 assert_eq!(
5730 String::from_utf8_lossy(&bytes),
5731 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5732 color 0.1:1.2:0.9:-0.3\n\
5733 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
5734 color 0.0:1.0:1.0:0.0\n\
5735 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\
5736 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",
5737 "the table comes before the clips, and a clip names a line of it"
5738 );
5739
5740 let back = parse(&bytes, &dir).expect("parse");
5741 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
5742 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
5743 assert_eq!(
5744 (
5745 got.brightness.to_bits(),
5746 got.contrast.to_bits(),
5747 got.saturation.to_bits(),
5748 got.tint.to_bits()
5749 ),
5750 (
5751 want.brightness.to_bits(),
5752 want.contrast.to_bits(),
5753 want.saturation.to_bits(),
5754 want.tint.to_bits()
5755 ),
5756 "color {i} came back as other bits"
5757 );
5758 }
5759 assert_eq!(back.color.len(), 3);
5760 assert_eq!(
5761 emit(
5762 &dir,
5763 &back.sources,
5764 &back.lanes,
5765 &back.eq,
5766 &back.color,
5767 (1280, 720),
5768 0
5769 ),
5770 bytes
5771 );
5772 }
5773
5774 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
5775 /// intact, and re-saving it writes the new magic and a `-` colour field.
5776 #[test]
5777 fn a_v5_file_grades_nothing() {
5778 let dir = PathBuf::from("/proj");
5779 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
5780 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
5781 let old = parse(v5, &dir).expect("v5 parses");
5782 assert!(old.color.is_empty(), "nothing before v6 grades anything");
5783 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
5784 assert_eq!(old.lanes[0].1[0].eq, Some(0));
5785 assert!(old.lanes[0].1[0].color.is_none());
5786 assert_eq!(
5787 String::from_utf8_lossy(&emit(
5788 &dir,
5789 &old.sources,
5790 &old.lanes,
5791 &old.eq,
5792 &old.color,
5793 (1280, 720),
5794 old.playhead
5795 )),
5796 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5797 eq 80.0:-3.0:0.707:ls\n\
5798 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"
5799 );
5800 }
5801
5802 /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
5803 /// written on its own line, comes back as the very number that was set, and
5804 /// a v7 file -- which has no such field -- loads at real time and re-saves
5805 /// saying so.
5806 #[test]
5807 fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
5808 let dir = PathBuf::from("/proj");
5809 let sources = vec![Source::new("/proj/a.mp4", 0)];
5810 let speeded = |start, in_frame, out_frame, permille| Clip {
5811 speed_keys: Vec::new(),
5812 reversed: false,
5813 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5814 angle: Default::default(),
5815 fade_in: 0,
5816 fade_out: 0,
5817 transition_out: 0,
5818 transition_kind: Default::default(),
5819 visualizer: 0,
5820 viz_paint: 0,
5821 gain_db: 0.0,
5822 gain_keys: Vec::new(),
5823 pan: 0,
5824 transform_keys: Vec::new(),
5825 opacity_keys: Vec::new(),
5826 color_keys: Vec::new(),
5827 effects: Vec::new(),
5828 start,
5829 in_frame,
5830 out_frame,
5831 source: 0,
5832 link: None,
5833 eq: None,
5834 color: None,
5835 transform: None,
5836 fit: FitPolicy::default(),
5837 speed: Speed::from_permille(permille),
5838 pitch: 0,
5839 };
5840 // 30 source frames at 2x is 15 timeline frames, which is where the
5841 // second clip starts -- the file writes the source range and the rate,
5842 // and the length on the timeline is derived from the two.
5843 let lanes = vec![
5844 (
5845 LaneKind::Video,
5846 vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
5847 ),
5848 (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
5849 ];
5850 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
5851 assert_eq!(
5852 String::from_utf8_lossy(&bytes),
5853 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5854 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\
5855 audio 1 0 0 30 0 - - - fit 2000 0 0 0 - 0 0\n",
5856 "the rate is the clip line's last field, in thousandths"
5857 );
5858 let back = parse(&bytes, &dir).expect("parse");
5859 assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
5860
5861 // ...and the dialect before it, which had no rate to name.
5862 let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5863 video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
5864 let old = parse(v7, &dir).expect("v7 parses");
5865 assert!(
5866 old.lanes
5867 .iter()
5868 .flat_map(|(_, clips)| clips)
5869 .all(|c| c.speed == Speed::NORMAL),
5870 "nothing before v8 plays at anything but real time"
5871 );
5872 assert_eq!(
5873 String::from_utf8_lossy(&emit(
5874 &dir,
5875 &old.sources,
5876 &old.lanes,
5877 &old.eq,
5878 &old.color,
5879 (1280, 720),
5880 old.playhead
5881 )),
5882 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5883 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"
5884 );
5885 // A rate outside what the editor can set is a corrupt line, by name.
5886 let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
5887 assert_eq!(
5888 parse(bad, &dir).unwrap_err().to_string(),
5889 "line 3: speed 9000 is outside 250-4000 thousandths"
5890 );
5891 }
5892
5893 #[test]
5894 fn a_v17_file_loads_with_zero_fades_and_fades_round_trip_bit_exactly() {
5895 let dir = PathBuf::from("/proj");
5896 // The v17 dialect: nine clip fields, the last the speed -- no fade
5897 // pair after it at all, not even zeroes.
5898 let v17 = b"edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5899 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
5900 let old = parse(v17, &dir).expect("v17 parses");
5901 assert!(
5902 old.lanes
5903 .iter()
5904 .flat_map(|(_, clips)| clips)
5905 .all(|c| c.fade_in == 0 && c.fade_out == 0),
5906 "nothing before v18 had a fade to name"
5907 );
5908
5909 // ...and the dialect that does: nonzero fades on both edges, written
5910 // and read back as the very numbers.
5911 let sources = vec![Source::new("/proj/a.mp4", 0)];
5912 let faded = Clip {
5913 speed_keys: Vec::new(),
5914 reversed: false,
5915 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5916 angle: Default::default(),
5917 fade_in: 5,
5918 fade_out: 7,
5919 transition_out: 0,
5920 transition_kind: Default::default(),
5921 visualizer: 0,
5922 viz_paint: 0,
5923 gain_db: 0.0,
5924 gain_keys: Vec::new(),
5925 pan: 0,
5926 transform_keys: Vec::new(),
5927 opacity_keys: Vec::new(),
5928 color_keys: Vec::new(),
5929 effects: Vec::new(),
5930 start: 0,
5931 in_frame: 0,
5932 out_frame: 30,
5933 source: 0,
5934 link: None,
5935 eq: None,
5936 color: None,
5937 transform: None,
5938 fit: FitPolicy::default(),
5939 speed: Speed::NORMAL,
5940 pitch: 0,
5941 };
5942 let lanes = vec![(LaneKind::Video, vec![faded])];
5943 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
5944 assert_eq!(
5945 String::from_utf8_lossy(&bytes),
5946 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5947 video 1 0 0 30 0 - - - fit 1000 5 7 0 - 0 0\n",
5948 "the fades are the clip line's last two fields"
5949 );
5950 let back = parse(&bytes, &dir).expect("parse");
5951 assert_eq!(
5952 back.lanes, lanes,
5953 "the fades round trip as the very numbers"
5954 );
5955 }
5956
5957 /// The whole of the v19 bump, the fade test's twin: a clip's dissolve into
5958 /// its successor is written as the clip line's own last field, comes back
5959 /// as the very number that was set, and a v18 file -- which has no such
5960 /// field -- loads with every clip's [`Clip::transition_out`] at zero and
5961 /// re-saves saying so.
5962 #[test]
5963 fn a_v18_file_loads_with_no_transition_and_transitions_round_trip_bit_exactly() {
5964 let dir = PathBuf::from("/proj");
5965 // The v18 dialect: eleven clip fields, the last the fade-out -- no
5966 // transition field after it at all, not even a zero.
5967 let v18 = b"edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5968 video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n";
5969 let old = parse(v18, &dir).expect("v18 parses");
5970 assert!(
5971 old.lanes
5972 .iter()
5973 .flat_map(|(_, clips)| clips)
5974 .all(|c| c.transition_out == 0),
5975 "nothing before v19 had a dissolve to name"
5976 );
5977
5978 // ...and the dialect that does: a nonzero dissolve, written and read
5979 // back as the very number.
5980 let sources = vec![Source::new("/proj/a.mp4", 0)];
5981 let dissolving = Clip {
5982 speed_keys: Vec::new(),
5983 reversed: false,
5984 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5985 angle: Default::default(),
5986 fade_in: 0,
5987 fade_out: 0,
5988 transition_out: 9,
5989 transition_kind: Default::default(),
5990 visualizer: 0,
5991 viz_paint: 0,
5992 gain_db: 0.0,
5993 gain_keys: Vec::new(),
5994 pan: 0,
5995 transform_keys: Vec::new(),
5996 opacity_keys: Vec::new(),
5997 color_keys: Vec::new(),
5998 effects: Vec::new(),
5999 start: 0,
6000 in_frame: 0,
6001 out_frame: 30,
6002 source: 0,
6003 link: None,
6004 eq: None,
6005 color: None,
6006 transform: None,
6007 fit: FitPolicy::default(),
6008 speed: Speed::NORMAL,
6009 pitch: 0,
6010 };
6011 let lanes = vec![(LaneKind::Video, vec![dissolving])];
6012 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6013 assert_eq!(
6014 String::from_utf8_lossy(&bytes),
6015 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6016 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n",
6017 "the dissolve is the clip line's own last field"
6018 );
6019 let back = parse(&bytes, &dir).expect("parse");
6020 assert_eq!(
6021 back.lanes, lanes,
6022 "the dissolve round trips as the very number"
6023 );
6024 }
6025
6026 /// The clip's packed look (v23): a chosen strand colour rides in the
6027 /// field's own bytes under the top bit and comes back bit-exact, a v22
6028 /// file's 32-bit value is the low half of that field with no strand
6029 /// colour, and a file older than the field itself is the zero it always
6030 /// was.
6031 #[test]
6032 fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() {
6033 use crate::decode::{
6034 VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue,
6035 with_viz_paint_strand_sat,
6036 };
6037 let (dir, sources, lanes) = doc();
6038 let mut painted = lanes.clone();
6039 // Azure, its dual half a chosen green rather than the automatic
6040 // complement of the clip's own hue.
6041 let chosen = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 64), 200);
6042 assert!(viz_strand_set(chosen));
6043 painted[0].1[0].viz_paint = chosen;
6044 let bytes = flat(&dir, &sources, &painted, 0);
6045 assert!(
6046 bytes.starts_with(b"edith 30\n"),
6047 "a project with a strand colour saves as v23: {}",
6048 String::from_utf8_lossy(&bytes)
6049 );
6050 let back = parse(&bytes, &dir).expect("v23 parses");
6051 assert_eq!(back.lanes, painted, "the look round-trips bit-exactly");
6052
6053 // A v22 file's field is a u32: the value lands in the low half
6054 // untouched, and a strand colour it cannot carry reads as auto.
6055 let look = VIZ_PAINT_AZURE as u32;
6056 let v22 = format!(
6057 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6058 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 {look}\n"
6059 );
6060 let old = parse(v22.as_bytes(), &dir).expect("v22 still loads");
6061 let paint = old.lanes[0].1[0].viz_paint;
6062 assert_eq!(paint, u64::from(look), "the low half is the v22 value");
6063 assert!(!viz_strand_set(paint), "a v22 look chose no strand colour");
6064 assert_eq!(viz_hue_ui(paint), 150);
6065 assert_eq!(viz_sat_ui(paint), 160);
6066 // ...and a file older than the field is the zero that means the
6067 // azure default, as it was before the field was widened.
6068 let v21 = b"edith 21\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6069 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0\n";
6070 let older = parse(v21, &dir).expect("v21 still loads");
6071 assert_eq!(older.lanes[0].1[0].viz_paint, 0);
6072 }
6073
6074 /// A v19 file is a v20 one that places no clip anywhere but its fit
6075 /// policy's own spot: it loads with every clip's [`Clip::transform`] at
6076 /// `None`, which is what a v19 file's missing field still means.
6077 #[test]
6078 fn a_v19_file_loads_untransformed() {
6079 let dir = PathBuf::from("/proj");
6080 // The v19 dialect: twelve clip fields, the last the transition -- no
6081 // transform field after it at all, not even a `-`.
6082 let v19 = b"edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6083 video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n";
6084 let old = parse(v19, &dir).expect("v19 parses");
6085 assert!(old.transform.is_empty(), "nothing before v20 has a table");
6086 assert!(
6087 old.lanes
6088 .iter()
6089 .flat_map(|(_, clips)| clips)
6090 .all(|c| c.transform.is_none()),
6091 "nothing before v20 had a placement to name"
6092 );
6093 }
6094
6095 /// [`colours_round_trip_bit_exactly_and_are_shared`]'s twin: two clips
6096 /// sharing one transform table entry write it once, and both bytes and
6097 /// values come back bit-exact.
6098 #[test]
6099 fn transforms_round_trip_bit_exactly_and_are_shared() {
6100 let dir = PathBuf::from("/proj");
6101 let sources = vec![source("/proj/a.mp4", 0)];
6102 let transform = vec![
6103 TransformParams {
6104 pos_x: 0.1,
6105 pos_y: -0.2,
6106 scale: 1.5,
6107 rotate: 90.0,
6108 crop_l: 0.1,
6109 crop_r: 0.0,
6110 crop_t: 0.0,
6111 crop_b: 0.05,
6112 opacity: 0.25,
6113 },
6114 // The awkward ones again: all 24 mantissa bits, an exponential
6115 // spelling, a subnormal and a negative zero -- and the identity,
6116 // which is a setting like any other.
6117 TransformParams {
6118 pos_x: -0.000_000_1,
6119 pos_y: 16_777_215.0,
6120 scale: f32::MIN_POSITIVE / 3.0,
6121 rotate: -0.0,
6122 crop_l: 0.0,
6123 crop_r: 0.0,
6124 crop_t: 0.0,
6125 crop_b: 0.0,
6126 opacity: 1.0,
6127 },
6128 TransformParams::default(),
6129 ];
6130 // Two clips share entry 0, so it is written once; one clip is untransformed.
6131 let lanes = two(
6132 vec![
6133 Clip {
6134 fade_in: 0,
6135 fade_out: 0,
6136 transition_out: 0,
6137 transition_kind: Default::default(),
6138 visualizer: 0,
6139 viz_paint: 0,
6140 gain_db: 0.0,
6141 transform: Some(0),
6142 fit: FitPolicy::default(),
6143 speed: Speed::NORMAL,
6144 ..clip(0, 0, 30, 0, Some(0))
6145 },
6146 Clip {
6147 fade_in: 0,
6148 fade_out: 0,
6149 transition_out: 0,
6150 transition_kind: Default::default(),
6151 visualizer: 0,
6152 viz_paint: 0,
6153 gain_db: 0.0,
6154 transform: Some(1),
6155 fit: FitPolicy::default(),
6156 speed: Speed::NORMAL,
6157 ..clip(30, 10, 20, 0, None)
6158 },
6159 ],
6160 vec![
6161 Clip {
6162 fade_in: 0,
6163 fade_out: 0,
6164 transition_out: 0,
6165 transition_kind: Default::default(),
6166 visualizer: 0,
6167 viz_paint: 0,
6168 gain_db: 0.0,
6169 transform: Some(0),
6170 fit: FitPolicy::default(),
6171 speed: Speed::NORMAL,
6172 ..clip(0, 0, 30, 0, Some(0))
6173 },
6174 Clip {
6175 fade_in: 0,
6176 fade_out: 0,
6177 transition_out: 0,
6178 transition_kind: Default::default(),
6179 visualizer: 0,
6180 viz_paint: 0,
6181 gain_db: 0.0,
6182 transform: Some(2),
6183 fit: FitPolicy::default(),
6184 speed: Speed::NORMAL,
6185 ..clip(30, 0, 10, 0, None)
6186 },
6187 ],
6188 );
6189 let bytes = super::emit(
6190 &dir,
6191 &sources,
6192 &lanes,
6193 &[],
6194 &[],
6195 &[],
6196 &[],
6197 &[],
6198 &transform,
6199 (1280, 720),
6200 None,
6201 crate::tonemap::Preset::default(),
6202 false,
6203 true,
6204 crate::export::EncoderSeat::default(),
6205 Limiter::default(),
6206 None,
6207 0,
6208 );
6209 assert_eq!(
6210 String::from_utf8_lossy(&bytes),
6211 "edith 31\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6212 transform 0.1:-0.2:1.5:90.0:0.1:0.0:0.0:0.05:0.25\n\
6213 transform -1e-7:16777215.0:3.918315e-39:-0.0:0.0:0.0:0.0:0.0\n\
6214 transform 0.0:0.0:1.0:0.0:0.0:0.0:0.0:0.0\n\
6215 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\
6216 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",
6217 "the table comes before the clips, and a clip names a line of it"
6218 );
6219
6220 let back = parse(&bytes, &dir).expect("parse");
6221 assert_eq!(back.lanes, lanes, "every clip keeps the transform it named");
6222 for (i, (got, want)) in back.transform.iter().zip(&transform).enumerate() {
6223 assert_eq!(
6224 (
6225 got.pos_x.to_bits(),
6226 got.pos_y.to_bits(),
6227 got.scale.to_bits(),
6228 got.rotate.to_bits(),
6229 got.crop_l.to_bits(),
6230 got.crop_r.to_bits(),
6231 got.crop_t.to_bits(),
6232 got.crop_b.to_bits(),
6233 got.opacity.to_bits(),
6234 ),
6235 (
6236 want.pos_x.to_bits(),
6237 want.pos_y.to_bits(),
6238 want.scale.to_bits(),
6239 want.rotate.to_bits(),
6240 want.crop_l.to_bits(),
6241 want.crop_r.to_bits(),
6242 want.crop_t.to_bits(),
6243 want.crop_b.to_bits(),
6244 want.opacity.to_bits(),
6245 ),
6246 "transform {i} came back as other bits"
6247 );
6248 }
6249 assert_eq!(back.transform.len(), 3);
6250 }
6251
6252 /// The whole of the v9 bump, the speed test's twin: the mix a project was
6253 /// left at -- every track's own volume and the master limiter -- plus the
6254 /// rate it was cut at, all written, all read back as the very numbers, and
6255 /// a v8 file (which has none of them) loading flat and unlimited.
6256 #[test]
6257 fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
6258 let dir = PathBuf::from("/proj");
6259 let sources = vec![Source::new("/proj/a.mp4", 0)];
6260 let lanes = vec![
6261 (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
6262 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6263 // A second audio track, turned down: the gain lines are per lane,
6264 // so the two must not run into one another.
6265 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6266 ];
6267 let limiter = Limiter {
6268 ceiling_db: -1.5,
6269 on: true,
6270 };
6271 let bytes = super::emit(
6272 &dir,
6273 &sources,
6274 &lanes,
6275 &[0.0, 3.0, -6.5],
6276 &[],
6277 &[],
6278 &[],
6279 &[],
6280 &[],
6281 (1280, 720),
6282 Some(23.976023976023978),
6283 crate::tonemap::Preset::default(),
6284 false,
6285 true,
6286 crate::export::EncoderSeat::default(),
6287 limiter,
6288 None,
6289 0,
6290 );
6291 assert_eq!(
6292 String::from_utf8_lossy(&bytes),
6293 "edith 30\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
6294 limiter -1.5 on\nsource 0 a.mp4\n\
6295 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\
6296 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6297 gain audio 1 3.0\ngain audio 2 -6.5\n",
6298 "the mix is lines of its own, the gains after the lanes they name"
6299 );
6300 let back = parse(&bytes, &dir).expect("parse");
6301 assert_eq!(back.lanes, lanes);
6302 assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
6303 assert_eq!(back.limiter, limiter);
6304 assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
6305
6306 // ...and the dialect before it, which carried none of the three: a v8
6307 // file mixes flat, limits nothing, and says nothing about its rate.
6308 let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6309 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6310 let old = parse(v8, &dir).expect("v8 parses");
6311 assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
6312 assert_eq!(old.limiter, Limiter::default());
6313 assert_eq!(old.fps, None);
6314 // A v9 file may leave all three out too, and means the same thing.
6315 assert_eq!(
6316 String::from_utf8_lossy(&emit(
6317 &dir,
6318 &old.sources,
6319 &old.lanes,
6320 &old.eq,
6321 &old.color,
6322 (1280, 720),
6323 old.playhead
6324 )),
6325 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6326 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"
6327 );
6328
6329 // Each of the three refuses by name, on its own line.
6330 for (text, want) in [
6331 (
6332 "edith 9\nfps nope\nsource 0 a.mp4\n",
6333 "line 2: \"nope\" is not a frame rate",
6334 ),
6335 (
6336 "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
6337 "line 2: limiter is on or off, not \"maybe\"",
6338 ),
6339 (
6340 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
6341 "line 4: gain names a lane that is not there",
6342 ),
6343 (
6344 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
6345 "line 4: gain names \"lane\", not a lane kind",
6346 ),
6347 ] {
6348 assert_eq!(
6349 parse(text.as_bytes(), &dir).unwrap_err().to_string(),
6350 want,
6351 "{text:?}"
6352 );
6353 }
6354 // A hand-written ceiling nothing could limit at is clamped, not taken.
6355 let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
6356 assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
6357 }
6358
6359 /// The refusals the colour grammar adds, each naming its line.
6360 #[test]
6361 fn a_malformed_colour_names_its_line() {
6362 let dir = PathBuf::from("/proj");
6363 let head = "edith 6\nsource 0 a.mp4\n";
6364 // v6, deliberately: the colour grammar is the same one v7 inherits, and
6365 // a v6 clip line is one field shorter.
6366 for (file, want) in [
6367 (
6368 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
6369 "line 3: color wants 4 fields, found 3",
6370 ),
6371 (
6372 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"),
6373 "line 3: color wants 1 fields, found 2",
6374 ),
6375 (
6376 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6377 "line 3: \"warm\" is not a number",
6378 ),
6379 // The two values the format cannot write and read back as itself.
6380 (
6381 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6382 "line 3: \"inf\" is not a number",
6383 ),
6384 (
6385 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
6386 "line 3: \"NaN\" is not a number",
6387 ),
6388 (
6389 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
6390 "line 4: clip names color 1 of 1",
6391 ),
6392 (
6393 format!("{head}video 1 0 0 5 0 - - 0\n"),
6394 "line 3: clip names color 0 of 0",
6395 ),
6396 // A clip's colour field is not optional in v6, and the table has to
6397 // be declared before the clip that names it.
6398 (
6399 format!("{head}video 1 0 0 5 0 - -\n"),
6400 "line 3: clip wants 7 fields, found 6",
6401 ),
6402 (
6403 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
6404 "line 4: color after a clip",
6405 ),
6406 // ...and a colour line in a file that predates them is a corrupt one.
6407 (
6408 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
6409 "line 3: unknown keyword \"color\"",
6410 ),
6411 ] {
6412 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6413 }
6414 }
6415
6416 /// The cut shapes are two more spellings of the same band grammar: they
6417 /// round-trip bit-exactly like the others, and a cut's gain is written as
6418 /// it was given even though the filter ignores it.
6419 #[test]
6420 fn cut_bands_round_trip_as_lc_and_hc() {
6421 let dir = PathBuf::from("/proj");
6422 let sources = vec![source("/proj/a.mp4", 0)];
6423 let eq = vec![EqParams {
6424 bands: vec![
6425 band_of(80.0, 0.0, 0.707, BandKind::LowCut),
6426 band_of(12_000.0, -6.5, 0.5, BandKind::HighCut),
6427 ],
6428 }];
6429 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], Vec::new());
6430 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
6431 assert!(
6432 String::from_utf8_lossy(&bytes).contains("eq 80.0:0.0:0.707:lc 12000.0:-6.5:0.5:hc\n"),
6433 "the cut shapes are spelled lc and hc"
6434 );
6435
6436 let back = parse(&bytes, &dir).expect("parse");
6437 assert_eq!(back.eq, eq, "both cut bands come back as they went in");
6438 assert_eq!(back.lanes, lanes);
6439 }
6440
6441 /// The refusals the eq grammar adds, each naming its line.
6442 #[test]
6443 fn a_malformed_equalizer_names_its_line() {
6444 let dir = PathBuf::from("/proj");
6445 let head = "edith 5\nsource 0 a.mp4\n";
6446 for (file, want) in [
6447 (
6448 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
6449 "line 3: band wants 4 fields, found 3",
6450 ),
6451 (
6452 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
6453 "line 3: \"notch\" is not a band shape",
6454 ),
6455 (
6456 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
6457 "line 3: \"wide\" is not a number",
6458 ),
6459 // Neither of the two values a coefficient cannot be built from, and
6460 // NaN would not even compare equal to itself on the way back.
6461 (
6462 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6463 "line 3: \"inf\" is not a number",
6464 ),
6465 (
6466 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6467 "line 3: \"NaN\" is not a number",
6468 ),
6469 (
6470 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
6471 "line 4: clip names eq 1 of 1",
6472 ),
6473 (
6474 format!("{head}video 1 0 0 5 0 - 0\n"),
6475 "line 3: clip names eq 0 of 0",
6476 ),
6477 // A clip's eq field is not optional in v5, and the table has to be
6478 // declared before the clip that names it.
6479 (
6480 format!("{head}video 1 0 0 5 0 -\n"),
6481 "line 3: clip wants 6 fields, found 5",
6482 ),
6483 (
6484 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
6485 "line 4: eq after a clip",
6486 ),
6487 // ...and an eq line in a file that predates them is a corrupt file.
6488 (
6489 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
6490 "line 3: unknown keyword \"eq\"",
6491 ),
6492 ] {
6493 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6494 }
6495 }
6496
6497 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
6498 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
6499 /// and not one byte else.
6500 #[test]
6501 fn a_v4_file_equalizes_nothing() {
6502 let dir = PathBuf::from("/proj");
6503 let (_, sources, lanes) = doc();
6504 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6505 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
6506 let old = parse(v4, &dir).expect("v4 parses");
6507 assert_eq!(
6508 (&old.sources, &old.lanes, old.playhead),
6509 (&sources, &lanes, 12)
6510 );
6511 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
6512 assert_eq!(
6513 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
6514 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6515 source 2 /elsewhere/b.mp4\n\
6516 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\
6517 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n"
6518 );
6519 // An empty lane's line is still the whole of that lane, eq or no eq.
6520 let empty = parse(
6521 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
6522 &dir,
6523 )
6524 .expect("parse");
6525 assert!(empty.lanes[1].1.is_empty());
6526 }
6527
6528 /// The other half of the compatibility promise: a v3 file is a v4 one
6529 /// without the lane numbers, and a v2 file names no audio stream and means
6530 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
6531 /// they always were, and saving either writes v5 with nothing else changed.
6532 #[test]
6533 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
6534 let dir = PathBuf::from("/proj");
6535 let (_, _, lanes) = doc();
6536 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6537 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6538 let old = parse(v3, &dir).expect("v3 parses");
6539 assert_eq!(
6540 (&old.sources, &old.lanes, old.playhead),
6541 (
6542 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
6543 &lanes,
6544 12
6545 ),
6546 "a v3 file loads as exactly the state its v5 twin does"
6547 );
6548 // ...and re-saved it *is* that twin: the magic and a lane number per
6549 // clip line, and not one byte else.
6550 assert_eq!(
6551 flat(&dir, &old.sources, &old.lanes, old.playhead),
6552 flat(&dir, &old.sources, &lanes, 12),
6553 );
6554
6555 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
6556 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6557 let back = parse(v2, &dir).expect("v2 parses");
6558 assert_eq!(
6559 back.sources,
6560 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
6561 );
6562 assert_eq!(back.lanes, lanes);
6563
6564 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6565 assert_eq!(
6566 String::from_utf8_lossy(&v5),
6567 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6568 source 0 /elsewhere/b.mp4\n\
6569 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\
6570 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
6571 "a re-saved v2 project differs only by its version, the lane \
6572 numbers, the streams it always meant and an equalizer it has none of"
6573 );
6574 let again = parse(&v5, &dir).expect("v5 parses");
6575 assert_eq!(again.sources, back.sources);
6576 }
6577
6578 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
6579 /// lanes, and saving it again writes v5.
6580 #[test]
6581 fn a_v1_file_loads_as_two_grouped_lanes() {
6582 let dir = PathBuf::from("/proj");
6583 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
6584 let back = parse(v1, &dir).expect("v1 parses");
6585 assert_eq!(
6586 back.lanes[0].1,
6587 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
6588 "v1 clips queue up: the second starts where the first ended"
6589 );
6590 assert_eq!(
6591 back.lanes,
6592 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
6593 "one take per clip, on both lanes"
6594 );
6595 assert_eq!(back.playhead, 5);
6596 // Saved again it is the current version, which round-trips to the
6597 // same document.
6598 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6599 assert!(v5.starts_with(b"edith 30\n"));
6600 let again = parse(&v5, &dir).expect("v5 parses");
6601 assert_eq!(again.lanes, back.lanes);
6602 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
6603 for (bytes, want) in [
6604 (
6605 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
6606 "line 3: unknown keyword \"video\"",
6607 ),
6608 (
6609 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
6610 "line 3: unknown keyword \"clip\"",
6611 ),
6612 ] {
6613 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
6614 }
6615 }
6616
6617 /// A gap is the absence of a line, so a lane's placements must arrive in
6618 /// order and never overlap -- the invariant the whole model rests on.
6619 #[test]
6620 fn a_lane_out_of_order_or_overlapping_is_refused() {
6621 let dir = PathBuf::from("/proj");
6622 for bytes in [
6623 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
6624 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
6625 ] {
6626 let err = parse(bytes, &dir).unwrap_err().to_string();
6627 assert!(err.starts_with("line 4: clip at "), "{err}");
6628 }
6629 // The lanes are independent, so a video line never crowds an audio one.
6630 assert!(
6631 parse(
6632 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
6633 &dir
6634 )
6635 .is_ok()
6636 );
6637 // ...and a lane may be empty as long as the other one is not.
6638 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
6639 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
6640 }
6641
6642 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
6643 /// and wrap in release, and a wrapped end passes the overlap check --
6644 /// crafted numbers must be refused by name, in both dialects.
6645 #[test]
6646 fn a_clip_whose_end_overflows_is_refused() {
6647 let dir = PathBuf::from("/proj");
6648 for bytes in [
6649 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
6650 // Two of them: the second would land *before* the first once wrapped.
6651 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
6652 // v1 has no `start` field, but its queue reaches the same ceiling.
6653 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
6654 ] {
6655 let err = parse(bytes, &dir).unwrap_err().to_string();
6656 assert!(
6657 err.contains("runs past the last frame there is"),
6658 "not refused by name: {err}"
6659 );
6660 }
6661 }
6662
6663 /// The relocatability promise, from the two directions a project path
6664 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
6665 /// clip.mp4`, whose parent is `""`) and a directory reached through a
6666 /// symlink. Both used to emit absolute source lines.
6667 #[test]
6668 fn a_non_canonical_project_path_still_writes_relative_sources() {
6669 assert_eq!(
6670 project_dir(Path::new("a.edith")),
6671 std::env::current_dir().expect("cwd"),
6672 "a bare filename is saved into the working directory"
6673 );
6674
6675 let dir = crate::scratch::Scratch::dir("ve_edith_link");
6676 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
6677 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
6678 let source = dir.join("real/a.mp4");
6679 let path = dir.join("link/p.edith");
6680
6681 let one = [clip(0, 0, 30, 0, None)];
6682 let entry = Source {
6683 path: source,
6684 audio_stream: 1, ..Default::default()
6685 };
6686 save(
6687 &path,
6688 &[entry],
6689 &two(one.to_vec(), one.to_vec()),
6690 &[],
6691 &[],
6692 &[],
6693 &[],
6694 &[],
6695 &[],
6696 (1280, 720),
6697 None,
6698 crate::tonemap::Preset::default(),
6699 false,
6700 true,
6701 crate::export::EncoderSeat::default(),
6702 Limiter::default(),
6703 None,
6704 0,
6705 )
6706 .expect("save");
6707 let bytes = std::fs::read(&path).expect("read back");
6708 assert_eq!(
6709 String::from_utf8_lossy(&bytes),
6710 "edith 30\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
6711 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"
6712 );
6713 // Loading rejoins the *given* directory, so the file is reached by the
6714 // way the project was opened -- the same file, through the link, still
6715 // playing the stream it was saved on.
6716 assert_eq!(
6717 load(&path).expect("load").sources,
6718 vec![Source {
6719 path: dir.join("link/a.mp4"),
6720 audio_stream: 1, ..Default::default()
6721 }]
6722 );
6723 std::fs::remove_dir_all(&dir).expect("cleanup");
6724 }
6725
6726 #[test]
6727 fn escapes_survive_the_bytes_json_would_not() {
6728 let dir = PathBuf::from("/proj");
6729 // A newline and a percent in a filename, plus a non-UTF-8 byte.
6730 let nasty = Source {
6731 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
6732 audio_stream: 0, ..Default::default()
6733 };
6734 let bytes = flat(
6735 &dir,
6736 std::slice::from_ref(&nasty),
6737 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
6738 0,
6739 );
6740 assert_eq!(
6741 bytes.iter().filter(|&&b| b == b'\n').count(),
6742 6,
6743 "the escaped newline must not become a line break: magic, playhead, \
6744 resolution, source, the clip, and the empty audio lane's own line"
6745 );
6746 let back = parse(&bytes, &dir).expect("parse");
6747 // The spaces in it are the reason the stream field leads rather than
6748 // trails: everything after the first one is path.
6749 assert_eq!(back.sources, vec![nasty]);
6750 }
6751
6752 /// A `flags` line names its lane the way a gain does and carries only the
6753 /// switches its kind of lane can have. A lane with none has no line, so a
6754 /// v23 file -- which has no such line -- parses with every switch clear, and
6755 /// one that carries the line before v24 is an unknown keyword.
6756 #[test]
6757 fn lane_switches_parse_by_kind_and_a_v23_file_has_none() {
6758 let dir = PathBuf::from("/proj");
6759 let doc = parse(
6760 b"edith 24\nvideo 1\naudio 1\nsub 1\nflags video 1 hidden locked\nflags audio 1 muted\nflags sub 1 hidden\n",
6761 &dir,
6762 )
6763 .expect("a v24 file with switches parses");
6764 assert_eq!(
6765 doc.flags,
6766 vec![
6767 LaneFlags {
6768 hidden: true,
6769 muted: false,
6770 locked: true,
6771 pan: 0.0,
6772 },
6773 LaneFlags {
6774 hidden: false,
6775 muted: true,
6776 locked: false,
6777 pan: 0.0,
6778 },
6779 LaneFlags {
6780 hidden: true,
6781 muted: false,
6782 locked: false,
6783 pan: 0.0,
6784 },
6785 ]
6786 );
6787
6788 let plain = parse(b"edith 24\nvideo 1\naudio 1\n", &dir).expect("no switches");
6789 assert_eq!(plain.flags, vec![LaneFlags::default(); 2]);
6790 let old = parse(b"edith 23\nvideo 1\naudio 1\n", &dir).expect("a v23 file loads");
6791 assert_eq!(
6792 old.flags,
6793 vec![LaneFlags::default(); 2],
6794 "every switch clear"
6795 );
6796
6797 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
6798 assert!(
6799 refuse(b"edith 24\nvideo 1\nflags video 1 hidden hidden\n").contains("twice"),
6800 "a switch named twice"
6801 );
6802 assert!(
6803 refuse(b"edith 24\naudio 1\nflags audio 1 hidden\n").contains("cannot be set"),
6804 "a hidden audio lane"
6805 );
6806 assert!(
6807 refuse(b"edith 24\nvideo 1\nflags video 1 muted\n").contains("cannot be set"),
6808 "a muted video lane"
6809 );
6810 assert!(
6811 refuse(b"edith 24\nvideo 1\nflags video 2 hidden\n").contains("not there"),
6812 "a lane that is not there"
6813 );
6814 assert!(
6815 refuse(b"edith 24\nvideo 1\nflags video 1\n").contains("no switch"),
6816 "a line with no switch"
6817 );
6818 assert!(
6819 refuse(b"edith 23\nvideo 1\nflags video 1 hidden\n").contains("unknown keyword"),
6820 "a flags line before v24 is not a dialect"
6821 );
6822 }
6823
6824 #[test]
6825 fn a_duck_line_round_trips_and_is_bounded_by_name() {
6826 let dir = PathBuf::from("/proj");
6827 let head = "edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6828 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6829 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6830 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
6831 let ok = parse(
6832 format!("{head}duck audio 2 1 -12.0 -40.0 80.0 400.0\n").as_bytes(),
6833 &dir,
6834 )
6835 .expect("a duck of A2 under A1 parses");
6836 assert_eq!(
6837 ok.ducks,
6838 vec![
6839 vec![],
6840 vec![],
6841 vec![crate::duck::Duck {
6842 under: 0,
6843 depth_db: -12.0,
6844 threshold_db: -40.0,
6845 attack_ms: 80.0,
6846 release_ms: 400.0,
6847 }]
6848 ],
6849 "one list per lane, the key named 0-based in the struct"
6850 );
6851 let refuse = |line: &str| {
6852 parse(format!("{head}{line}\n").as_bytes(), &dir)
6853 .unwrap_err()
6854 .to_string()
6855 };
6856 assert!(refuse("duck audio 2 2 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
6857 assert!(refuse("duck audio 2 3 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
6858 assert!(refuse("duck audio 2 0 -12.0 -40.0 80.0 400.0").contains("lane 0"));
6859 assert!(refuse("duck audio 2 1 -41.0 -40.0 80.0 400.0").contains("out of its range"));
6860 assert!(refuse("duck audio 2 1 -12.0 -40.0 0.0 400.0").contains("out of its range"));
6861 assert!(refuse("duck video 1 1 -12.0 -40.0 80.0 400.0").contains("not an audio lane"));
6862 // A dialect before v25 has no ducks, so the same line is an unknown one.
6863 let v24 = format!(
6864 "{}duck audio 2 1 -12.0 -40.0 80.0 400.0\n",
6865 head.replacen("edith 25", "edith 24", 1)
6866 );
6867 assert!(
6868 parse(v24.as_bytes(), &dir)
6869 .unwrap_err()
6870 .to_string()
6871 .contains("unknown keyword"),
6872 "a v24 file cannot carry a duck"
6873 );
6874 // ...and a v24 file without one still loads, with every lane unducked.
6875 let old = parse(head.replacen("edith 25", "edith 24", 1).as_bytes(), &dir)
6876 .expect("v24 still loads");
6877 assert!(old.ducks.iter().all(Vec::is_empty));
6878 }
6879
6880 /// The v42 `effect` lines: a clip's whole stack round-trips in order, switch and
6881 /// every value included, through the same `save_flagged` every save takes; a project
6882 /// with no effect keeps its older header; a v41 file refuses the line; a bad line is
6883 /// refused by name.
6884 #[test]
6885 fn effect_lines_round_trip_in_v42_and_older_files_refuse_them() {
6886 use crate::effects::{Effect, EffectKind};
6887 let dir = std::env::temp_dir().join(format!("edith-effects-{}", std::process::id()));
6888 std::fs::create_dir_all(&dir).unwrap();
6889 let path = dir.join("fx.edith");
6890 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
6891 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
6892 save_flagged(
6893 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
6894 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
6895 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
6896 )
6897 .expect("saves");
6898 std::fs::read_to_string(&path).unwrap()
6899 };
6900 let plain = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
6901 let before = save(&plain);
6902 assert!(!before.starts_with("edith 42") && !before.contains("effect"), "{before}");
6903 let mut lanes = plain.clone();
6904 let mut blur = Effect::new(EffectKind::Blur);
6905 blur.set("radius", 12.25).unwrap();
6906 let mut key = Effect::new(EffectKind::ChromaKey);
6907 key.on = false;
6908 key.set("tolerance", 0.123_456_7).unwrap();
6909 let stack = vec![Effect::new(EffectKind::Vignette), blur, key, Effect::new(EffectKind::EllipseMask)];
6910 lanes[0].1[0].effects = stack.clone();
6911 let text = save(&lanes);
6912 assert!(text.starts_with("edith 42\n"), "an effect makes it v42: {text}");
6913 assert!(text.contains("\neffect video 1 0 blur 1 12.25\n"), "{text}");
6914 assert!(text.contains("\neffect video 1 0 chroma_key 0 0 255 0 0.1234567 0.1 0.5\n"), "{text}");
6915 let back = load(&path).expect("v42 loads");
6916 assert_eq!(back.lanes[0].1[0].effects, stack, "order, switches and values survive");
6917 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
6918 lanes[0].1[0].effects.clear();
6919 assert_eq!(save(&lanes), before, "no effect: the bytes it was");
6920 std::fs::remove_dir_all(&dir).ok();
6921
6922 let dir = PathBuf::from("/proj");
6923 let video_head = "edith 42\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6924 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";
6925 let doc = parse(format!("{video_head}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).expect("parses");
6926 assert_eq!(doc.lanes[0].1[0].effects[0].get("amount"), Some(0.5));
6927 let refuse = |line: &str| parse(format!("{video_head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
6928 assert!(refuse("effect video 1 0 sparkle 1 0.5").contains("not one"));
6929 assert!(refuse("effect video 1 0 sharpen 2 0.5").contains("not 0 or 1"));
6930 assert!(refuse("effect video 1 0 sharpen 1 9").contains("out of its range"));
6931 assert!(refuse("effect video 1 0 vignette 1 0.5").contains("wants 2 values"));
6932 assert!(refuse("effect video 1 4 sharpen 1 0.5").contains("does not have"));
6933 assert!(refuse("effect audio 1 0 sharpen 1 0.5").contains("wants a video clip"));
6934 assert!(refuse("effect video 2 0 sharpen 1 0.5").contains("not there"));
6935 let v41 = video_head.replacen("edith 42", "edith 41", 1);
6936 let err = parse(format!("{v41}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).unwrap_err().to_string();
6937 assert!(err.contains("unknown keyword \"effect\""), "{err}");
6938 }
6939
6940 /// The v50 pan lines: a clip pan and a lane pan round-trip, a project with neither keeps its
6941 /// header and its bytes, and an out-of-range or unknown-lane pan is refused by name.
6942 #[test]
6943 fn pan_lines_round_trip_in_v50() {
6944 let dir = std::env::temp_dir().join(format!("edith-pan-{}", std::process::id()));
6945 std::fs::create_dir_all(&dir).unwrap();
6946 let path = dir.join("pan.edith");
6947 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
6948 let save = |lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]| {
6949 save_flagged(
6950 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
6951 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
6952 Limiter::default(), None, 0, flags, &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
6953 )
6954 .expect("saves");
6955 std::fs::read_to_string(&path).unwrap()
6956 };
6957 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))]);
6958 let before = save(&plain, &[]);
6959 assert!(!before.contains("pan"), "{before}");
6960 let mut lanes = plain.clone();
6961 lanes[1].1[1].pan = -25;
6962 let flags = [LaneFlags::default(), LaneFlags { pan: 0.5, locked: true, ..LaneFlags::default() }];
6963 let text = save(&lanes, &flags);
6964 assert!(text.starts_with("edith 50\n"), "{text}");
6965 assert!(text.contains("\nlanepan audio 1 0.5\n") && text.contains("\nclippan audio 1 1 -0.25\n"), "{text}");
6966 let back = load(&path).expect("v50 loads");
6967 assert_eq!(back.lanes[1].1[1].pan, -25);
6968 assert_eq!(back.lanes[1].1[0].pan, 0);
6969 assert_eq!(back.flags[1].pan, 0.5);
6970 assert!(back.flags[1].locked, "the switches stay");
6971 assert_eq!(save(&back.lanes, &back.flags), text, "saved again: the same bytes");
6972 let dirp = PathBuf::from("/proj");
6973 let head = "edith 50\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6974 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";
6975 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
6976 assert!(refuse("clippan audio 1 0 2").contains("out of its range"));
6977 assert!(refuse("clippan audio 1 4 0.5").contains("does not have"));
6978 assert!(refuse("lanepan audio 3 0.5").contains("not there"));
6979 assert!(refuse("lanepan video 1 0.5").contains("not an audio lane"));
6980 let old = head.replacen("edith 50", "edith 49", 1);
6981 let err = parse(format!("{old}lanepan audio 1 0.5\n").as_bytes(), &dirp).unwrap_err().to_string();
6982 assert!(err.contains("unknown keyword"), "{err}");
6983 std::fs::remove_dir_all(&dir).ok();
6984 }
6985
6986
6987 /// The v55 pitch lines: a clip's semitones round-trip and a project with none is the bytes a
6988 /// v51 one was; an out-of-range, unknown-lane or unknown-clip pitch is refused by name, and a
6989 /// pitch line under an older header is refused as unknown.
6990 #[test]
6991 fn pitch_lines_round_trip_in_v55() {
6992 let dir = std::env::temp_dir().join(format!("edith-pitch-{}", std::process::id()));
6993 std::fs::create_dir_all(&dir).unwrap();
6994 let path = dir.join("pitch.edith");
6995 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
6996 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
6997 save_flagged(
6998 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
6999 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7000 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7001 )
7002 .expect("saves");
7003 std::fs::read_to_string(&path).unwrap()
7004 };
7005 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))]);
7006 let before = save(&plain);
7007 assert!(!before.contains("pitch"), "{before}");
7008 assert!(!before.starts_with("edith 55"), "{before}");
7009 let mut lanes = plain.clone();
7010 lanes[1].1[1].pitch = -7;
7011 let text = save(&lanes);
7012 assert!(text.starts_with("edith 55\n"), "{text}");
7013 assert!(text.contains("\npitch audio 1 1 -7\n"), "{text}");
7014 let back = load(&path).expect("v55 loads");
7015 assert_eq!(back.lanes[1].1[1].pitch, -7);
7016 assert_eq!(back.lanes[1].1[0].pitch, 0);
7017 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7018 let dirp = PathBuf::from("/proj");
7019 let head = "edith 55\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7020 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";
7021 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7022 assert!(refuse("pitch audio 1 0 13").contains("out of its range"));
7023 assert!(refuse("pitch audio 1 0 1.5").contains("out of its range"));
7024 assert!(refuse("pitch audio 1 4 3").contains("does not have"));
7025 assert!(refuse("pitch audio 3 0 3").contains("not there"));
7026 assert!(refuse("pitch video 1 0 3").contains("not an audio lane"));
7027 let old = head.replacen("edith 55", "edith 51", 1);
7028 let err = parse(format!("{old}pitch audio 1 0 3\n").as_bytes(), &dirp).unwrap_err().to_string();
7029 assert!(err.contains("unknown keyword"), "{err}");
7030 std::fs::remove_dir_all(&dir).ok();
7031 }
7032
7033 /// The v51 library lines: bins, filed sources and starred ones round-trip; a project with
7034 /// none keeps its v50 bytes; the lines are refused in v50 and bad ones by name.
7035 #[test]
7036 fn library_lines_round_trip_with_mask_keys_in_v53() {
7037 use crate::project::Bin;
7038 let dir = std::env::temp_dir().join(format!("edith-bins-{}", std::process::id()));
7039 std::fs::create_dir_all(&dir).unwrap();
7040 let path = dir.join("bins.edith");
7041 let mut src = vec![
7042 Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() },
7043 Source { path: dir.join("b.mp4"), audio_stream: 0, ..Default::default() },
7044 ];
7045 let mut lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7046 let mut mask = crate::effects::Effect::new(crate::effects::EffectKind::EllipseMask);
7047 mask.keys = vec![crate::effects::MaskKey {
7048 at: 0, x: 0.5, y: 0.5, width: 0.4, height: 0.4, feather: 0.02, ease: KeyEase::Linear,
7049 }];
7050 lanes[0].1[0].effects = vec![mask];
7051 let save = |src: &[Source], bins: &[Bin]| {
7052 let main = encode_flagged(
7053 &dir, src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7054 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7055 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7056 );
7057 let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS);
7058 std::fs::write(&path, &bytes).unwrap();
7059 String::from_utf8(bytes).unwrap()
7060 };
7061 let plain = save(&src, &[]);
7062 assert!(plain.starts_with("edith 45\n") || !plain.starts_with("edith 51"), "{plain}");
7063 assert!(!plain.contains("bin") && !plain.contains("srcfav"), "{plain}");
7064 let bins = vec![
7065 Bin { id: 1, parent: 0, name: "Interviews \"A\"".into() },
7066 Bin { id: 3, parent: 1, name: "B roll".into() },
7067 ];
7068 src[0].bin = 3;
7069 src[1].fav = true;
7070 src[1].bin = 1;
7071 let text = save(&src, &bins);
7072 // A mask key is v53, and the library and the notes lines keep it there.
7073 assert!(text.starts_with("edith 53\n"), "{text}");
7074 assert!(text.contains("\nsrcbin 0 3\n") && text.contains("\nsrcfav 1\n"), "{text}");
7075 assert!(text.contains("\nmkeys video ") && text.contains("\nnotes Two cuts\n"), "{text}");
7076 let back = load(&path).expect("v53 loads");
7077 assert_eq!(back.notes, "Two cuts");
7078 assert_eq!(back.bins, bins);
7079 assert_eq!((back.sources[0].bin, back.sources[0].fav), (3, false));
7080 assert_eq!((back.sources[1].bin, back.sources[1].fav), (1, true));
7081 assert_eq!(save(&back.sources, &back.bins), text, "saved again: the same bytes");
7082 let dirp = PathBuf::from("/proj");
7083 let head = "edith 51\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7084 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";
7085 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7086 assert!(refuse("bin 1 0").contains("wants an id"));
7087 assert!(refuse("bin 0 0 x").contains("not a new id"));
7088 assert!(refuse("bin 1 0 x\nbin 1 0 y").contains("not a new id"));
7089 assert!(refuse("bin 2 1 x").contains("not a top-level bin"));
7090 assert!(refuse("bin 1 0 x\nbin 2 0 X").contains("two bins named"));
7091 assert!(refuse("bin 1 0 x\nbin 2 1 y\nbin 3 2 z").contains("not a top-level bin"));
7092 assert!(refuse("srcbin 0 9").contains("not defined"));
7093 assert!(refuse("bin 1 0 x\nsrcbin 4 1").contains("does not have"));
7094 assert!(refuse("srcfav 7").contains("does not have"));
7095 let old = head.replacen("edith 51", "edith 50", 1);
7096 for line in ["bin 1 0 x", "srcfav 0"] {
7097 let err = parse(format!("{old}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7098 assert!(err.contains("unknown keyword"), "{err}");
7099 }
7100 std::fs::remove_dir_all(&dir).ok();
7101 }
7102
7103 /// The v41 `voice` lines: every processor of an audio lane (the noise profile included)
7104 /// round-trips bit for bit; a lane with no voice setting writes none, so a project nobody
7105 /// has cleaned keeps its older header and its exact bytes; a v40 file loads with every
7106 /// processor off and refuses the lines; a number out of range is refused by name.
7107 /// The v43 look lines: wheels, curves and a LUT path (relative inside the
7108 /// project folder) round trip bit-exactly; a grade without a look writes none
7109 /// and stays under its old header; a missing LUT still loads; bad lines are
7110 /// refused by name.
7111 #[test]
7112 fn look_lines_round_trip_in_v43() {
7113 use crate::color::{Curve, Look, Wheels};
7114 let dir = std::env::temp_dir().join(format!("edith-look-{}", std::process::id()));
7115 std::fs::create_dir_all(dir.join("luts")).unwrap();
7116 let cube = dir.join("luts/warm look.cube");
7117 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();
7118 let path = dir.join("look.edith");
7119 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7120 let lanes = two(
7121 vec![Clip { color: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { color: Some(1), ..clip(30, 0, 30, 0, Some(0)) }],
7122 vec![clip(0, 0, 60, 0, Some(0))],
7123 );
7124 let look = Look {
7125 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] },
7126 curves: [
7127 Curve::new(&[[0.25, 0.2], [0.75, 0.8]]).unwrap(),
7128 Curve::default(),
7129 Curve::new(&[[0.0, 0.1], [0.5, 0.5], [1.0, 0.95]]).unwrap(),
7130 Curve::default(),
7131 ],
7132 lut: Some(crate::cube::LutRef::open(&cube)),
7133 lut_mix: 0.7,
7134 };
7135 let color = vec![ColorParams { contrast: 1.1, look, ..Default::default() }, ColorParams { tint: 0.2, ..Default::default() }];
7136 let save = |color: &[ColorParams]| {
7137 save_flagged(
7138 &path, &src, &lanes, &[], &[], &[], &[], color, &[], (1280, 720), Some(30.0),
7139 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7140 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7141 )
7142 .expect("saves");
7143 std::fs::read_to_string(&path).unwrap()
7144 };
7145 let text = save(&color);
7146 assert!(text.starts_with("edith 43\n"), "a look makes it v43: {text}");
7147 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}");
7148 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}");
7149 assert!(text.contains("\nlut 0 0.7 luts/warm look.cube\n"), "relative inside the folder: {text}");
7150 assert!(!text.contains("curve 1") && !text.contains("lut 1"), "no look, no lines");
7151 let back = load(&path).expect("v43 loads");
7152 assert_eq!(back.color, color, "every number survives");
7153 assert_eq!(save(&back.color), text, "a re-save is the same file");
7154 // No look: the old header and no look line.
7155 let plain = save(&[color[1], color[1]]);
7156 assert!(plain.starts_with("edith 3") && !plain.contains("wheels") && !plain.contains("\nlut "), "{plain}");
7157 // A missing LUT loads, and says why it cannot be used.
7158 let gone = text.replace("luts/warm look.cube", "luts/gone.cube");
7159 std::fs::write(&path, &gone).unwrap();
7160 let doc = load(&path).expect("a missing LUT still loads");
7161 let lut = doc.color[0].look.lut.expect("named");
7162 assert!(lut.problem().expect("missing").contains("cannot read"));
7163 std::fs::remove_dir_all(&dir).ok();
7164
7165 let head = "edith 43\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\n\
7166 video 1 0 0 30 0 - - 0 fit 1000 0 0 0 - 0 0\n";
7167 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7168 assert!(refuse("wheels 1 0:0:0:0 0:0:0:0 0:0:0:0").contains("names color 1"));
7169 assert!(refuse("wheels 0 2:0:0:0 0:0:0:0 0:0:0:0").contains("outside -1..1"));
7170 assert!(refuse("wheels 0 0:0:0 0:0:0:0 0:0:0:0").contains("4 values"));
7171 assert!(refuse("curve 0 cyan 0.1:0.2").contains("not master"));
7172 assert!(refuse("curve 0 red 0.5:0.2,0.4:0.3").contains("strictly increase"));
7173 assert!(refuse("curve 0 red 0.5").contains("<x>:<y>"));
7174 assert!(refuse("lut 0 1.5 a.cube").contains("0..=1"));
7175 assert!(refuse("lut 0 1.0").contains("<mix> <path>"));
7176 for old in ["edith 42", "edith 41"] {
7177 let older = head.replacen("edith 43", old, 1);
7178 assert!(parse(format!("{older}lut 0 1.0 a.cube\n").as_bytes(), &dir).is_err(), "a {old} file has no lut line");
7179 }
7180 }
7181
7182 #[test]
7183 fn voice_lines_round_trip_in_v41_and_older_files_load_with_them_off() {
7184 use crate::voice::{PROFILE_BANDS, Strength};
7185 let dir = std::env::temp_dir().join(format!("edith-voice-{}", std::process::id()));
7186 std::fs::create_dir_all(&dir).unwrap();
7187 let path = dir.join("voice.edith");
7188 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7189 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7190 let profile: Vec<f32> = (0..PROFILE_BANDS).map(|b| -80.0 + b as f32 * 0.1).collect();
7191 let fx = VoiceFx::clean_voice(Strength::Strong, profile, Some(-52.0));
7192 let save = |voices: &[VoiceFx]| {
7193 save_flagged(
7194 &path, &src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7195 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7196 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), voices, &[],
7197 )
7198 .expect("saves");
7199 std::fs::read_to_string(&path).unwrap()
7200 };
7201 let text = save(&[VoiceFx::default(), fx.clone()]);
7202 assert!(text.starts_with("edith 41\n"), "a voice makes it v41: {text}");
7203 for kind in ["gate", "nr", "comp", "deess"] {
7204 assert!(text.contains(&format!("\nvoice audio 1 {kind} 1 ")), "{kind}: {text}");
7205 }
7206 let back = load(&path).expect("v41 loads");
7207 assert_eq!(back.voices, vec![VoiceFx::default(), fx.clone()], "every number and the profile survive");
7208 // Saved again from what was loaded: the same bytes.
7209 let again = save(&back.voices);
7210 assert_eq!(again, text);
7211 // Only what differs from the default is written, and a lane with nothing writes no line.
7212 let comp_only = VoiceFx { comp: Compressor { on: true, ..Compressor::DEFAULT }, ..Default::default() };
7213 let text = save(&[VoiceFx::default(), comp_only.clone()]);
7214 assert_eq!(text.matches("\nvoice ").count(), 1, "{text}");
7215 assert_eq!(load(&path).unwrap().voices[1], comp_only);
7216 // Nothing set: not v41 and no voice line -- the bytes a v40 save wrote.
7217 let plain = save(&[VoiceFx::default(), VoiceFx::default()]);
7218 assert!(!plain.contains("voice") && plain.starts_with("edith 3") && !plain.starts_with("edith 41"), "{plain}");
7219 assert_eq!(save(&[]), plain, "no list is the same as a list of defaults");
7220 std::fs::remove_file(&path).ok();
7221
7222 let head = "edith 41\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7223 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";
7224 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7225 assert!(refuse("voice audio 1 gate 1 -45.0 2.0 150.0 60.0 5.0").contains("out of its range"));
7226 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"));
7227 assert!(refuse("voice audio 1 nr 1 0.6 -18.0 -").contains("no noise profile"));
7228 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");
7229 assert!(refuse("voice audio 1 gate 2 -45.0 2.0 150.0 60.0 -18.0").contains("not 0 or 1"));
7230 assert!(refuse("voice audio 1 gate 1 -45.0 2.0").contains("wants 6 fields"));
7231 assert!(refuse("voice audio 1 reverb 1").contains("not a processor"));
7232 assert!(refuse("voice audio 2 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not there"));
7233 assert!(refuse("voice video 1 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not an audio lane"));
7234 // A v40 file carries none, and the same line in one is an unknown keyword.
7235 let v40 = head.replacen("edith 41", "edith 40", 1);
7236 let err = parse(format!("{v40}voice audio 1 gate 1 -45.0 2.0 150.0 60.0 -18.0\n").as_bytes(), &dir)
7237 .unwrap_err()
7238 .to_string();
7239 assert!(err.contains("unknown keyword"), "{err}");
7240 let old = parse(v40.as_bytes(), &dir).expect("v40 still loads");
7241 assert!(old.voices.iter().all(|v| !v.is_active()) && old.voices.len() == 2);
7242 std::fs::remove_dir_all(&dir).ok();
7243 }
7244
7245 #[test]
7246 fn a_lane_ducked_under_two_keys_round_trips_in_v30() {
7247 let dir = PathBuf::from("/proj");
7248 let head = "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7249 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7250 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7251 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7252 audio 3 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7253 let two = format!(
7254 "{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"
7255 );
7256 let ok = parse(two.as_bytes(), &dir).expect("two keys for A3 parse");
7257 assert_eq!(ok.ducks[3].len(), 2, "both ducks kept, in file order");
7258 assert_eq!(ok.ducks[3][0].under, 0);
7259 assert_eq!(ok.ducks[3][1].under, 1);
7260 let refuse = |text: String| parse(text.as_bytes(), &dir).unwrap_err().to_string();
7261 assert!(
7262 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"))
7263 .contains("same key twice")
7264 );
7265 // A v29 file cannot hold two for one lane: refused by name, not dropped.
7266 let v29 = format!(
7267 "{}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",
7268 head.replacen("edith 30", "edith 29", 1)
7269 );
7270 assert!(refuse(v29).contains("names a lane twice"));
7271 }
7272
7273 #[test]
7274 fn a_wrong_first_line_is_refused_by_name() {
7275 let dir = PathBuf::from("/proj");
7276 let err = parse(b"edith 56\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
7277 .unwrap_err()
7278 .to_string();
7279 assert_eq!(err, "line 1: unsupported version 56");
7280 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
7281 assert_eq!(
7282 parse(junk, &dir).unwrap_err().to_string(),
7283 "line 1: not an edith file"
7284 );
7285 }
7286 }
7287
7288 /// The v34 `chapter` line: a project's chapters are saved in frame order and
7289 /// come back as they were, and a project with none is still a v33-or-older
7290 /// file. A v33 file loads with no chapters, and a chapter line in one is refused.
7291 #[test]
7292 fn chapters_round_trip_and_a_v33_file_loads_without_them() {
7293 use crate::project::Chapter;
7294 let dir = std::env::temp_dir().join(format!("edith-chapters-{}", std::process::id()));
7295 std::fs::create_dir_all(&dir).unwrap();
7296 let path = dir.join("chapters.edith");
7297 let chapters = vec![
7298 Chapter { frame: 0, title: "Intro".into() },
7299 Chapter { frame: 1500, title: "Setup: 100% \\ done".into() },
7300 ];
7301 save_flagged(
7302 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7303 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7304 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &chapters, &[], &CaptionStyle::default(), &[], &[],
7305 )
7306 .expect("a project with chapters saves");
7307 let text = std::fs::read_to_string(&path).unwrap();
7308 assert!(text.starts_with("edith 34\n"), "chapters make it v34: {text}");
7309 assert!(text.contains("\nchapter 0 Intro\nchapter 1500 "), "frame order, one line each: {text}");
7310 let back = load(&path).expect("v34 loads");
7311 assert_eq!(back.chapters, chapters);
7312 std::fs::remove_file(&path).ok();
7313
7314 // A project with no chapters keeps the header it always had.
7315 let bare = b"edith 33\nplayhead 0\nsource 0 a.mp4\n";
7316 let old = parse(bare, &dir).expect("a v33 file loads");
7317 assert!(old.chapters.is_empty());
7318 let mixed = parse(b"edith 33\nsource 0 a.mp4\nchapter 0 Intro\n", &dir)
7319 .unwrap_err()
7320 .to_string();
7321 assert_eq!(mixed, "line 3: unknown keyword \"chapter\"");
7322 // Out of order, a name with none, and a frame that is not a frame are refused.
7323 for line in ["chapter 10 B\nchapter 5 A\n", "chapter 5 \n", "chapter x Intro\n"] {
7324 let file = format!("edith 34\nsource 0 a.mp4\n{line}");
7325 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7326 }
7327 std::fs::remove_dir(&dir).ok();
7328 }
7329
7330 /// The v36 `marker` and `marknote` lines: markers (point and range, with and without a
7331 /// note, two on one frame) round-trip and make the file v36; a v35 file loads with none
7332 /// and refuses the lines; a project with no marker keeps its older header.
7333 #[test]
7334 fn markers_round_trip_and_a_v35_file_loads_without_them() {
7335 use crate::project::{Marker, MarkerColor};
7336 let dir = std::env::temp_dir().join(format!("edith-markers-{}", std::process::id()));
7337 std::fs::create_dir_all(&dir).unwrap();
7338 let path = dir.join("markers.edith");
7339 let mk = |frame, length, name: &str, note: &str, color| Marker { frame, length, name: name.into(), note: note.into(), color };
7340 let markers = vec![
7341 mk(0, 0, "Intro", "", MarkerColor::Blue),
7342 mk(100, 50, "Fix: 100% \\ the cut", "line one\nline two", MarkerColor::Red),
7343 mk(100, 0, "Same frame", "", MarkerColor::Purple),
7344 mk(900, 0, "Late", "has a note", MarkerColor::Green),
7345 ];
7346 let save = |markers: &[Marker]| {
7347 save_flagged(
7348 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7349 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7350 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, &CaptionStyle::default(), &[], &[],
7351 )
7352 .expect("saves");
7353 };
7354 save(&markers);
7355 let text = std::fs::read_to_string(&path).unwrap();
7356 assert!(text.starts_with("edith 36\n"), "markers make it v36: {text}");
7357 assert!(text.contains("\nmarker 0 0 blue Intro\nmarker 100 50 red "), "{text}");
7358 assert!(text.contains("\nmarknote 1 line one\\nline two\nmarknote 3 has a note\n"), "{text}");
7359 assert_eq!(load(&path).expect("v36 loads").markers, markers);
7360 save(&[]);
7361 let text = std::fs::read_to_string(&path).unwrap();
7362 assert!(!text.starts_with("edith 36") && !text.contains("marker"), "no markers, an older file: {text}");
7363 std::fs::remove_file(&path).ok();
7364
7365 let old = parse(b"edith 35\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v35 file loads");
7366 assert!(old.markers.is_empty());
7367 let mixed = parse(b"edith 35\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).unwrap_err().to_string();
7368 assert_eq!(mixed, "line 3: unknown keyword \"marker\"");
7369 for line in [
7370 "marker 10 0 red B\nmarker 5 0 red A\n",
7371 "marker 5 0 red \n",
7372 "marker 5 0 pink A\n",
7373 "marker x 0 red A\n",
7374 "marknote 0 hi\n",
7375 ] {
7376 let file = format!("edith 36\nsource 0 a.mp4\n{line}");
7377 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7378 }
7379 std::fs::remove_dir(&dir).ok();
7380 }
7381
7382 /// The v40 `capstyle` line: an animated caption style round-trips and makes the file v40;
7383 /// the default style writes no line and keeps the older header; a v36 file loads as the
7384 /// default and a v39 file refuses the line; a bad line is refused by name.
7385 /// The v40 `cuewords` lines: word times round-trip through the text, a cue without any
7386 /// writes no line, and a v39 file refuses the line.
7387 #[test]
7388 fn cue_word_times_round_trip_through_the_lines() {
7389 let dir = PathBuf::from("/proj");
7390 let cue = |text: &str, words: Vec<(i64, i64, String)>| crate::subtitle::Cue {
7391 start_us: 0,
7392 end_us: 3_000_000,
7393 text: text.into(),
7394 image: None,
7395 words,
7396 karaoke: Vec::new(),
7397 };
7398 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7399 track.cues = vec![
7400 cue("plain", vec![]),
7401 cue("two words", vec![(0, 1_000_000, "two".into()), (1_000_000, 2_500_000, "words".into())]),
7402 ];
7403 let lines = String::from_utf8(cue_word_lines(&[track])).unwrap();
7404 assert_eq!(lines, "cuewords 0 1 0 1000000 two 1000000 2500000 words\n");
7405 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7406 let doc = parse(file.as_bytes(), &dir).expect("v40 parses");
7407 assert_eq!(
7408 doc.cue_words,
7409 vec![(0, 1, vec![(0, 1_000_000, "two".to_string()), (1_000_000, 2_500_000, "words".to_string())])]
7410 );
7411 let old = file.replacen("edith 40", "edith 39", 1);
7412 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("unknown keyword"));
7413 for bad in ["cuewords 0 1 0 5\n", "cuewords 9 1 0 5 a\n", "cuewords 0 1 x 5 a\n"] {
7414 let f = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{bad}");
7415 assert!(parse(f.as_bytes(), &dir).is_err(), "{bad:?} is refused");
7416 }
7417 }
7418
7419 /// The whole project loop for word times: a track with uneven word times is written as
7420 /// `cuewords` lines, read back and attached to a freshly loaded project, and the cue then
7421 /// answers with the same uneven times -- until its text is retyped, which drops them.
7422 #[test]
7423 fn a_projects_cue_word_times_survive_the_file_and_die_with_a_text_edit() {
7424 let words = vec![(0, 200_000, "so".to_string()), (200_000, 2_600_000, "extraordinary".to_string())];
7425 let make = |words: Vec<(i64, i64, String)>| {
7426 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7427 track.cues = vec![crate::subtitle::Cue {
7428 start_us: 0,
7429 end_us: 3_000_000,
7430 text: "So extraordinary".into(),
7431 image: None,
7432 words,
7433 karaoke: Vec::new(),
7434 }];
7435 track
7436 };
7437 let mut project = crate::Project::single("/proj/a.mp4", 150);
7438 assert!(project.add_subtitles(&make(words.clone())));
7439 let lines = String::from_utf8(cue_word_lines(project.subtitles())).unwrap();
7440 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7441 let doc = parse(file.as_bytes(), &PathBuf::from("/proj")).expect("the file parses");
7442
7443 let mut loaded = crate::Project::single("/proj/a.mp4", 150);
7444 assert!(loaded.add_subtitles(&make(Vec::new())));
7445 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "the SRT alone has no word times");
7446 let mut loaded = loaded.with_cue_words(&doc.cue_words);
7447 assert_eq!(loaded.subtitles()[0].cues[0].real_words(), Some(&words[..]), "the uneven times are back");
7448 assert!(loaded.set_cue_text(0, 0, "Something else"));
7449 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "retyped words have no times");
7450 }
7451
7452 #[test]
7453 fn the_caption_style_round_trips_and_a_v36_file_loads_as_static() {
7454 use crate::captionanim::CaptionAnim;
7455 let dir = std::env::temp_dir().join(format!("edith-capstyle-{}", std::process::id()));
7456 std::fs::create_dir_all(&dir).unwrap();
7457 let path = dir.join("capstyle.edith");
7458 let save = |cs: &CaptionStyle| {
7459 save_flagged(
7460 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7461 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7462 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], cs, &[], &[],
7463 )
7464 .expect("saves");
7465 };
7466 let style = CaptionStyle {
7467 anim: CaptionAnim::Karaoke,
7468 highlight: [0x12, 0xab, 0xff],
7469 hl_box: true,
7470 uppercase: true,
7471 words_per_line: 3,
7472 };
7473 save(&style);
7474 let text = std::fs::read_to_string(&path).unwrap();
7475 assert!(text.starts_with("edith 40\n"), "{text}");
7476 assert!(text.contains("\ncapstyle karaoke 12abff 1 1 3\n"), "{text}");
7477 assert_eq!(load(&path).expect("v40 loads").caption_style, style);
7478 // The default is no line and an older header: the bytes an older build wrote.
7479 save(&CaptionStyle::default());
7480 let text = std::fs::read_to_string(&path).unwrap();
7481 assert!(!text.contains("capstyle") && !text.starts_with("edith 40"), "{text}");
7482 assert_eq!(load(&path).unwrap().caption_style, CaptionStyle::default());
7483 let old = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v36 file loads");
7484 assert_eq!(old.caption_style, CaptionStyle::default());
7485 let mixed = parse(b"edith 39\nsource 0 a.mp4\ncapstyle pop ffd600 0 0 0\n", &dir)
7486 .unwrap_err()
7487 .to_string();
7488 assert_eq!(mixed, "line 3: unknown keyword \"capstyle\"");
7489 for line in [
7490 "capstyle spin ffd600 0 0 0",
7491 "capstyle pop ffd60 0 0 0",
7492 "capstyle pop ffd600 2 0 0",
7493 "capstyle pop ffd600 0 0 99",
7494 "capstyle pop ffd600 0 0",
7495 ] {
7496 let file = format!("edith 40\nsource 0 a.mp4\n{line}\n");
7497 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7498 }
7499 std::fs::remove_file(&path).ok();
7500 std::fs::remove_dir(&dir).ok();
7501 }
7502
7503 /// Crafted files that declare more than any editor writes get a clear error,
7504 /// never an allocation or a hang.
7505 #[test]
7506 fn crafted_tables_over_the_caps_are_refused() {
7507 let dir = PathBuf::from("/proj");
7508 let head = "edith 40\nsource 0 a.mp4\n";
7509 let bands = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS + 1].join(" ");
7510 let words = "0 1 w ".repeat(MAX_CUE_WORDS + 1);
7511 let order = (0..=MAX_SEQUENCES).map(|i| i.to_string()).collect::<Vec<_>>().join(" ");
7512 for (file, what) in [
7513 (format!("{head}eq {bands}\n"), "equalizer"),
7514 (format!("{head}cuewords 0 0 {}\n", words.trim_end()), "cuewords"),
7515 (format!("edith 45\nsource 0 a.mp4\nseqorder {order}\n"), "seqorder"),
7516 ] {
7517 let err = parse(file.as_bytes(), &dir).expect_err(what).to_string();
7518 assert!(err.contains("at most") || err.contains("more than"), "{what}: {err}");
7519 }
7520 // And a table of exactly the cap still opens.
7521 let ok = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS].join(" ");
7522 assert!(parse(format!("{head}eq {ok}\n").as_bytes(), &dir).is_ok());
7523 // A project whose lists run past the cap is refused as a whole.
7524 let mut many = String::from("edith 40\nsource 0 a.mp4\n");
7525 for i in 0..=MAX_LIST_ENTRIES {
7526 many.push_str(&format!("chapter {i} c\n"));
7527 }
7528 let err = parse(many.as_bytes(), &dir).unwrap_err().to_string();
7529 assert!(err.contains("at most"), "{err}");
7530 }
7531
7532 #[test]
7533 fn the_newest_version_is_the_magic_line_the_writer_emits() {
7534 assert_eq!(MAGIC, format!("edith {NEWEST_VERSION}").as_bytes());
7535 }
7536
7537 #[test]
7538 fn malformed_lines_name_their_line_number() {
7539 let dir = PathBuf::from("/proj");
7540 let cases: [(&[u8], &str); 10] = [
7541 // v3 wants the stream before the path, and a path after it.
7542 (
7543 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
7544 "line 2: \"a.mp4\" is not a number",
7545 ),
7546 (
7547 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
7548 "line 2: source without a path",
7549 ),
7550 (
7551 b"edith 1\nsource a.mp4\nclip 0 5\n",
7552 "line 3: clip wants 3 fields, found 2",
7553 ),
7554 (
7555 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
7556 "line 3: \"five\" is not a number",
7557 ),
7558 (
7559 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
7560 "line 3: clip [5, 5) is empty",
7561 ),
7562 (
7563 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
7564 "line 3: clip [7, 5) is empty",
7565 ),
7566 (
7567 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
7568 "line 3: clip names source 1 of 1",
7569 ),
7570 (
7571 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
7572 "line 4: source after a clip",
7573 ),
7574 (
7575 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
7576 "line 3: unknown keyword \"\"",
7577 ),
7578 (
7579 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
7580 "line 3: playhead belongs once, before the sources",
7581 ),
7582 ];
7583 for (bytes, want) in cases {
7584 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
7585 }
7586 }
7587
7588 /// The emptied timeline writes and reads back: every lane declared, no clip
7589 /// on any of them, and the source that gave the project its frame rate still
7590 /// named. Nothing about the format changes for it -- an empty lane already
7591 /// had a line of its own.
7592 #[test]
7593 fn a_project_without_clips_round_trips() {
7594 let dir = PathBuf::from("/proj");
7595 let source = Source {
7596 path: PathBuf::from("/proj/a.mp4"),
7597 audio_stream: 0, ..Default::default()
7598 };
7599 let bytes = flat(
7600 &dir,
7601 std::slice::from_ref(&source),
7602 &two(Vec::new(), Vec::new()),
7603 0,
7604 );
7605 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
7606 assert_eq!(back.sources, vec![source]);
7607 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
7608 assert_eq!(back.playhead, 0);
7609 // Older dialects, where the two lanes are implied rather than declared.
7610 assert_eq!(
7611 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
7612 two(Vec::new(), Vec::new())
7613 );
7614 assert!(
7615 parse(b"edith 1\n", &dir)
7616 .expect("a project of nothing")
7617 .sources
7618 .is_empty()
7619 );
7620 }
7621
7622 /// Every truncation of a good file either parses or refuses; none panics.
7623 #[test]
7624 fn truncations_never_panic() {
7625 let (dir, sources, lanes) = doc();
7626 let bytes = flat(&dir, &sources, &lanes, 12);
7627 for cut in 0..bytes.len() {
7628 let _ = parse(&bytes[..cut], &dir);
7629 // ...and the same file with a byte lopped off the front, which
7630 // shifts every field into the wrong place.
7631 let _ = parse(&bytes[cut..], &dir);
7632 }
7633 // A % escape at the very end of a line has nothing to consume.
7634 assert_eq!(
7635 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
7636 .unwrap_err()
7637 .to_string(),
7638 "line 2: truncated % escape in the path"
7639 );
7640 }
7641
7642 /// A clip's visualizer field is a whole byte of flags, and a line naming one
7643 /// past it used to be truncated into a look nobody chose (`300` loaded as
7644 /// `44`, with the fast bit and the ink nibble both wrong). It is refused by
7645 /// name now, like the resolution's bound, the sample rate's range, the tone
7646 /// map and the encoder seat beside it.
7647 #[test]
7648 fn a_visualizer_byte_past_a_byte_is_refused_and_the_legal_ones_still_load() {
7649 // The door the parser reads that field through: the low bits are the
7650 // style, bit 3 the fast flag and the high nibble the ink, so every value a
7651 // byte holds is a look and 256 and up is not one.
7652 assert_eq!(flags_byte(b"0", 1).expect("zero is the plain look"), 0);
7653 assert_eq!(flags_byte(b"255", 1).expect("the whole byte is flags"), 255);
7654 let refused = flags_byte(b"300", 9).expect_err("300 is not a byte of flags");
7655 assert_eq!(
7656 refused.to_string(),
7657 "line 9: 300 is not a set of visualizer flags"
7658 );
7659 }
7660
7661 /// ...and the same field through the parser, on a document of the newest
7662 /// dialect: the legal byte is what lands in the clip, the illegal one is the
7663 /// refusal above rather than a truncation.
7664 #[test]
7665 fn a_clip_line_whose_visualizer_is_past_a_byte_loses_the_whole_load() {
7666 let dir = PathBuf::from("/proj");
7667 let line = |flags: &str| {
7668 format!(
7669 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7670 video 1 0 0 30 0 - - - fit 1000 0 0 0 - {flags} 0\n"
7671 )
7672 };
7673 let doc = parse(line("12").as_bytes(), &dir).expect("12 is a look");
7674 // The keyword is the saver's own for this dialect, so a mismatch here would
7675 // be this test's line and not the field it is about.
7676 assert_eq!(doc.lanes[0].1[0].visualizer, 12);
7677 let refused = parse(line("300").as_bytes(), &dir).expect_err("300 is not a look");
7678 assert!(
7679 refused
7680 .to_string()
7681 .contains("is not a set of visualizer flags"),
7682 "{refused}"
7683 );
7684 }
7685}
7686
7687#[cfg(test)]
7688mod title_tests {
7689 use super::*;
7690
7691 fn sample() -> Vec<Title> {
7692 vec![
7693 Title {
7694 start: 0,
7695 frames: 90,
7696 text: "Episode 17\n100% \\ done".into(),
7697 style: TextStyle {
7698 size: 80,
7699 outline: Outline::Thick,
7700 boxed: false,
7701 place: Place::Centre,
7702 ..TextStyle::default()
7703 },
7704 fade_in: 10,
7705 fade_out: 5,
7706 in_anim: TitleAnim::None,
7707 out_anim: TitleAnim::None,
7708 anim_frames: 0,
7709 },
7710 Title {
7711 start: 60,
7712 frames: 120,
7713 text: "Jane Doe \u{2014} Engineer".into(),
7714 style: TextStyle::default(),
7715 fade_in: 0,
7716 fade_out: 0,
7717 in_anim: Default::default(),
7718 out_anim: Default::default(),
7719 anim_frames: 0,
7720 },
7721 ]
7722 }
7723
7724 fn styled() -> Vec<Title> {
7725 let mut t = sample();
7726 t[1].style = TextStyle {
7727 hplace: HPlace::Left,
7728 align: Align::Right,
7729 weight: Weight::Bold,
7730 ink: [255, 204, 0],
7731 box_color: [10, 20, 30, 200],
7732 ..TextStyle::default()
7733 };
7734 t
7735 }
7736
7737 #[test]
7738 fn a_title_look_round_trips_and_only_a_styled_one_writes_a_line() {
7739 // Default looks write no `titlestyle` line at all.
7740 assert!(!String::from_utf8(title_lines(&sample())).unwrap().contains("titlestyle"));
7741 let titles = styled();
7742 let body = title_lines(&titles);
7743 let text = String::from_utf8(body.clone()).unwrap();
7744 assert_eq!(text.matches("titlestyle").count(), 1);
7745 assert!(text.contains("titlestyle 1 left right bold ffcc00 0a141ec8\n"), "{text}");
7746 let mut bytes = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7747 bytes.extend_from_slice(&body);
7748 let doc = parse(&bytes, Path::new(".")).expect("a v49 file with a title look parses");
7749 assert_eq!(doc.titles, titles);
7750 let mut again = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7751 again.extend_from_slice(&title_lines(&doc.titles));
7752 assert_eq!(again, bytes);
7753 }
7754
7755 #[test]
7756 fn a_title_look_is_a_v49_line_and_a_bad_one_is_refused_by_name() {
7757 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");
7758 let ok = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(49));
7759 assert!(parse(ok.as_bytes(), Path::new(".")).is_ok());
7760 let old = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(48));
7761 assert!(parse(old.as_bytes(), Path::new(".")).is_err(), "titlestyle is not a v48 line");
7762 // A v48 file with plain titles still loads, with the default look.
7763 let doc = parse(head(48).as_bytes(), Path::new(".")).unwrap();
7764 assert_eq!(doc.titles[0].style, TextStyle { boxed: true, ..TextStyle::default() });
7765 for line in [
7766 "titlestyle 0 middle left bold ffffff 000000ff",
7767 "titlestyle 0 left up bold ffffff 000000ff",
7768 "titlestyle 0 left left heavy ffffff 000000ff",
7769 "titlestyle 0 left left bold fff 000000ff",
7770 "titlestyle 0 left left bold ffffff 000000",
7771 "titlestyle 5 left left bold ffffff 000000ff",
7772 ] {
7773 let text = format!("{}{line}\n", head(49));
7774 assert!(parse(text.as_bytes(), Path::new(".")).is_err(), "{line}");
7775 }
7776 }
7777
7778 #[test]
7779 fn title_lines_round_trip_through_the_loader_with_escapes() {
7780 let titles = sample();
7781 let mut bytes = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7782 bytes.extend_from_slice(&title_lines(&titles));
7783 let doc = parse(&bytes, Path::new(".")).expect("a v26 file with titles parses");
7784 assert_eq!(doc.titles, titles);
7785 // Written and read again, the same bytes come back.
7786 let mut again = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7787 again.extend_from_slice(&title_lines(&doc.titles));
7788 assert_eq!(again, bytes);
7789 }
7790
7791 #[test]
7792 fn a_v25_file_has_no_titles_and_loads() {
7793 let v25 = b"edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7794 let doc = parse(v25, Path::new(".")).expect("v25 still loads");
7795 assert!(doc.titles.is_empty());
7796 let as_v25 = b"edith 25\nplayhead 0\nsource 0 a.mp4\ntitle 0 10 0 0 50 none 0 bottom hi\n";
7797 assert!(
7798 parse(as_v25, Path::new(".")).is_err(),
7799 "title is not a v25 line"
7800 );
7801 }
7802
7803 #[test]
7804 fn a_title_line_outside_its_range_is_refused_by_name() {
7805 let head = "edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7806 for line in [
7807 "title 0 0 0 0 50 none 0 bottom hi",
7808 "title 0 10 0 0 9 none 0 bottom hi",
7809 "title 0 10 0 0 50 wavy 0 bottom hi",
7810 "title 0 10 0 0 50 none 2 bottom hi",
7811 "title 0 10 0 0 50 none 0 middle hi",
7812 "title 0 10 11 0 50 none 0 bottom hi",
7813 "title 0 10 0 0 50 none 0 bottom",
7814 ] {
7815 let body = format!("{head}{line}\n");
7816 assert!(
7817 parse(body.as_bytes(), Path::new(".")).is_err(),
7818 "{line} was accepted"
7819 );
7820 }
7821 }
7822}
7823
7824#[cfg(test)]
7825mod clip_gain_tests {
7826 use super::*;
7827
7828 /// A v26 file loads, every clip at unity; a `clipgain` line in one is a
7829 /// line the dialect does not have, so it is refused by number.
7830 #[test]
7831 fn a_v26_file_loads_at_unity_and_refuses_a_clipgain_line() {
7832 let dir = PathBuf::from("/proj");
7833 let old = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7834 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7835 let doc = parse(old, &dir).expect("a v26 file still loads");
7836 assert_eq!(doc.lanes[0].1[0].gain_db, 0.0);
7837 let with = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7838 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\nclipgain audio 1 0 -6\n";
7839 let err = parse(with, &dir).unwrap_err().to_string();
7840 assert!(err.contains("line 6"), "{err}");
7841 }
7842
7843 /// The writer's own bytes: a gained clip gets a `clipgain` line after its
7844 /// lanes, unity clips get none, and the value comes back exactly.
7845 #[test]
7846 fn clip_gain_lines_are_written_only_off_unity_and_round_trip() {
7847 let dir = PathBuf::from("/proj");
7848 let clip = |gain_db: f32| Clip {
7849 speed_keys: Vec::new(),
7850 reversed: false,
7851 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
7852 angle: Default::default(),
7853 gain_keys: Vec::new(),
7854 pan: 0,
7855 transform_keys: Vec::new(),
7856 opacity_keys: Vec::new(),
7857 color_keys: Vec::new(),
7858 effects: Vec::new(),
7859 start: 0,
7860 in_frame: 0,
7861 out_frame: 30,
7862 source: 0,
7863 link: None,
7864 eq: None,
7865 color: None,
7866 transform: None,
7867 fit: FitPolicy::default(),
7868 speed: Speed::NORMAL,
7869 fade_in: 0,
7870 fade_out: 0,
7871 transition_out: 0,
7872 transition_kind: Default::default(),
7873 visualizer: 0,
7874 viz_paint: 0,
7875 gain_db,
7876 pitch: 0,
7877 };
7878 let lanes = vec![
7879 (LaneKind::Video, vec![clip(0.0)]),
7880 (LaneKind::Audio, vec![clip(-6.5), clip(0.0)]),
7881 ];
7882 let bytes = clip_gain_lines(&lanes);
7883 assert_eq!(bytes, b"clipgain audio 1 0 -6.5\n".to_vec());
7884 let mut text = b"edith 27\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7885 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7886 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7887 audio 1 30 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"
7888 .to_vec();
7889 text.extend_from_slice(&bytes);
7890 let doc = parse(&text, &dir).expect("a v27 file with a clip gain parses");
7891 assert_eq!(doc.lanes[1].1[0].gain_db, -6.5);
7892 assert_eq!(doc.lanes[1].1[1].gain_db, 0.0);
7893 }
7894}
7895
7896#[cfg(test)]
7897mod gain_key_tests {
7898 use super::*;
7899
7900 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7901 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7902
7903 /// A v27 file loads with every clip's envelope empty, and a `gainkeys` line
7904 /// in one is a line the dialect does not have, so it is refused by number.
7905 #[test]
7906 fn a_v27_file_loads_flat_and_refuses_a_gainkeys_line() {
7907 let dir = PathBuf::from("/proj");
7908 let old = format!("edith 27\n{HEAD}");
7909 let doc = parse(old.as_bytes(), &dir).expect("a v27 file still loads");
7910 assert!(doc.lanes[0].1[0].gain_keys.is_empty());
7911 let with = format!("edith 27\n{HEAD}gainkeys audio 1 0 0:-6\n");
7912 let err = parse(with.as_bytes(), &dir).unwrap_err().to_string();
7913 assert!(err.contains("line 6"), "{err}");
7914 }
7915
7916 /// The writer's own bytes: a clip with points gets one `gainkeys` line after
7917 /// its lanes, a clip without gets none, and the points come back exactly.
7918 #[test]
7919 fn gain_key_lines_are_written_only_with_points_and_round_trip() {
7920 let dir = PathBuf::from("/proj");
7921 let mut text = format!("edith 28\n{HEAD}").into_bytes();
7922 text.extend_from_slice(b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n");
7923 let doc = parse(&text, &dir).expect("a v28 file with an envelope parses");
7924 let keys = &doc.lanes[0].1[0].gain_keys;
7925 assert_eq!(
7926 keys,
7927 &[
7928 GainKey::new(0, 0.0),
7929 GainKey::new(30, -20.0),
7930 GainKey::new(45, -6.5),
7931 ]
7932 );
7933 let lanes: Vec<(LaneKind, Vec<Clip>)> =
7934 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
7935 let bytes = gain_key_lines(&lanes);
7936 assert_eq!(bytes, b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n".to_vec());
7937 let again = parse(
7938 &[format!("edith 28\n{HEAD}").as_bytes(), &bytes].concat(),
7939 &dir,
7940 )
7941 .expect("the writer's own line parses");
7942 assert_eq!(again.lanes[0].1[0].gain_keys, *keys);
7943 }
7944
7945 /// A ramp can make a clip shorter than its constant footprint, which the lines before
7946 /// its `speedkeys` still show: the next clip, placed against the ramp's length, loads;
7947 /// one that really overlaps the ramped footprint is refused.
7948 #[test]
7949 fn a_clip_placed_against_a_shorter_ramp_loads_and_a_real_overlap_does_not() {
7950 let dir = PathBuf::from("/proj");
7951 let next = |start: u32| {
7952 format!("audio 1 {start} 0 30 0 - - - fit 1000 0 0 0 - 0 0\n")
7953 };
7954 let ok = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(22));
7955 let doc = parse(ok.as_bytes(), &dir).expect("the ramp is 22 frames, the next clip starts at 22");
7956 assert_eq!(doc.lanes[0].1.len(), 2);
7957 let bad = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(21));
7958 assert!(parse(bad.as_bytes(), &dir).is_err(), "21 is inside the ramped clip");
7959 }
7960
7961 /// A `speedkeys` line is a v35 clip's ramp: it reads back as the keys, its footprint
7962 /// is the ramp's, and the writer's own line reads back to the same keys. A clip with no
7963 /// keys writes no line.
7964 #[test]
7965 fn speedkeys_lines_round_trip_and_a_clip_without_a_ramp_writes_none() {
7966 let dir = PathBuf::from("/proj");
7967 let text = format!("edith 35\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
7968 let doc = parse(text.as_bytes(), &dir).expect("a v35 file with a ramp parses");
7969 let clip = &doc.lanes[0].1[0];
7970 assert_eq!(
7971 clip.speed_keys,
7972 vec![
7973 SpeedKey { at: 0, speed: Speed::NORMAL },
7974 SpeedKey { at: 30, speed: Speed::from_permille(2000) },
7975 ]
7976 );
7977 // 30 source frames at a rate that climbs from 1x to 2x: 22 timeline frames.
7978 assert_eq!(clip.frames(), 22);
7979 let lanes: Vec<(LaneKind, Vec<Clip>)> =
7980 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
7981 assert_eq!(speed_key_lines(&lanes), b"speedkeys audio 1 0 0:1000 30:2000\n".to_vec());
7982 let mut plain = lanes.clone();
7983 plain[0].1[0].speed_keys.clear();
7984 assert!(speed_key_lines(&plain).is_empty(), "no ramp, no line");
7985 let again = parse(
7986 &[format!("edith 35\n{HEAD}").as_bytes(), &speed_key_lines(&lanes)].concat(),
7987 &dir,
7988 )
7989 .expect("the writer's own line parses");
7990 assert_eq!(again.lanes[0].1[0].speed_keys, clip.speed_keys);
7991 }
7992
7993 /// A `transition` line (v37) names how a clip's dissolve is drawn: every kind's name
7994 /// reads back as the kind, the writer's own lines parse, a clip with the default writes
7995 /// none, and an older file (no line) means a dissolve.
7996 #[test]
7997 fn transition_lines_round_trip_every_kind_and_old_files_dissolve() {
7998 let dir = PathBuf::from("/proj");
7999 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8000 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8001 let old = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("v35 parses");
8002 assert_eq!(old.lanes[0].1[0].transition_kind, TransitionKind::Dissolve);
8003 let mut kinds = Vec::new();
8004 for shape in TransitionKind::SHAPES {
8005 match shape.dir() {
8006 Some(_) => kinds.extend(crate::transitions::Dir::ALL.map(|d| shape.with_dir(d))),
8007 None => kinds.push(shape),
8008 }
8009 }
8010 for kind in kinds {
8011 let mut lanes: Vec<(LaneKind, Vec<Clip>)> = old.lanes.clone();
8012 lanes[0].1[0].transition_kind = kind;
8013 let lines = transition_lines(&lanes);
8014 if kind == TransitionKind::Dissolve {
8015 assert!(lines.is_empty(), "the default writes no line");
8016 }
8017 let text = [format!("edith 37\n{head}").as_bytes(), &lines].concat();
8018 let back = parse(&text, &dir).unwrap_or_else(|e| panic!("{}: {e}", kind.name()));
8019 assert_eq!(back.lanes[0].1[0].transition_kind, kind);
8020 }
8021 for bad in ["transition video 1 0 swirl\n", "transition video 1 4 zoom\n", "transition video 2 0 zoom\n"] {
8022 let err = parse(format!("edith 37\n{head}{bad}").as_bytes(), &dir).unwrap_err().to_string();
8023 assert!(err.contains("line 6"), "{bad}: {err}");
8024 }
8025 for old in [35, 36] {
8026 let file = format!("edith {old}\n{head}transition video 1 0 zoom\n");
8027 assert!(parse(file.as_bytes(), &dir).is_err(), "a v{old} reader has no such line");
8028 }
8029 }
8030
8031 /// The writer emits the highest version a project needs: markers alone are v36, a
8032 /// transition kind makes it v37 (markers and all, which round-trip together), only
8033 /// dissolves and no markers fall back to the older header, and a v36 file still loads.
8034 #[test]
8035 fn the_header_is_the_highest_version_needed_and_v36_and_v37_round_trip() {
8036 use crate::project::{Marker, MarkerColor};
8037 let dir = std::env::temp_dir().join(format!("edith-v37-{}", std::process::id()));
8038 std::fs::create_dir_all(&dir).unwrap();
8039 let path = dir.join("v37.edith");
8040 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";
8041 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8042 let sources = doc.sources;
8043 let mut lanes = doc.lanes;
8044 let markers = vec![Marker { frame: 12, length: 0, name: "Beat".into(), note: "a note".into(), color: MarkerColor::Blue }];
8045 let save_styled = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker], cs: &CaptionStyle| {
8046 save_flagged(
8047 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8048 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8049 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, cs, &[], &[],
8050 )
8051 .expect("saves");
8052 std::fs::read_to_string(&path).unwrap()
8053 };
8054 let save = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker]| {
8055 save_styled(lanes, markers, &CaptionStyle::default())
8056 };
8057 assert!(save(&lanes, &markers).starts_with("edith 36\n"), "markers alone are v36");
8058 lanes[0].1[0].transition_kind = TransitionKind::Zoom;
8059 let text = save(&lanes, &markers);
8060 assert!(text.starts_with("edith 37\n"), "a transition makes it v37: {text}");
8061 let back = load(&path).expect("v37 loads");
8062 assert_eq!(back.markers, markers);
8063 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8064 let text = save(&lanes, &[]);
8065 assert!(text.starts_with("edith 37\n") && text.contains("transition "), "{text}");
8066 lanes[0].1[0].reversed = true;
8067 let text = save(&lanes, &markers);
8068 assert!(text.starts_with("edith 38\n") && text.contains("reverse video 1 0"), "a reversed clip makes it v38: {text}");
8069 let back = load(&path).expect("v38 loads");
8070 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8071 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8072 lanes[0].1[0].opacity_keys = vec![OpacityKey { at: 0, opacity: 0.5, ease: KeyEase::Hold }];
8073 let text = save(&lanes, &markers);
8074 assert!(text.starts_with("edith 39\n") && text.contains("okeys video 1 0"), "an animation makes it v39: {text}");
8075 let back = load(&path).expect("v39 loads");
8076 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8077 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8078 // ...and a project caption style on top of all of it makes it v40.
8079 let style = CaptionStyle { anim: crate::captionanim::CaptionAnim::Pop, ..CaptionStyle::default() };
8080 let text = save_styled(&lanes, &markers, &style);
8081 assert!(text.starts_with("edith 40\n") && text.contains("\ncapstyle pop "), "a caption style makes it v40: {text}");
8082 let back = load(&path).expect("v40 loads");
8083 assert!(back.lanes[0].1[0].reversed && back.markers == markers && back.caption_style == style);
8084 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8085 lanes[0].1[0].opacity_keys.clear();
8086 lanes[0].1[0].reversed = false;
8087 lanes[0].1[0].transition_kind = TransitionKind::Dissolve;
8088 let text = save(&lanes, &[]);
8089 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}");
8090 let v36 = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).expect("a v36 file loads");
8091 assert_eq!(v36.markers.len(), 1);
8092 std::fs::remove_dir_all(&dir).ok();
8093 }
8094
8095 /// `lanename` and `deint` lines are v46: both round-trip, a project with neither keeps
8096 /// its older header and exact bytes, an older header refuses them and bad ones are
8097 /// refused by line.
8098 #[test]
8099 fn lane_names_and_deinterlace_round_trip_in_v46_and_without_them_the_bytes_are_unchanged() {
8100 let dir = std::env::temp_dir().join(format!("edith-v46-{}", std::process::id()));
8101 std::fs::create_dir_all(&dir).unwrap();
8102 let path = dir.join("v46.edith");
8103 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";
8104 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8105 let sources = doc.sources;
8106 let mut lanes = doc.lanes;
8107 let n = lanes.len();
8108 let save = |lanes: &[(LaneKind, Vec<Clip>)], names: &[String]| {
8109 save_flagged(
8110 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8111 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8112 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], names,
8113 )
8114 .expect("saves");
8115 std::fs::read_to_string(&path).unwrap()
8116 };
8117 let blank = vec![String::new(); n];
8118 let plain = save(&lanes, &blank);
8119 assert!(!plain.contains("lanename") && !plain.contains("deint") && !plain.starts_with("edith 46"), "{plain}");
8120 let mut names = blank.clone();
8121 names[0] = "Main \\ cam".into();
8122 let text = save(&lanes, &names);
8123 assert!(text.starts_with("edith 46\n") && text.contains("\nlanename video 1 Main \\\\ cam\n"), "{text}");
8124 assert_eq!(load(&path).expect("v46 loads").names[0], "Main \\ cam");
8125 assert_eq!(save(&lanes, &blank), plain, "no names is the bytes it was");
8126 lanes[0].1[0].deinterlace = Deinterlace::Field;
8127 let text = save(&lanes, &blank);
8128 assert!(text.starts_with("edith 46\n") && text.contains("\ndeint video 1 0 field\n"), "{text}");
8129 assert_eq!(load(&path).unwrap().lanes[0].1[0].deinterlace, Deinterlace::Field);
8130 for older in ["edith 45", "edith 44"] {
8131 for line in ["lanename video 1 X\n", "deint video 1 0 off\n"] {
8132 let old = format!("{older}\n{head}{line}");
8133 assert!(parse(old.as_bytes(), &dir).is_err(), "{older} refuses {line:?}");
8134 }
8135 }
8136 for (line, why) in [
8137 ("lanename video 1 \n", "1 to"),
8138 ("lanename video 3 X\n", "not there"),
8139 ("lanename tape 1 X\n", "not a lane kind"),
8140 ("deint video 1 0 weave\n", "frame, field or off"),
8141 ("deint video 1 4 off\n", "does not have"),
8142 ] {
8143 let err = parse(format!("edith 46\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8144 assert!(err.contains(why) && err.contains("line"), "{line:?}: {err}");
8145 }
8146 let long = "x".repeat(crate::project::MAX_LANE_NAME_CHARS + 1);
8147 assert!(parse(format!("edith 46\n{head}lanename video 1 {long}\n").as_bytes(), &dir).is_err());
8148 std::fs::remove_file(&path).ok();
8149 std::fs::remove_dir(&dir).ok();
8150 }
8151
8152 /// A `stab` line is a v44 clip's stabilisation: it round-trips through a save, a
8153 /// project with no stabilised clip keeps its older header and its exact bytes, an
8154 /// older file refuses the line and a bad one is refused by its line number.
8155 #[test]
8156 fn stab_lines_round_trip_in_v44_and_without_one_the_bytes_are_unchanged() {
8157 let dir = std::env::temp_dir().join(format!("edith-stab-{}", std::process::id()));
8158 std::fs::create_dir_all(&dir).unwrap();
8159 let path = dir.join("v44.edith");
8160 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";
8161 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8162 let sources = doc.sources;
8163 let mut lanes = doc.lanes;
8164 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
8165 save_flagged(
8166 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8167 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8168 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
8169 )
8170 .expect("saves");
8171 std::fs::read_to_string(&path).unwrap()
8172 };
8173 let plain = save(&lanes);
8174 assert!(!plain.contains("stab") && !plain.starts_with("edith 44"), "{plain}");
8175 let st = crate::stabilise::Stabilise::new(0.75, crate::stabilise::Crop::Full);
8176 lanes[0].1[0].stabilise = Some(st);
8177 let text = save(&lanes);
8178 assert!(text.starts_with("edith 44\n") && text.contains("\nstab video 1 0 0.75 full\n"), "{text}");
8179 assert_eq!(load(&path).expect("v44 loads").lanes[0].1[0].stabilise, Some(st));
8180 lanes[0].1[0].stabilise = None;
8181 assert_eq!(save(&lanes), plain, "off again is the bytes it was");
8182 for older in ["edith 43", "edith 42", "edith 41"] {
8183 let old = format!("{older}\n{head}stab video 1 0 0.5 zoom\n");
8184 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("stab"), "{older} has no stab line");
8185 }
8186 for (line, why) in [
8187 ("stab video 1 0 0.5\n", "wants a video clip"),
8188 ("stab video 1 0 1.5 zoom\n", "from 0 to 1"),
8189 ("stab video 1 0 0.5 tilt\n", "zoom or full"),
8190 ("stab video 1 4 0.5 zoom\n", "which the lane does not have"),
8191 ] {
8192 let err = parse(format!("edith 44\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8193 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8194 }
8195 std::fs::remove_dir_all(&dir).ok();
8196 }
8197
8198 /// A `reverse` line is a v38 clip's direction: it reads back as `reversed`, the
8199 /// writer's own line reads back the same, a project with none is written under
8200 /// the v35 header it always was, and an older file or a bad line is refused by
8201 /// its line number.
8202 #[test]
8203 fn reverse_lines_round_trip_and_older_files_and_bad_lines_are_refused() {
8204 let dir = PathBuf::from("/proj");
8205 let text = format!("edith 38\n{HEAD}reverse audio 1 0\n");
8206 let doc = parse(text.as_bytes(), &dir).expect("a v38 file with a reversed clip parses");
8207 assert!(doc.lanes[0].1[0].reversed);
8208 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8209 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8210 assert_eq!(reverse_lines(&lanes), b"reverse audio 1 0\n".to_vec());
8211 let mut plain = lanes.clone();
8212 plain[0].1[0].reversed = false;
8213 assert!(reverse_lines(&plain).is_empty(), "forward, no line");
8214 let again = parse(
8215 &[format!("edith 38\n{HEAD}").as_bytes(), &reverse_lines(&lanes)].concat(),
8216 &dir,
8217 )
8218 .expect("the writer's own line parses");
8219 assert!(again.lanes[0].1[0].reversed);
8220 // A v37 file (or older) has no such line.
8221 for old in [35, 37] {
8222 let file = format!("edith {old}\n{HEAD}reverse audio 1 0\n");
8223 let err = parse(file.as_bytes(), &dir).unwrap_err().to_string();
8224 assert!(err.contains("reverse"), "v{old}: {err}");
8225 }
8226 let head = format!("edith 38\n{HEAD}");
8227 for (line, why) in [
8228 ("reverse audio 1\n", "wants a lane and a clip"),
8229 ("reverse subtitle 1 0\n", "not a lane kind"),
8230 ("reverse audio 9 0\n", "a lane that is not there"),
8231 ("reverse audio 1 5\n", "which the lane does not have"),
8232 ] {
8233 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8234 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8235 }
8236 }
8237
8238 /// A v34 file has no `speedkeys` line, and a bad ramp is refused by its line: a speed
8239 /// out of range, keys out of frame order, a key without a speed, or more than the cap.
8240 #[test]
8241 fn a_v34_file_refuses_a_speedkeys_line_and_a_bad_ramp_is_refused() {
8242 let dir = PathBuf::from("/proj");
8243 let v34 = format!("edith 34\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8244 let err = parse(v34.as_bytes(), &dir).unwrap_err().to_string();
8245 assert!(err.contains("speedkeys"), "{err}");
8246 let head = format!("edith 35\n{HEAD}");
8247 for line in [
8248 "speedkeys audio 1 0 0:9000\n",
8249 "speedkeys audio 1 0 30:1000 0:1000\n",
8250 "speedkeys audio 1 0 0\n",
8251 "speedkeys audio 1 0 0:1000 1:1000 2:1000 3:1000 4:1000 5:1000 6:1000 7:1000 8:1000\n",
8252 ] {
8253 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8254 assert!(err.contains("line 6"), "{line}: {err}");
8255 }
8256 }
8257
8258 /// A point out of source order, one out of range, or a clip with more than
8259 /// the cap are all refused by line; the dialect keeps the invariants.
8260 #[test]
8261 fn a_bad_gainkeys_line_is_refused() {
8262 let dir = PathBuf::from("/proj");
8263 let head = format!("edith 28\n{HEAD}");
8264 for line in [
8265 "gainkeys audio 1 0 30:-6 0:0\n",
8266 "gainkeys audio 1 0 0:-90\n",
8267 "gainkeys audio 1 0 0\n",
8268 "gainkeys audio 1 0 0 0x\n",
8269 ] {
8270 let text = format!("{head}{line}");
8271 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8272 assert!(err.contains("line 6"), "{line}: {err}");
8273 }
8274 let many: String = (0..=MAX_GAIN_KEYS as u32)
8275 .map(|i| format!(" {i}:0"))
8276 .collect();
8277 let text = format!("{head}gainkeys audio 1 0 0{many}\n");
8278 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8279 assert!(err.contains("more than"), "{err}");
8280 }
8281}
8282
8283#[cfg(test)]
8284mod animation_key_tests {
8285 use super::*;
8286
8287 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8288 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8289 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8290
8291 /// A v35 file written before the easings existed still loads, every key linear
8292 /// (or the `ease` it said), and resaving it does not change a key.
8293 #[test]
8294 fn a_v35_file_upgrades_with_its_keys_linear_and_resaves_as_v32_bytes() {
8295 let dir = PathBuf::from("/proj");
8296 let text = format!(
8297 "edith 35\n{HEAD}gainkeys audio 1 0 0:0 20:-6.5\n\
8298 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"
8299 );
8300 let doc = parse(text.as_bytes(), &dir).expect("a v35 file loads");
8301 let clips = &doc.lanes[1].1;
8302 assert_eq!(clips[0].gain_keys, [GainKey::new(0, 0.0), GainKey::new(20, -6.5)]);
8303 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Ease);
8304 assert!(doc.lanes[0].1[0].opacity_keys.is_empty() && doc.lanes[0].1[0].color_keys.is_empty());
8305 // The writers' lines for those clips are the bytes the file had.
8306 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0 20:-6.5\n".to_vec());
8307 assert_eq!(
8308 tkey_lines(&doc.lanes),
8309 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()
8310 );
8311 assert!(doc.lanes.iter().all(|(_, clips)| !clips.iter().any(needs_v39)), "still not a v39 project");
8312 assert!(opacity_key_lines(&doc.lanes).is_empty() && color_key_lines(&doc.lanes).is_empty());
8313 }
8314
8315 /// The v39 lines read back, in range and in order, and an older dialect has
8316 /// no such lines (nor the new easings) and says so by line number.
8317 #[test]
8318 fn v39_reads_okeys_ckeys_and_eased_points_and_older_dialects_refuse_them() {
8319 let dir = PathBuf::from("/proj");
8320 let new = format!(
8321 "edith 39\n{HEAD}okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n\
8322 ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n\
8323 gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n\
8324 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"
8325 );
8326 let doc = parse(new.as_bytes(), &dir).expect("a v39 file loads");
8327 let v = &doc.lanes[0].1[0];
8328 assert_eq!(v.opacity_keys.len(), 3);
8329 assert_eq!(v.opacity_keys[0].ease, KeyEase::EaseIn);
8330 assert_eq!(v.opacity_keys[1], OpacityKey { at: 10, opacity: 0.5, ease: KeyEase::Hold });
8331 assert_eq!(v.color_keys[0].ease, KeyEase::EaseOut);
8332 assert_eq!(v.color_keys[1].params.contrast, 2.0);
8333 assert_eq!(v.transform_keys[1].ease, KeyEase::Hold);
8334 let g = &doc.lanes[1].1[0].gain_keys;
8335 assert_eq!((g[0].ease, g[1].ease, g[2].ease), (KeyEase::EaseOut, KeyEase::Hold, KeyEase::Linear));
8336 // ...and writing them gives the same lines back.
8337 assert_eq!(
8338 opacity_key_lines(&doc.lanes),
8339 b"okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n".to_vec()
8340 );
8341 assert_eq!(
8342 color_key_lines(&doc.lanes),
8343 b"ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n".to_vec()
8344 );
8345 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n".to_vec());
8346
8347 // A v35 reader has none of it.
8348 let old = format!("edith 35\n{HEAD}okeys video 1 0 0:lin:0\n");
8349 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("line 7"));
8350 // ...and so has a v38 one.
8351 let old = format!("edith 38\n{HEAD}okeys video 1 0 0:lin:0\n");
8352 assert!(parse(old.as_bytes(), &dir).is_err(), "a v38 reader has no okeys line");
8353 let old = format!("edith 35\n{HEAD}tkeys video 1 0 0:hold:0,0,1,0,0,0,0,0,1\n");
8354 assert!(parse(old.as_bytes(), &dir).is_err(), "a hold ease is not a v35 word");
8355 }
8356
8357 #[test]
8358 fn bad_okeys_and_ckeys_lines_are_refused() {
8359 let dir = PathBuf::from("/proj");
8360 for bad in [
8361 "okeys video 1 0 0:lin:1.5", // opacity out of range
8362 "okeys video 1 0 5:lin:0 5:lin:1", // two at one frame
8363 "okeys video 1 0 9:lin:0 5:lin:1", // not in source order
8364 "okeys video 1 0 0:wobble:1", // unknown ease
8365 "okeys audio 1 0 0:lin:1", // not a video lane
8366 "okeys video 1 3 0:lin:1", // no such clip
8367 "ckeys video 1 0 0:lin:2,1,1,0", // brightness out of range
8368 "ckeys video 1 0 0:lin:0,1,1", // three values
8369 "ckeys video 1 0 0:lin:0,3,1,0", // contrast out of range
8370 ] {
8371 let text = format!("edith 39\n{HEAD}{bad}\n");
8372 assert!(parse(text.as_bytes(), &dir).is_err(), "{bad}");
8373 }
8374 }
8375}