forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

edith.rs8554 lines, 384.9 KiBHistoryRawDownload
1//! The project file: a line of text per thing, and nothing else.
2//!
3//! ```text
4//! edith 30
5//! playhead 90
6//! resolution 1920 1080
7//! fps 30.0
8//! tonemap vivid
9//! proxy on
10//! autoproxy off
11//! encoder hardware
12//! limiter -1.0 on
13//! source 0 test_av.mp4
14//! source 1 /elsewhere/test_av2.mp4
15//! subtitle - subs.srt
16//! subtitle 3 test_av.mp4
17//! cue 0 3 Retyped\nby hand
18//! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
19//! color 0.1:1.2:0.9:-0.3
20//! transform 0.1:-0.1:1.5:90.0:0.0:0.0:0.0:0.0
21//! video 1 0 0 120 0 0 0 0 fit 1000 0 0 0 -
22//! audio 1 0 0 120 0 0 0 - fit 1000 30 30 0 -
23//! video 2 120 0 120 1 - - - fill 2000 0 0 0 0
24//! audio 2
25//! sub 1 0 60 0 500000 1500000
26//! sub 2
27//! gain audio 1 -3.0
28//! flags audio 1 muted
29//! ```
30//!
31//! The `fps` line is the rate the timeline was cut at -- the scaffolding
32//! source's own unless a rate was picked
33//! ([`crate::PlaybackSession::set_frame_rate`]), and the *only* thing that says
34//! so once one was, since every clip number in the file is counted in it.
35//! Printed so it reads back bit-exactly. A file without one (every dialect
36//! before v9) means 0"whatever the scaffolding source runs at", which is what
37//! such a project always was and is an answer only a project holding a video has
38//! ([`crate::PlaybackSession::open_project`]).
39//!
40//! A `subtitle` line is `subtitle <track> <path>`: which track of that file the
41//! cues are in -- a Matroska track number, or `-` when the path *is* a subtitle
42//! file ([`crate::subtitle`]) -- and then the path, last and escaped for the
43//! reason a source's is. Only the reference is written: the cues themselves are
44//! read back out of the file on the way in, exactly as a clip's pictures are, so
45//! a project file stays an edit list. A subtitle file that has gone missing
46//! since the save comes back listed and refused by name rather than dropped,
47//! which is what keeps a re-save from losing it.
48//!
49//! A `sublang` line is `sublang <track> <code>`: the language of a subtitle
50//! track, the track by its position in the `subtitle` lines and the code as the
51//! rest of the line (escaped as a `cue`'s text is). Written after the `subtitle`
52//! lines, one for each track that has a language: an import names a standalone
53//! file's from its file name or the person's `lang`, and a retype replaces an
54//! embedded track's container language. **Version 33** is the first dialect
55//! with one; a project with none is written exactly as it always was.
56//!
57//! A `chapter` line is `chapter <frame> <name>`: a chapter marker at a timeline
58//! frame, the name as the rest of the line, escaped as a `cue` line's is. Written
59//! after the `title` lines in frame order, one per frame. **Version 34** is the
60//! first dialect with one; a project with none is written exactly as a v33 one.
61//!
62//! A `speedkeys` line is `speedkeys <kind> <ord> <index> <at>:<permille> ...`: a
63//! clip's speed ramp ([`crate::project::Clip::speed_keys`]), the keys in frame
64//! order, each speed in thousandths like the clip's own `speed` field. Written after
65//! the lanes it names, only for a clip with keys. **Version 35** is the first
66//! dialect with one; a project with no ramp is written exactly as a v34 one.
67//!
68//! A `marker` line is `marker <frame> <length> <color> <name>`: a comment marker, a
69//! point when the length in frames is 0 and a range otherwise, the colour one of
70//! red, orange, yellow, green, blue or purple, the name the rest of the line (escaped
71//! as a `cue` line's is). Written after the `chapter` lines in frame order; several may
72//! share a frame. A `marknote <n> <text>` line gives the note of the n-th `marker` line
73//! (the first is 0), only for a marker that has one. **Version 36** is the first
74//! dialect with either; a project with no marker is written exactly as a v35 one.
75//!
76//! A `transition` line is `transition <kind> <ord> <index> <name>`: how a clip's
77//! `transition_out` is drawn ([`crate::transitions::TransitionKind`]), by its
78//! name -- `dip-black`, `wipe-left`, `zoom` and so on. Written after the lanes it
79//! names, only for a clip whose kind is not the dissolve. **Version 37** is the
80//! first dialect with one; a project with only dissolves is written exactly as
81//! before, and a file without the line means dissolves.
82//!
83//! A `reverse` line is `reverse <kind> <ord> <index>`: the clip plays its source window
84//! backwards ([`crate::project::Clip::reversed`]), named as a `speedkeys` line names its
85//! clip. The clip's window, speed and footprint are the lines it already has; the
86//! source-keyed `gainkeys` and `tkeys` are written as the clip plays them, so they
87//! need no knowing of the direction to be read. Written after the lanes it names, only
88//! for a reversed clip. **Version 38** is the first dialect with one; a project with
89//! none is written exactly as a v35 (or older) one.
90//!
91//! An `okeys` line is `okeys video <ord> <index> <at>:<ease>:<opacity> ...` and a
92//! `ckeys` line `ckeys video <ord> <index> <at>:<ease>:<b>,<c>,<s>,<t> ...`: a video
93//! clip's opacity and colour animations, keys in source order, each with the ease of
94//! the segment that leaves it (`lin`, `ease`, `in`, `out`, `hold`). **Version 39** is the
95//! first dialect with either, and the first where a `gainkeys` or `tkeys` point may
96//! carry an ease beyond linear and `ease`; a project with none is written as before.
97//!
98//! A `capstyle` line is `capstyle <animation> <rrggbb> <box 0|1> <uppercase 0|1> <words per
99//! line>`: the project's caption animation, written only when it is not the default. A
100//! `cuewords` line is `cuewords <track> <cue> <start_us> <end_us> <word> ...`: a cue's real
101//! word times, only for a cue that has them. **Version 40** is the first dialect with
102//! either; a project with neither is written under the header it needed before.
103//!
104//! A `cue` line is `cue <track> <cue> <text>`: an override of one cue's words,
105//! the track by position in the `subtitle` lines (the first is track 0) and the
106//! cue by its position in that track as its file parses -- so it needs the file
107//! it names to be the one it was edited against, which a project holds it to by
108//! not changing the file. The text is the rest of the line, escaped: `\\` for a
109//! backslash, `\n` and `\r` for the two line breaks, and nothing else. Applied
110//! on the way in, after the track is read, so the edited words come back where
111//! the file's would have been. Written after the `subtitle` lines it names and
112//! only when somebody has retyped a cue, so a project nobody has edited is the
113//! bytes it was. Like the `flags` lines it is v24: a v23 file has none.
114//!
115//! The `tonemap` line is which HDR-to-SDR rendition the project is watched and
116//! exported in ([`crate::tonemap::Preset`]), spelled `reference`, `standard` or
117//! `vivid`. Left out when it is the default, which is `reference` -- so a
118//! project holding no HDR media, and one whose owner never picked, are the bytes
119//! they were.
120//!
121//! The `proxy` line is whether this project is cut on the stand-ins
122//! ([`crate::proxy`]) rather than on the films themselves, spelled `on` or
123//! `off`. Left out when it is off, which is what every dialect before v12 was.
124//! *Which* sources have a stand-in is not written: a proxy is found by the
125//! film's own path, length and modification time, so the cache is the only
126//! answer and a project file cannot go stale about it.
127//!
128//! The `autoproxy` line is whether a film this machine cuts slowly gets a
129//! stand-in made for it the moment it is imported ([`crate::proxy::wanted`]),
130//! spelled `on` or `off`. Left out when it is on, which is what every dialect
131//! before v13 did and could not be told not to. With it off an import makes
132//! nothing at all, and turning the `proxy` switch on is what asks for the
133//! stand-ins this project is missing -- which is the only way to ask, so a
134//! project that never wants them never spends a minute of encode on one.
135//!
136//! The `encoder` line is which seat an export of this project writes its
137//! picture with ([`crate::export::EncoderSeat`]), spelled `auto`, `hardware` or
138//! `software`. Left out when it is `auto` -- hardware where this machine has a
139//! seat and software everywhere else -- which is what every dialect before v14
140//! did and could not be told otherwise. It is the project's and not the
141//! machine's for the reason the tone map is: a person who picked the software
142//! encoder for *this* delivery picked it for every export of it, and a pick
143//! that vanished on a reload is a pick nobody could keep.
144//!
145//! The `limiter` line is the master limiter over the whole mix
146//! ([`crate::limiter`]): its true-peak ceiling in dBTP and whether it is in circuit,
147//! spelled `on` or `off`. Left out when it is the default, which is off.
148//!
149//! A `gain` line is `gain <kind> <lane> <dB>`: how loud that whole lane plays,
150//! everything on it and every frequency of it -- a different thing from a
151//! clip's `eq` line, which is one take and one band. It names its lane the way
152//! a clip line does and comes *after* the lanes, because a lane is declared by
153//! its clips and a gain declares nothing. Only a lane somebody has turned gets
154//! one; the rest are at 0 dB, which is where every lane of every dialect before
155//! v9 is.
156//!
157//! A `voice` line is `voice audio <lane> <processor> <fields>...`: one audio lane's voice
158//! cleanup ([`crate::voice`]), one line per processor that is not at its default --
159//! `gate <on> <threshold> <attack> <release> <hold> <range>`, `nr <on> <strength> <floor>
160//! <profile>` (the noise profile as 256 comma-separated dB, or `-`), `comp <on> <threshold>
161//! <ratio> <attack> <release> <knee> <makeup> <auto>` and `deess <on> <threshold> <amount>
162//! <lo> <hi>`. **Version 41** is the first dialect with one; a project with every lane at
163//! the defaults is written under the header it needed before, and a v40 file loads with every
164//! processor off.
165//!
166//! An `effect` line is `effect video <lane> <clip> <kind> <on> <value>...`: one effect of
167//! a clip's effects stack ([`crate::effects`]), the lines of one clip in stack order. `kind`
168//! is the effect's name (`blur`, `vignette`, `chroma_key`, ...), `on` is `1` or `0`, and the
169//! values are its parameters in [`crate::effects::EffectKind::params`] order, each in its
170//! range. **Version 42** is the first dialect with one; a project with no effect on any clip
171//! is written under the header it needed before.
172//!
173//! A `stab` line is `stab video <ord> <index> <strength> <crop>`: a video clip's
174//! stabilisation ([`crate::stabilise`]), strength `0..=1` and crop `zoom` or `full`. Only a
175//! stabilised clip gets one. **Version 44** is the first dialect with one; a project with no
176//! stabilised clip is written under the header it needed before.
177//!
178//! A `lanename` line is `lanename <kind> <lane> <name>`: the display label a lane was given
179//! (the text escaped as a title's is); the lane keeps its address. A `deint` line is
180//! `deint video <ord> <index> <mode>` with mode `field` or `off` (`frame` is the default and
181//! written by no one): how a clip's interlaced source is deinterlaced. **Version 46** is the
182//! first dialect with either; a project with no named lane and no such clip is written under
183//! the header it needed before.
184//!
185//! A `flags` line is `flags <kind> <lane> <switch>...`: which lane, named as a
186//! gain names one, and then the switches that are set on it -- any of `hidden`,
187//! `muted` and `locked`, each at most once, in any order. `hidden` is for a
188//! video or subtitle lane and `muted` for an audio one: a switch the kind of
189//! lane cannot have is refused, as the setters refuse it. Like a gain it comes
190//! after the lanes and only a lane somebody has switched gets one, so a
191//! project with none is the bytes a v23 one was bar the version line.
192//!
193//! A `duck` line is `duck audio <lane> <under> <depth> <threshold> <attack> <release>`:
194//! the audio lane that is ducked, the audio lane it is ducked under (its key),
195//! both named as a gain names an audio lane (1-based, `audio 1` is `A1`), then
196//! the depth in dB (`-40..=0`), the key threshold in dBFS (`-90..=0`), and the
197//! attack and release in ms (attack `1..=2000`, release `1..=10000`). Like a
198//! gain it comes after the lanes, a duck names its key lane, and only a lane
199//! somebody has ducked gets one; a key may not be the lane it ducks. A project
200//! with none is the bytes a v24 one was bar the version line. **Version 30** lets
201//! a lane be ducked under several keys: one `duck` line per key, in the order
202//! the lane holds them, and the same key twice is refused. Before it a lane has
203//! one `duck` line, and a second for it is refused by name.
204//!
205//! A `title` line is one title card or text overlay:
206//! `title <start> <frames> <fade_in> <fade_out> <size> <outline> <boxed> <place> <text>`.
207//! The frames are timeline frames (the title shows on `start..start+frames`),
208//! the fades are frames, `size` is the em size in permille of the frame height
209//! (`10..=200`), `outline` is `none`, `thin` or `thick`, `boxed` is `0` or `1`,
210//! and `place` is `bottom`, `top` or `centre`. The text is the rest of the line,
211//! escaped as a `cue` line's is, so it may hold spaces and a line break as `\n`.
212//! Titles are written in list order, after the `duck` lines; a project with none
213//! is the bytes a v25 one was bar the version line.
214//!
215//! **Version 49** gives a title a look: a `titlestyle <title> <position> <align> <weight>
216//! <rrggbb> <rrggbbaa>` line after the `title` lines, one per title that is not white, regular,
217//! centred on a black 60% box, naming the title by its place in the list (0 is the first).
218//! `position` is where the block sits across the frame and `align` how its lines line up in it
219//! (both `centre`, `left` or `right`); `weight` is `regular` or `bold`; the first colour is the
220//! letters, the second the box with its opacity last. A project with none is the bytes a v48 one
221//! was bar the version line.
222//!
223//! **Version 54** gives a title an entrance and an exit animation: a `titleanim <title> <in> <out>
224//! <frames>` line after the `titlestyle` lines, one per title that has either, naming the title by
225//! its place in the list. `in` and `out` are the animation's name ([`TitleAnim::name`], `none` for
226//! none) and `frames` how long each takes. A project with none is the bytes a v53 one was bar the
227//! version line.
228//!
229//! **Version 56** animates any effect parameter: an `ekeys video <ord> <index> <slot> <at>:<ease>:<v0>,<v1>,...`
230//! line per effect with keys, the keys in source order, with one value for each of the effect's
231//! parameters ([`crate::effects::EffectKind::params`]) and the ease of the segment that leaves each
232//! key (a custom bezier is written as [`KeyEase::token`] gives it). A parameter that cannot be
233//! keyed (a switch or a choice) holds its static value. A v53 file's `mkeys` lines, which keyed
234//! only a mask's position, size and soft edge, are still read. A project with none is the bytes a
235//! v55 one was bar the version line.
236//!
237//! A `ttkeys` line is `ttkeys <title> <at>:<ease>:<x>,<y>,<scale>,<opacity> ...`: a title's own
238//! keyframe animation ([`crate::titleanim::TitleKey`]), the title named by its place in the list
239//! and the keys in frame order, `at` counted from the title's first frame. Written after the
240//! title's `titleanim` line, one per title that has keys. It is also v56, so a project with title
241//! keys is written as v56 and a project with none is the bytes a v55 one was bar the version line.
242//!
243//! A `cueadd` line is one cue added to a subtitle track, which no file has:
244//! `cueadd <track> <start_us> <end_us> <text>`, the track by its position in
245//! the `subtitle` lines, the times in microseconds on the track's own clock, and
246//! the text escaped as a `cue` line's is. It comes after the `cue` lines, so an
247//! added cue lands among the file's cues however they were retyped. A project
248//! with none is the bytes a v28 one was bar the version line.
249//!
250//! A `pitch` line is `pitch audio <ord> <index> <semitones>`: an audio clip's pitch
251//! shift in whole semitones, `-12` to `12`, written for each clip that is not at `0`,
252//! after the lanes it names (as `clippan` is). **Version 52** is the first dialect
253//! with one; a project with none is the bytes a v51 one was bar the version line.
254//!
255//! The `resolution` line is the **project's** picture size, which is a
256//! different thing from any source's: media of other sizes are placed on it.
257//! It belongs once, beside the playhead, and a file without one (every dialect
258//! before v7) means "source 0's own picture", which is what such a project
259//! always was.
260//!
261//! A source line is `source <audio stream> <path>`: which of the file's audio
262//! tracks that source plays, in the file order
263//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
264//! stream first because a path runs to the end of the line (it may hold
265//! spaces) and an optional *trailing* field could not be told from one.
266//!
267//! An eq line is `eq <band>...`, one band per field, each
268//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk`, `hs`,
269//! `lc` (low cut) or `hc` (high cut) ([`crate::eq::BandKind`]). Like a source it is named by *position* --
270//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
271//! curve write it once. `eq` on its own is the empty cascade, which is a
272//! setting like any other. The numbers are printed to round trip bit-exactly;
273//! anything not finite is refused, here and at [`crate::Project::set_eq`].
274//!
275//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
276//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
277//! -- the first colour line is color 0 -- printed and refused by the same rules.
278//!
279//! A colour line's look ([`crate::color::Look`]) rides on three line types
280//! written at the end of the file and naming the colour line by position:
281//! `wheels <color> <lift> <gamma> <gain>` (each `<master>:<red>:<green>:<blue>`,
282//! -1..1), `curve <color> <channel> <x>:<y>,...` (channel `master`, `red`, `green`
283//! or `blue`, up to 16 points in 0..1 with rising inputs) and `lut <color> <mix>
284//! <path>` (mix 0..1, the path written as a source's is). **Version 43** is the
285//! first dialect with them; a project whose grades have no look is written under
286//! the header it needed before. A LUT file that is missing or malformed does not
287//! stop the load: the clip plays without it and the project names it
288//! ([`crate::Project::lut_problems`]).
289//!
290//! A transform line is `transform <pos_x>:<pos_y>:<scale>:<rotate>:<crop_l>:
291//! <crop_r>:<crop_t>:<crop_b>` ([`crate::transform::TransformParams`]), named by
292//! position exactly as an eq or a colour line is -- the first transform line is
293//! transform 0 -- printed and refused by the same rules: how a clip's picture
294//! sits, is sized, is turned and is trimmed on the canvas, on top of whatever
295//! its fit policy already placed.
296//!
297//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
298//! <color> <fit> <speed> <fade_in> <fade_out> <transition_out> <transform> <visualizer> <viz_paint>`:
299//! which lane the clip is on -- its kind and its 1-based number
300//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
301//! column shows -- then where the clip sits on the timeline, the half-open
302//! source range it plays, the file it plays from, its group id, the eq line it
303//! plays through, the colour line it is graded by (`-` for none of those three)
304//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
305//! `stretch` or `center` ([`crate::scale::FitPolicy`]), how fast it plays,
306//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip
307//! nobody has speeded), and finally its ramp up from silence and ramp down to
308//! it, in timeline frames ([`crate::project::Clip::fade_in`],
309//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), its
310//! cross-dissolve into whatever abuts its end
311//! ([`crate::project::Clip::transition_out`], `0` for a hard cut), and last of
312//! all the transform line it is placed, sized, turned and cropped by, on top
313//! of everything its fit policy already did (`-` for a clip left at its fit
314//! policy's own spot, [`crate::project::Clip::transform`]), a visualizer
315//! flags byte (`0` for an ordinary picture, bit 0 for a waveform of the
316//! source's sound, the rest outline/smooth/fast/tint) and that waveform's
317//! packed look ([`crate::project::Clip::viz_paint`]): hue, sat, strands and
318//! glow in the low four bytes, then the strand colour's own hue and sat,
319//! with the top bit set once a clip has chosen one.
320//! Timeline placement is
321//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
322//! to write for one, and nothing that can disagree about its length. The `<in>`
323//! and `<out>` are *source* frames whatever the speed says: how long the clip is
324//! on the timeline is that range divided by the rate, and is written nowhere.
325//!
326//! A lane is declared by the clips on it, in the order the lanes are displayed
327//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
328//! is the only way an empty lane could still be there on the way back. A lane
329//! number may not skip one of its kind.
330//!
331//! A subtitle lane is a lane like the other two and is written in its place
332//! among them, `sub` for its kind: `sub <lane> <start> <frames> <track>
333//! <in> <out>` ([`crate::project::SubClip`]) -- where the caption sits on the
334//! timeline and how many frames it covers, then which `subtitle` line's words
335//! it shows (by position, the first one is track 0) and the half-open window of
336//! that track it shows, in *microseconds*, which is the clock the cues
337//! themselves are timed in. Two clocks on one line because a subtitle has two:
338//! a placement is in timeline frames like everything else, and a window is in
339//! the file's own time whatever the timeline runs at. A lane holding nothing
340//! has the bare `sub <lane>` line for the reason a video one does, and the
341//! track a caption names has to be one the file declared -- a `sub` line naming
342//! track 3 of a two-track palette is refused here, as a clip naming a source
343//! that is not there is.
344//!
345//! **Version 23** was this without the `flags` lines: such a project has no
346//! lane hidden, muted or locked, which is what every lane of every dialect
347//! before it is.
348//! **Version 22** was this with a 32-bit packed look: such a project's clips
349//! chose no strand colour, which is what the top bit still clear means, and
350//! their value is the low half of the one v23 writes.
351//! **Version 19** was this without the clip's transform field: such a project
352//! places no clip anywhere but its fit policy's own spot, which is what `-`
353//! still means. **Version 18** was that without the clip's transition field:
354//! such a project dissolves no clip into its neighbor, which is what `0` still
355//! means. **Version 17** was this without the clip's two fade fields: such a project
356//! holds no clip anyone has faded, which is what a `0 0` pair still means.
357//! **Version 15** was this without the caption's group field: such a project
358//! holds captions no hand ever grouped, which is every caption there could be.
359//! **Version 14** was that without the `sub` lines: such a project holds no
360//! subtitle lane at all -- its `subtitle` lines are the palette, and where the
361//! words of it were shown was nowhere in the file.
362//! **Version 13** was that without the `encoder` line: such a project takes the
363//! hardware seat where there is one and the software encoder
364//! everywhere else, which is the only choice those projects had.
365//! **Version 12** was that without the `autoproxy` line: such a project makes a
366//! stand-in for every film that wants one the moment it arrives, which is all
367//! any project could do.
368//! **Version 11** was that without the `proxy` line: such a project is cut on
369//! its films themselves, which is all any project could do.
370//! **Version 10** was that without the `tonemap` line: such a project is shown
371//! in the reference rendition, which is the only one there was.
372//! **Version 9** was that without the `subtitle` lines: such a project shows no
373//! subtitles, which is all any project could do.
374//! **Version 8** was that without the `fps` and `limiter` lines and without
375//! the `gain` ones: such a project mixes every lane at unity, limits nothing,
376//! and comes back at the rate its scaffolding source runs at.
377//! **Version 7** was that without the clip's speed field -- every clip of such
378//! a project plays at real time, which is the only rate there was.
379//! **Version 6** was that without the `resolution` line and without the clip's
380//! fit field -- such a project is the size of its first source and letterboxes
381//! nothing, because nothing on it could differ in size. **Version 5** was that
382//! without the colour lines and without the clip's colour
383//! field. **Version 4** was that without the eq lines and without the clip's eq
384//! field. **Version 3** was that without the lane number, and held one video
385//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
386//! well, which is this file's stream 0 -- one per file, whichever audio track
387//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
388//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
389//! cumulatively and copied onto both lanes as one group each, which is exactly
390//! what a v1 timeline meant, and an older file simply equalizes and grades
391//! nothing, and an older one plays everything at real time, and an older one
392//! mixes flat, and an older one shows no subtitles, and an older one is shown
393//! in the reference rendition, and an older one places none of the words it
394//! names, and an older one has no lane hidden, muted or locked -- and saving
395//! any of them writes v24. An older
396//! reader refuses a newer file by name.
397//!
398//! Text because an edit list is a few integers and a path, and a path is
399//! *bytes* on this platform -- a JSON string would have to lossily decode one.
400//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
401//! everything a line-based format cannot carry) and survives round-trip
402//! exactly. Paths under the project file's own directory are written relative
403//! to it, so a folder holding the media and the `.edith` can be moved or
404//! copied anywhere and still open; anything else is absolute.
405//!
406//! The parser is strict and every refusal names its 1-based line: a project
407//! file is generated, so a line it did not generate is a corrupt file, not a
408//! dialect. Structure is checked here (fields, ordering, empty clips,
409//! out-of-range source indexes); whether the files on disk still match the
410//! timeline is [`crate::PlaybackSession::open_project`]'s business.
411//!
412//! Writing goes through `<path>.part` and a rename, as an export does, so an
413//! interrupted save cannot destroy the previous version of the project. The
414//! bytes are fsynced before the rename and the directory after it, so what a
415//! power loss can lose is a whole save, never half of one under the real name.
416
417use std::ffi::OsString;
418use std::io::Write;
419use std::os::unix::ffi::{OsStrExt, OsStringExt};
420use std::path::{Path, PathBuf};
421
422use crate::color::ColorParams;
423use crate::duck::{
424 Duck, MAX_ATTACK_MS, MAX_DEPTH_DB, MAX_RELEASE_MS, MAX_THRESHOLD_DB, MIN_DEPTH_DB,
425 MIN_THRESHOLD_DB, MIN_TIME_MS,
426};
427use crate::eq::{Band, BandKind, EqParams};
428use crate::limiter::Limiter;
429use crate::project::{
430 Chapter, Clip, Deinterlace, GainKey, Marker, MarkerColor, Lane, LaneFlags, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_KEYS,
431 MAX_SPEED_KEYS, MIN_CLIP_GAIN_DB, STILL_DEFAULT_SECS, STILL_MAX_SECS, STILL_MIN_SECS, Source, Speed, SpeedKey, SubClip,
432 Title, check_chapter, check_marker, check_title,
433};
434use crate::scale::FitPolicy;
435use crate::subtitle::SubtitleTrack;
436use crate::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};
437use crate::voice::{Compressor, DeEsser, Gate, NoiseReduction, VoiceFx};
438use crate::text::{Align, HPlace, Outline, Place, TextStyle, Weight};
439use crate::titleanim::{TitleAnim, TitleKey};
440use crate::color::{ColorKey, MAX_COLOR_KEYS};
441use crate::transitions::TransitionKind;
442use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, TransformParams};
443
444/// The newest project format version: the `N` in the `edith N` first line that
445/// [`save`] writes for a project that uses the newest features. A reader refuses any
446/// higher version by name.
447pub const NEWEST_VERSION: u32 = 57;
448
449/// What [`save`] writes. Read support goes back to `edith 1`; see the module
450/// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`].
451const MAGIC: &[u8] = b"edith 57";
452const MAGIC_V56: &[u8] = b"edith 56";
453const MAGIC_V55: &[u8] = b"edith 55";
454const MAGIC_V54: &[u8] = b"edith 54";
455const MAGIC_V53: &[u8] = b"edith 53";
456const MAGIC_V52: &[u8] = b"edith 52";
457const MAGIC_V51: &[u8] = b"edith 51";
458const MAGIC_V50: &[u8] = b"edith 50";
459const MAGIC_V49: &[u8] = b"edith 49";
460const MAGIC_V48: &[u8] = b"edith 48";
461const MAGIC_V47: &[u8] = b"edith 47";
462const MAGIC_V46: &[u8] = b"edith 46";
463/// The most bands one equalizer line may declare. A hand-built cascade is a
464/// handful; the cap keeps a crafted line from making every clip run a million
465/// filters.
466const MAX_EQ_BANDS: usize = 64;
467/// The most words one `cuewords` line may carry (a cue is a line or two).
468const MAX_CUE_WORDS: usize = 1_000;
469/// The most sequences (tabs) a project may hold, each a parse of its own.
470const MAX_SEQUENCES: usize = 256;
471/// The most chapters, and the most markers, a project may hold.
472const MAX_LIST_ENTRIES: usize = 100_000;
473
474const MAGIC_V45: &[u8] = b"edith 45";
475const MAGIC_V44: &[u8] = b"edith 44";
476const MAGIC_V43: &[u8] = b"edith 43";
477const MAGIC_V42: &[u8] = b"edith 42";
478const MAGIC_V41: &[u8] = b"edith 41";
479const MAGIC_V40: &[u8] = b"edith 40";
480const MAGIC_V39: &[u8] = b"edith 39";
481const MAGIC_V38: &[u8] = b"edith 38";
482const MAGIC_V37: &[u8] = b"edith 37";
483const MAGIC_V36: &[u8] = b"edith 36";
484const MAGIC_V35: &[u8] = b"edith 35";
485const MAGIC_V34: &[u8] = b"edith 34";
486const MAGIC_V33: &[u8] = b"edith 33";
487const MAGIC_V32: &[u8] = b"edith 32";
488const MAGIC_V31: &[u8] = b"edith 31";
489const MAGIC_V30: &[u8] = b"edith 30";
490const MAGIC_V29: &[u8] = b"edith 29";
491const MAGIC_V28: &[u8] = b"edith 28";
492const MAGIC_V27: &[u8] = b"edith 27";
493const MAGIC_V26: &[u8] = b"edith 26";
494const MAGIC_V25: &[u8] = b"edith 25";
495const MAGIC_V24: &[u8] = b"edith 24";
496const MAGIC_V23: &[u8] = b"edith 23";
497const MAGIC_V22: &[u8] = b"edith 22";
498const MAGIC_V21: &[u8] = b"edith 21";
499const MAGIC_V20: &[u8] = b"edith 20";
500const MAGIC_V19: &[u8] = b"edith 19";
501const MAGIC_V18: &[u8] = b"edith 18";
502const MAGIC_V17: &[u8] = b"edith 17";
503const MAGIC_V16: &[u8] = b"edith 16";
504const MAGIC_V15: &[u8] = b"edith 15";
505const MAGIC_V14: &[u8] = b"edith 14";
506const MAGIC_V13: &[u8] = b"edith 13";
507const MAGIC_V12: &[u8] = b"edith 12";
508const MAGIC_V11: &[u8] = b"edith 11";
509const MAGIC_V10: &[u8] = b"edith 10";
510const MAGIC_V9: &[u8] = b"edith 9";
511const MAGIC_V8: &[u8] = b"edith 8";
512const MAGIC_V7: &[u8] = b"edith 7";
513const MAGIC_V6: &[u8] = b"edith 6";
514const MAGIC_V5: &[u8] = b"edith 5";
515const MAGIC_V4: &[u8] = b"edith 4";
516const MAGIC_V3: &[u8] = b"edith 3";
517const MAGIC_V2: &[u8] = b"edith 2";
518const MAGIC_V1: &[u8] = b"edith 1";
519
520/// What a project file says: an edit list plus where the playhead stood.
521/// Structurally valid by construction -- see [`parse`].
522#[derive(Debug)]
523pub struct Document {
524 /// Paths absolute, relative entries already joined to the file's own
525 /// directory.
526 pub sources: Vec<Source>,
527 /// Every lane, in display order, which is the order
528 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
529 /// `A1` -- for every dialect before v4.
530 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
531 /// What is placed on each lane, in the order `lanes` is in and as long as
532 /// it -- the `sub` lines. Empty for every video and audio lane, which hold
533 /// no [`SubClip`], and for every lane of every dialect before v15, which
534 /// placed no words anywhere ([`crate::Project::with_subs`] takes it back).
535 pub subs: Vec<Vec<SubClip>>,
536 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
537 /// every dialect before v5.
538 pub eq: Vec<EqParams>,
539 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
540 /// every dialect before v6.
541 pub color: Vec<ColorParams>,
542 /// The transform table [`Clip::transform`] indexes into, in file order.
543 /// Empty for every dialect before v20.
544 pub transform: Vec<TransformParams>,
545 /// The project's own picture size. `None` for every dialect before v7 and
546 /// for a v7 file that leaves it out, which both mean "source 0's picture".
547 pub resolution: Option<(u32, u32)>,
548 /// Every lane's own volume in dB, in the order `lanes` is in and as long as
549 /// it; `0.0` for a lane nobody has turned, which is every lane of every
550 /// dialect before v9.
551 pub gains: Vec<f32>,
552 /// Every lane's switches -- hidden, muted, locked -- in the order `lanes` is
553 /// in and as long as it. All clear for every dialect before v24, which had
554 /// no such switches, and for a lane a `flags` line does not name.
555 pub flags: Vec<LaneFlags>,
556 /// Every lane's auto-ducks, in the order `lanes` is in and as long as it;
557 /// empty for every lane but an audio lane somebody has ducked. Each lane
558 /// has at most one duck per key. Empty of every list for every dialect
559 /// before v25, which had no ducks, and at most one per lane before v30.
560 pub ducks: Vec<Vec<Duck>>,
561 /// The title cards and text overlays, in the order the file has them.
562 /// Empty for every dialect before v26, which had none.
563 pub titles: Vec<Title>,
564 /// The chapter markers, in frame order. Empty for every dialect before v34.
565 pub chapters: Vec<Chapter>,
566 /// The comment markers, in frame order. Empty for every dialect before v36.
567 pub markers: Vec<Marker>,
568 /// How burned captions animate, the `capstyle` line. The default (static cues) for every
569 /// dialect before v40.
570 pub caption_style: CaptionStyle,
571 /// Every lane's voice processors, in the order `lanes` is in and as long as it.
572 /// All off for every dialect before v41, and for a lane no `voice` line names.
573 pub voices: Vec<VoiceFx>,
574 /// One display name per lane (empty for none), from the `lanename` lines (v46).
575 pub names: Vec<String>,
576 /// The master limiter. Off for every dialect before v9, and for a v9 file
577 /// that leaves the line out.
578 pub limiter: Limiter,
579 /// The subtitle tracks, as the file names them: the path the cues are in
580 /// and which track of it, which is what [`crate::subtitle::open`] takes.
581 /// Reading them is the loader's business, not this module's -- a `.edith`
582 /// holds no cues. Empty for every dialect before v10.
583 pub subtitles: Vec<(PathBuf, Option<u64>)>,
584 /// The language of a subtitle track, `(track, code)`: the track by its
585 /// position in `subtitles`, the code as the file holds it (ISO 639-2 for
586 /// one set by a person, a container's own tag for an embedded track that
587 /// was not retyped). Empty for every dialect before v33.
588 pub sub_langs: Vec<(usize, String)>,
589 /// The cue overrides, `(track, cue, text)`: the track by its position in
590 /// `subtitles`, the cue by its position in that track. Empty for every
591 /// dialect before v24.
592 pub cue_edits: Vec<(usize, usize, String)>,
593 /// The cues added to a track ([`crate::project::AddedCue`]), each on its
594 /// track's own clock. Empty for every dialect before v29.
595 pub cue_adds: Vec<crate::project::AddedCue>,
596 /// The word times of cues, `(track, cue, words)` with the cue by its position in the track
597 /// as it stands after the edits and additions: the `cuewords` lines (v40). Empty before v40.
598 pub cue_words: Vec<crate::project::CueWordRow>,
599 /// The timeline's frame rate. `None` for every dialect before v9 and for a
600 /// v9 file that leaves it out, which both mean "whatever the scaffolding
601 /// source runs at" -- the inference a project of nothing but stills and
602 /// songs has no answer for (see
603 /// [`crate::PlaybackSession::open_project`]).
604 pub fps: Option<f64>,
605 /// The HDR-to-SDR rendition every clip on an HDR curve is shown in.
606 /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and
607 /// for a v11 file that leaves the line out, which both mean the published
608 /// conversion -- the only one those projects had.
609 pub tone: crate::tonemap::Preset,
610 /// Whether the films are cut on their stand-ins ([`crate::proxy`]). `false`
611 /// for every dialect before v12 and for a v12 file that leaves the line
612 /// out, which both mean the films themselves -- the only thing those
613 /// projects could do.
614 pub proxy: bool,
615 /// Whether an import makes a stand-in for a film that wants one by itself
616 /// ([`crate::proxy`]). `true` for every dialect before v13 and for a v13
617 /// file that leaves the line out, which both mean by itself -- the only
618 /// thing those projects did.
619 pub auto_proxy: bool,
620 /// Which encoder an export writes the picture with
621 /// ([`crate::export::EncoderSeat`]). `Auto` for every dialect before v14 and
622 /// for a v14 file that leaves the line out, which both mean the seat this
623 /// machine has -- the only choice those projects offered.
624 pub encoder: crate::export::EncoderSeat,
625 /// The rate the project's *sound* is mixed and exported at, chosen rather
626 /// than probed. `None` for every dialect before v17 and for a v17 file that
627 /// leaves the line out, which both mean what they always did: the rate of
628 /// the sources' own: the highest rate among the sources that have sound,
629 /// or 48 kHz when every one of them is below 44.1 kHz. Playback and export
630 /// both resample every other source
631 /// to whichever rate this resolves to, exactly as they already resample a
632 /// source shot at another rate than the timeline's -- an explicit choice
633 /// here only changes what that timeline's own rate *is*.
634 pub sample_rate: Option<u32>,
635 pub playhead: u32,
636 /// The active sequence's id and name, from the `seqactive` line (v45). `None` for a file
637 /// that holds one sequence, which is every dialect before v45.
638 pub seq_active: Option<(u32, String)>,
639 /// The tab order, from the `seqorder` line.
640 pub seq_order: Vec<u32>,
641 /// The other sequences, each a complete document of its own (`seq` ... `endseq`).
642 pub sequences: Vec<SeqDoc>,
643 /// The `mcam` lines (v47): a multicam source sequence's id and one angle's name each, in
644 /// angle order. Empty for a file with no multicam clip.
645 pub mcams: Vec<(u32, String)>,
646 /// The library's bins, from the `bin` lines (v51). Empty for a file with none.
647 pub bins: Vec<crate::project::Bin>,
648 /// The project notes, from the `notes` line (v52). Empty for a file with none, and for
649 /// every dialect before v52.
650 pub notes: String,
651 /// The length a still is placed at, from the `still` line (v52). `None` for a file that
652 /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s.
653 pub still_secs: Option<f64>,
654 /// The speech model, from the `speech` line (v57). `None` for a file that names none, which
655 /// means the model is picked.
656 pub speech_model: Option<String>,
657 /// The device the speech model runs on, from the `speech` line (v57). Auto for a file without one.
658 pub speech_device: crate::speech::DeviceChoice,
659}
660
661/// A parked sequence read off a v45 file.
662#[derive(Debug)]
663pub struct SeqDoc {
664 pub id: u32,
665 pub name: String,
666 pub doc: Document,
667}
668
669/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
670/// already be orphan-free ([`crate::Project::without_orphan_sources`]);
671/// `gains` is one dB per lane in the same order the lanes are in
672/// ([`crate::Project::lane_gains`]) and `subs` is one list of placements per
673/// lane in that same order ([`crate::Project::lane_subs`]).
674///
675/// The same as [`save_flagged`] with every lane's switches clear, for the
676/// callers that have none to write.
677#[allow(clippy::too_many_arguments)]
678pub fn save(
679 path: &Path,
680 sources: &[Source],
681 lanes: &[(LaneKind, Vec<Clip>)],
682 gains: &[f32],
683 subs: &[Vec<SubClip>],
684 subtitles: &[SubtitleTrack],
685 eq: &[EqParams],
686 color: &[ColorParams],
687 transform: &[TransformParams],
688 resolution: (u32, u32),
689 fps: Option<f64>,
690 tone: crate::tonemap::Preset,
691 proxy: bool,
692 auto_proxy: bool,
693 encoder: crate::export::EncoderSeat,
694 limiter: Limiter,
695 sample_rate: Option<u32>,
696 playhead: u32,
697) -> crate::Result<()> {
698 save_flagged(
699 path,
700 sources,
701 lanes,
702 gains,
703 subs,
704 subtitles,
705 eq,
706 color,
707 transform,
708 resolution,
709 fps,
710 tone,
711 proxy,
712 auto_proxy,
713 encoder,
714 limiter,
715 sample_rate,
716 playhead,
717 &[],
718 &[],
719 &[],
720 &[],
721 &[],
722 &[],
723 &[],
724 &CaptionStyle::default(),
725 &[],
726 &[],
727 )
728}
729
730/// The bytes [`save_flagged`] writes, for a caller that assembles a file of several parts
731/// ([`sequenced`]). `dir` is the project's directory, which relative paths are written against.
732#[allow(clippy::too_many_arguments)]
733pub fn encode_flagged(
734 dir: &Path,
735 sources: &[Source],
736 lanes: &[(LaneKind, Vec<Clip>)],
737 gains: &[f32],
738 subs: &[Vec<SubClip>],
739 subtitles: &[SubtitleTrack],
740 eq: &[EqParams],
741 color: &[ColorParams],
742 transform: &[TransformParams],
743 resolution: (u32, u32),
744 fps: Option<f64>,
745 tone: crate::tonemap::Preset,
746 proxy: bool,
747 auto_proxy: bool,
748 encoder: crate::export::EncoderSeat,
749 limiter: Limiter,
750 sample_rate: Option<u32>,
751 playhead: u32,
752 flags: &[LaneFlags],
753 ducks: &[Vec<Duck>],
754 cue_edits: &[(usize, usize, String)],
755 cue_adds: &[crate::project::AddedCue],
756 titles: &[Title],
757 chapters: &[Chapter],
758 markers: &[Marker],
759 caption_style: &CaptionStyle,
760 voices: &[VoiceFx],
761 names: &[String],
762) -> Vec<u8> {
763 let mut bytes = emit(
764 dir,
765 sources,
766 lanes,
767 gains,
768 subs,
769 subtitles,
770 eq,
771 color,
772 transform,
773 resolution,
774 fps,
775 tone,
776 proxy,
777 auto_proxy,
778 encoder,
779 limiter,
780 sample_rate,
781 playhead,
782 );
783 // The cue overrides after the subtitle lines `emit` wrote, which
784 // they name; then the switches, which name lanes, as the gains do.
785 bytes.extend_from_slice(&cue_lines(cue_edits));
786 bytes.extend_from_slice(&cue_add_lines(cue_adds));
787 let cue_words = cue_word_lines(subtitles);
788 bytes.extend_from_slice(&flag_lines(lanes, flags));
789 bytes.extend_from_slice(&duck_lines(lanes, ducks));
790 bytes.extend_from_slice(&title_lines(titles));
791 // The chapters after the titles, and a file that has any is v34 whatever
792 // `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
793 // the one line `emit` wrote that these change, so it is swapped here,
794 // where the lines they need are.
795 let ramped = lanes
796 .iter()
797 .any(|(_, clips)| clips.iter().any(|c| !c.speed_keys.is_empty()));
798 let transitioned = lanes.iter().any(|(_, clips)| {
799 clips.iter().any(|c| c.transition_kind != TransitionKind::Dissolve)
800 });
801 let reversed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.reversed));
802 // ...and one with an opacity or colour animation, or a key easing beyond
803 // linear and `ease`, is v39.
804 let animated = lanes.iter().any(|(_, clips)| clips.iter().any(needs_v39));
805 // ...and one with a project caption style or cue word times is v40.
806 let captioned = *caption_style != CaptionStyle::default() || !cue_words.is_empty();
807 // ...and one with a lane's voice processor is v41.
808 let voiced = voices.iter().any(|v| !v.is_default());
809 // ...and one with a clip's effect is v42.
810 let effected = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.effects.is_empty()));
811 // ...and one with a grade's wheels, curves or LUT is v43.
812 let looked = color.iter().any(|p| p.look != crate::color::Look::default());
813 // ...and one with a stabilised clip is v44.
814 let steadied = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.stabilise.is_some()));
815 // ...and one with a named lane or a clip's deinterlace choice is v46.
816 let named = names.iter().any(|n| !n.is_empty());
817 let deinterlaced = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.deinterlace != Deinterlace::Frame));
818 // ...and one with a multicam clip's angle is v47.
819 let angled = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.angle.is_default()));
820 // ...and one with a generated source (a solid, a gradient, a countdown, bars, an adjustment
821 // layer), a clip's colour label or a switched-off clip is v48.
822 // ...and one with a title's colour, weight, alignment, position or box colour is v49.
823 let styled = titles.iter().any(|t| !title_look_is_default(&t.style));
824 // ...and one with a title's entrance or exit animation is v54.
825 let titled = titles.iter().any(|t| t.in_anim != TitleAnim::None || t.out_anim != TitleAnim::None);
826 let marked = sources.iter().any(|s| crate::generate::is_generated(&s.path))
827 || lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.mark.is_default()));
828 // ...and one with a clip pan or a lane pan is v50.
829 let panned = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pan != 0)) || flags.iter().any(|f| f.pan != 0.0);
830 // ...and one with an effect's keys is v56 (`ekeys`), as is one with a custom bezier key easing.
831 let keyed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty())));
832 // ...and one with a clip's pitch shift is v55.
833 let pitched = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch != 0));
834 // ...and one with a title's own keys is v56 (`ttkeys`).
835 let title_keyed = titles.iter().any(|t| !t.keys.is_empty());
836 let curved = keyed || title_keyed || lanes.iter().any(|(_, clips)| clips.iter().any(has_bezier));
837 if curved || pitched || titled || panned || styled || marked || angled || named || deinterlaced || steadied || looked || effected || voiced || captioned || animated || reversed || transitioned || ramped || !chapters.is_empty() || !markers.is_empty() {
838 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
839 let header = if curved {
840 MAGIC_V56
841 } else if pitched {
842 MAGIC_V55
843 } else if titled {
844 MAGIC_V54
845 } else if panned {
846 MAGIC_V50
847 } else if styled {
848 MAGIC_V49
849 } else if marked {
850 MAGIC_V48
851 } else if angled {
852 MAGIC_V47
853 } else if named || deinterlaced {
854 MAGIC_V46
855 } else if steadied {
856 MAGIC_V44
857 } else if looked {
858 MAGIC_V43
859 } else if effected {
860 MAGIC_V42
861 } else if voiced {
862 MAGIC_V41
863 } else if captioned {
864 MAGIC_V40
865 } else if animated {
866 MAGIC_V39
867 } else if reversed {
868 MAGIC_V38
869 } else if transitioned {
870 MAGIC_V37
871 } else if !markers.is_empty() {
872 MAGIC_V36
873 } else if ramped {
874 MAGIC_V35
875 } else {
876 MAGIC_V34
877 };
878 bytes.splice(..first_end, header.iter().copied());
879 }
880 bytes.extend_from_slice(&chapter_lines(chapters));
881 bytes.extend_from_slice(&marker_lines(markers));
882 bytes.extend_from_slice(&capstyle_line(caption_style));
883 bytes.extend_from_slice(&cue_words);
884 bytes.extend_from_slice(&voice_lines(lanes, voices));
885 bytes.extend_from_slice(&clip_gain_lines(lanes));
886 bytes.extend_from_slice(&gain_key_lines(lanes));
887 bytes.extend_from_slice(&tkey_lines(lanes));
888 bytes.extend_from_slice(&speed_key_lines(lanes));
889 bytes.extend_from_slice(&transition_lines(lanes));
890 bytes.extend_from_slice(&reverse_lines(lanes));
891 bytes.extend_from_slice(&opacity_key_lines(lanes));
892 bytes.extend_from_slice(&color_key_lines(lanes));
893 bytes.extend_from_slice(&effect_lines(lanes));
894 bytes.extend_from_slice(&effect_key_lines(lanes));
895 bytes.extend_from_slice(&look_lines(color, dir));
896 bytes.extend_from_slice(&stab_lines(lanes));
897 bytes.extend_from_slice(&deint_lines(lanes));
898 bytes.extend_from_slice(&lane_name_lines(lanes, names));
899 bytes.extend_from_slice(&angle_lines(lanes));
900 bytes.extend_from_slice(&mark_lines(lanes));
901 bytes.extend_from_slice(&pan_lines(lanes, flags));
902 bytes.extend_from_slice(&pitch_lines(lanes));
903 bytes
904}
905
906/// `main` (a document as [`encode_flagged`] wrote it) with the library's lines after it (v51):
907/// `bin <id> <parent> <name>` for each bin, `srcbin <source> <bin>` for each filed source and
908/// `srcfav <source>` for each starred one. A library with none of these is `main` untouched, so
909/// such a project is the bytes it was before v51.
910/// `current` (a file's first line, without its newline) with `candidate` in its place when
911/// `candidate` is a newer dialect, else `current` untouched. The library and notes lines raise
912/// the header to what they need and never lower it, so a file with effect keys (v56) keeps v56.
913fn raise_header(current: &[u8], candidate: &[u8]) -> Vec<u8> {
914 let version = |h: &[u8]| {
915 std::str::from_utf8(h).ok().and_then(|l| l.strip_prefix("edith ")).and_then(|n| n.parse::<u32>().ok()).unwrap_or(0)
916 };
917 if version(candidate) > version(current) { candidate.to_vec() } else { current.to_vec() }
918}
919
920pub fn binned(mut main: Vec<u8>, sources: &[Source], bins: &[crate::project::Bin]) -> Vec<u8> {
921 let mut lines = Vec::new();
922 for b in bins {
923 lines.extend_from_slice(format!("bin {} {} ", b.id, b.parent).as_bytes());
924 escape_text(&b.name, &mut lines);
925 lines.push(b'\n');
926 }
927 for (i, s) in sources.iter().enumerate() {
928 if s.bin != 0 {
929 lines.extend_from_slice(format!("srcbin {i} {}\n", s.bin).as_bytes());
930 }
931 if s.fav {
932 lines.extend_from_slice(format!("srcfav {i}\n").as_bytes());
933 }
934 }
935 if lines.is_empty() {
936 return main;
937 }
938 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
939 let header = raise_header(&main[..first_end], MAGIC_V51);
940 main.splice(..first_end, header);
941 if main.last() != Some(&b'\n') {
942 main.push(b'\n');
943 }
944 main.extend_from_slice(&lines);
945 main
946}
947
948/// `main` with the project notes, the still length and the speech choices after it (v52, v57): a
949/// `notes` line when there are notes, a `still` line when the length is not the default, a
950/// `speech` line when a model or a device is picked. A project with none is `main` untouched, so
951/// it keeps the bytes it had before v52.
952pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64, speech_model: Option<&str>, speech_device: crate::speech::DeviceChoice) -> Vec<u8> {
953 let mut lines = Vec::new();
954 if !notes.is_empty() {
955 lines.extend_from_slice(b"notes ");
956 escape_text(notes, &mut lines);
957 lines.push(b'\n');
958 }
959 if still_secs != STILL_DEFAULT_SECS {
960 lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes());
961 }
962 let speech = speech_model.is_some() || speech_device != crate::speech::DeviceChoice::Auto;
963 if speech {
964 lines.extend_from_slice(format!("speech {}", speech_device.as_str()).as_bytes());
965 if let Some(m) = speech_model {
966 lines.extend_from_slice(format!(" {m}").as_bytes());
967 }
968 lines.push(b'\n');
969 }
970 if lines.is_empty() {
971 return main;
972 }
973 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
974 let header = raise_header(&main[..first_end], if speech { MAGIC } else { MAGIC_V52 });
975 main.splice(..first_end, header);
976 if main.last() != Some(&b'\n') {
977 main.push(b'\n');
978 }
979 main.extend_from_slice(&lines);
980 main
981}
982
983/// [`save`], with each lane's switches -- `flags` is one entry per lane in the
984/// same order as `lanes`, as `gains` is ([`crate::Project::lane_flags`]).
985#[allow(clippy::too_many_arguments)]
986pub fn save_flagged(
987 path: &Path,
988 sources: &[Source],
989 lanes: &[(LaneKind, Vec<Clip>)],
990 gains: &[f32],
991 subs: &[Vec<SubClip>],
992 subtitles: &[SubtitleTrack],
993 eq: &[EqParams],
994 color: &[ColorParams],
995 transform: &[TransformParams],
996 resolution: (u32, u32),
997 fps: Option<f64>,
998 tone: crate::tonemap::Preset,
999 proxy: bool,
1000 auto_proxy: bool,
1001 encoder: crate::export::EncoderSeat,
1002 limiter: Limiter,
1003 sample_rate: Option<u32>,
1004 playhead: u32,
1005 flags: &[LaneFlags],
1006 ducks: &[Vec<Duck>],
1007 cue_edits: &[(usize, usize, String)],
1008 cue_adds: &[crate::project::AddedCue],
1009 titles: &[Title],
1010 chapters: &[Chapter],
1011 markers: &[Marker],
1012 caption_style: &CaptionStyle,
1013 voices: &[VoiceFx],
1014 names: &[String],
1015) -> crate::Result<()> {
1016 let dir = project_dir(path);
1017 let bytes = encode_flagged(
1018 &dir,
1019 sources,
1020 lanes,
1021 gains,
1022 subs,
1023 subtitles,
1024 eq,
1025 color,
1026 transform,
1027 resolution,
1028 fps,
1029 tone,
1030 proxy,
1031 auto_proxy,
1032 encoder,
1033 limiter,
1034 sample_rate,
1035 playhead,
1036 flags,
1037 ducks,
1038 cue_edits,
1039 cue_adds,
1040 titles,
1041 chapters,
1042 markers,
1043 caption_style,
1044 voices,
1045 names,
1046 );
1047 write_atomic(path, &bytes)
1048}
1049
1050/// One parked sequence as a file holds it: a whole standalone document of its own.
1051pub struct SeqBlock {
1052 pub id: u32,
1053 pub name: String,
1054 pub bytes: Vec<u8>,
1055}
1056
1057/// `main` (the active sequence, as [`encode_flagged`] wrote it) with the other sequences after
1058/// it, as a v45 file: the `seqactive` and `seqorder` lines, then each parked sequence between
1059/// `seq <id> <name>` and `endseq`. The body of each block is a complete document, so its lines
1060/// read exactly as a project file's do.
1061pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[SeqBlock], mcam: &[(u32, Vec<String>)]) -> Vec<u8> {
1062 let mut bytes = main;
1063 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
1064 // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46
1065 // when a part is v46; a newer-only line under an older header is refused.
1066 let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n');
1067 let v57 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1068 let v56 = v57 || is(&bytes, MAGIC_V56) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V56));
1069 let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55));
1070 let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54));
1071 let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53));
1072 let v52 = v53 || is(&bytes, MAGIC_V52) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V52));
1073 let v51 = v52 || is(&bytes, MAGIC_V51) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V51));
1074 let v50 = v51 || is(&bytes, MAGIC_V50) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V50));
1075 let v49 = v50 || is(&bytes, MAGIC_V49) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V49));
1076 let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48));
1077 let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47));
1078 let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46));
1079 let header = if v57 { MAGIC } else if v56 { MAGIC_V56 } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 };
1080 bytes.splice(..first_end, header.iter().copied());
1081 bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes());
1082 escape_text(active.1, &mut bytes);
1083 bytes.push(b'\n');
1084 let ids: Vec<String> = order.iter().map(u32::to_string).collect();
1085 bytes.extend_from_slice(format!("seqorder {}\n", ids.join(" ")).as_bytes());
1086 for (id, names) in mcam {
1087 for name in names {
1088 bytes.extend_from_slice(format!("mcam {id} ").as_bytes());
1089 escape_text(name, &mut bytes);
1090 bytes.push(b'\n');
1091 }
1092 }
1093 for b in blocks {
1094 bytes.extend_from_slice(format!("seq {} ", b.id).as_bytes());
1095 escape_text(&b.name, &mut bytes);
1096 bytes.push(b'\n');
1097 bytes.extend_from_slice(&b.bytes);
1098 if bytes.last() != Some(&b'\n') {
1099 bytes.push(b'\n');
1100 }
1101 bytes.extend_from_slice(b"endseq\n");
1102 }
1103 bytes
1104}
1105
1106/// Writes `bytes` to `path` atomically: a `.part` file beside it, synced, renamed over it, and the
1107/// directory synced, so until the rename the old file is still the whole truth.
1108pub fn write_atomic(path: &Path, bytes: &[u8]) -> crate::Result<()> {
1109 let dir = project_dir(path);
1110 let mut part = path.to_path_buf().into_os_string();
1111 part.push(".part");
1112 let part = PathBuf::from(part);
1113 let result = std::fs::File::create(&part)
1114 .and_then(|mut f| {
1115 f.write_all(bytes)?;
1116 f.sync_all()
1117 })
1118 .and_then(|()| std::fs::rename(&part, path))
1119 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
1120 if result.is_err() {
1121 let _ = std::fs::remove_file(&part);
1122 }
1123 result.map_err(Into::into)
1124}
1125
1126pub fn load(path: &Path) -> crate::Result<Document> {
1127 let data = std::fs::read(path)?;
1128 // Relative lines are joined to the directory the project was opened
1129 // through, so the file is reached the way the project was opened; the
1130 // save side compares canonically (`written_path`), so whichever way it
1131 // was opened, a saved source is written relative.
1132 parse(&data, path.parent().unwrap_or(Path::new("")))
1133}
1134
1135/// The form a source or subtitle path is written in: relative to the project's
1136/// directory when the file is inside it, however the path was spelled -- a
1137/// `..` or a symlink on the way in is resolved before the comparison -- and as
1138/// it is otherwise. This is the one rule every save follows.
1139fn written_path(path: &Path, dir: &Path) -> PathBuf {
1140 if let Ok(rel) = path.strip_prefix(dir) {
1141 return rel.to_path_buf();
1142 }
1143 if let Ok(real) = path.canonicalize()
1144 && let Ok(rel) = real.strip_prefix(dir)
1145 {
1146 return rel.to_path_buf();
1147 }
1148 path.to_path_buf()
1149}
1150
1151/// The directory a project file's relative source lines are measured from, in
1152/// the same canonical form [`crate::Project`] keeps its sources in -- without
1153/// that the prefix simply never matches and every line comes out absolute,
1154/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
1155/// a bare filename is `""`). Canonicalizing fails only if the directory does
1156/// not exist, and then the write is about to fail anyway.
1157pub(crate) fn project_dir(path: &Path) -> PathBuf {
1158 let dir = path
1159 .parent()
1160 .filter(|p| !p.as_os_str().is_empty())
1161 .unwrap_or(Path::new("."));
1162 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
1163}
1164
1165/// The `cue` lines: one per retyped cue, after the `subtitle` lines that name
1166/// their tracks. Only a cue somebody has retyped has one, so an unedited project
1167/// is the bytes it was.
1168fn cue_lines(edits: &[(usize, usize, String)]) -> Vec<u8> {
1169 let mut out = Vec::new();
1170 for (track, cue, text) in edits {
1171 out.extend_from_slice(format!("cue {track} {cue} ").as_bytes());
1172 escape_text(text, &mut out);
1173 out.push(b'\n');
1174 }
1175 out
1176}
1177
1178/// The `cuewords` lines (v40): `cuewords <track> <cue> <start_us> <end_us> <word> ...` for each
1179/// cue that has word times, the cue by its position in the track as it stands when saved. The
1180/// times are on the track's own clock; a word has no whitespace, so a space separates fields.
1181fn cue_word_lines(subtitles: &[SubtitleTrack]) -> Vec<u8> {
1182 let mut out = Vec::new();
1183 for (t, track) in subtitles.iter().enumerate() {
1184 for (c, cue) in track.cues.iter().enumerate().filter(|(_, c)| !c.words.is_empty()) {
1185 out.extend_from_slice(format!("cuewords {t} {c}").as_bytes());
1186 for (start, end, word) in &cue.words {
1187 out.extend_from_slice(format!(" {start} {end} ").as_bytes());
1188 escape_text(word, &mut out);
1189 }
1190 out.push(b'\n');
1191 }
1192 }
1193 out
1194}
1195
1196/// The `cueadd` lines: one per cue added to a track, after the `cue` lines, as
1197/// `cueadd <track> <start_us> <end_us> <text>`, the text escaped as a `cue` line's is.
1198fn cue_add_lines(adds: &[crate::project::AddedCue]) -> Vec<u8> {
1199 let mut out = Vec::new();
1200 for a in adds {
1201 out.extend_from_slice(format!("cueadd {} {} {} ", a.track, a.start_us, a.end_us).as_bytes());
1202 escape_text(&a.text, &mut out);
1203 out.push(b'\n');
1204 }
1205 out
1206}
1207
1208/// The `duck` lines: one per duck, in lane order and then in the order the lane
1209/// holds them, the key named as the lanes are (1-based), so a project with none
1210/// is the bytes a v24 one was bar the version line.
1211fn duck_lines(lanes: &[(LaneKind, Vec<Clip>)], ducks: &[Vec<Duck>]) -> Vec<u8> {
1212 let mut out = Vec::new();
1213 let mut audio = 0u32;
1214 for ((kind, _), lane_ducks) in lanes.iter().zip(ducks) {
1215 if *kind != LaneKind::Audio {
1216 continue;
1217 }
1218 audio += 1;
1219 for d in lane_ducks {
1220 out.extend_from_slice(
1221 format!(
1222 "duck audio {audio} {} {:?} {:?} {:?} {:?}\n",
1223 d.under + 1,
1224 d.depth_db,
1225 d.threshold_db,
1226 d.attack_ms,
1227 d.release_ms
1228 )
1229 .as_bytes(),
1230 );
1231 }
1232 }
1233 out
1234}
1235
1236/// The `voice` lines: `voice audio <ord> <processor> <fields>...`, one per processor of an
1237/// audio lane that is not at its default (so a lane nobody has cleaned writes none, and a
1238/// project with none is the bytes a v36 one was bar the version line). The processors:
1239/// `gate <on> <threshold> <attack> <release> <hold> <range>`, `nr <on> <strength> <floor>
1240/// <profile>` (the profile a comma-separated list of dB, or `-`), `comp <on> <threshold>
1241/// <ratio> <attack> <release> <knee> <makeup> <auto>` and `deess <on> <threshold> <amount>
1242/// <lo> <hi>`; `<on>` and `<auto>` are `0` or `1`.
1243fn voice_lines(lanes: &[(LaneKind, Vec<Clip>)], voices: &[VoiceFx]) -> Vec<u8> {
1244 let mut out = String::new();
1245 let mut audio = 0u32;
1246 for ((kind, _), v) in lanes.iter().zip(voices) {
1247 if *kind != LaneKind::Audio {
1248 continue;
1249 }
1250 audio += 1;
1251 let b = |x: bool| u8::from(x);
1252 if v.gate != Gate::DEFAULT {
1253 let g = &v.gate;
1254 out += &format!(
1255 "voice audio {audio} gate {} {:?} {:?} {:?} {:?} {:?}\n",
1256 b(g.on), g.threshold_db, g.attack_ms, g.release_ms, g.hold_ms, g.range_db
1257 );
1258 }
1259 if v.nr != NoiseReduction::default() {
1260 let n = &v.nr;
1261 let profile = if n.profile.is_empty() {
1262 "-".to_string()
1263 } else {
1264 n.profile.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>().join(",")
1265 };
1266 out += &format!("voice audio {audio} nr {} {:?} {:?} {profile}\n", b(n.on), n.strength, n.floor_db);
1267 }
1268 if v.comp != Compressor::DEFAULT {
1269 let c = &v.comp;
1270 out += &format!(
1271 "voice audio {audio} comp {} {:?} {:?} {:?} {:?} {:?} {:?} {}\n",
1272 b(c.on), c.threshold_db, c.ratio, c.attack_ms, c.release_ms, c.knee_db, c.makeup_db, b(c.auto_makeup)
1273 );
1274 }
1275 if v.deess != DeEsser::DEFAULT {
1276 let d = &v.deess;
1277 out += &format!(
1278 "voice audio {audio} deess {} {:?} {:?} {:?} {:?}\n",
1279 b(d.on), d.threshold_db, d.amount, d.lo_hz, d.hi_hz
1280 );
1281 }
1282 }
1283 out.into_bytes()
1284}
1285
1286/// The pan lines (v50): `clippan audio <ord> <index> <pan>` for each audio clip that is not in the
1287/// middle, and `lanepan audio <ord> <pan>` for each audio lane that is not.
1288fn pan_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1289 let mut out = Vec::new();
1290 let mut audio = 0u32;
1291 for (n, (kind, clips)) in lanes.iter().enumerate() {
1292 if *kind != LaneKind::Audio {
1293 continue;
1294 }
1295 audio += 1;
1296 if let Some(f) = flags.get(n).filter(|f| f.pan != 0.0) {
1297 out.extend_from_slice(format!("lanepan audio {audio} {}\n", f.pan).as_bytes());
1298 }
1299 for (idx, c) in clips.iter().enumerate() {
1300 if c.pan != 0 {
1301 out.extend_from_slice(format!("clippan audio {audio} {idx} {}\n", c.pan_value()).as_bytes());
1302 }
1303 }
1304 }
1305 out
1306}
1307
1308/// The pitch lines (v55): `pitch audio <ord> <index> <semitones>` for each audio clip whose
1309/// pitch shift is not `0`.
1310fn pitch_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1311 let mut out = Vec::new();
1312 let mut audio = 0u32;
1313 for (kind, clips) in lanes {
1314 if *kind != LaneKind::Audio {
1315 continue;
1316 }
1317 audio += 1;
1318 for (idx, c) in clips.iter().enumerate() {
1319 if c.pitch != 0 {
1320 out.extend_from_slice(format!("pitch audio {audio} {idx} {}\n", c.pitch).as_bytes());
1321 }
1322 }
1323 }
1324 out
1325}
1326
1327/// The `clipgain` lines: one per clip whose own gain is not unity, as
1328/// `clipgain <kind> <ord> <index> <db>`. `index` counts the lane's clips from
1329/// `0`, in lane order. Written after the lanes they name, and only for a clip
1330/// somebody has turned, so a project with none is the bytes a v26 one was bar
1331/// the version line.
1332fn clip_gain_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1333 let mut out = Vec::new();
1334 let (mut video, mut audio) = (0u32, 0u32);
1335 for (kind, clips) in lanes {
1336 let (keyword, ord) = match kind {
1337 LaneKind::Video => {
1338 video += 1;
1339 ("video", video)
1340 }
1341 LaneKind::Audio => {
1342 audio += 1;
1343 ("audio", audio)
1344 }
1345 LaneKind::Subtitle => continue,
1346 };
1347 for (idx, c) in clips.iter().enumerate() {
1348 if c.gain_db != 0.0 {
1349 out.extend_from_slice(
1350 format!("clipgain {keyword} {ord} {idx} {}\n", c.gain_db).as_bytes(),
1351 );
1352 }
1353 }
1354 }
1355 out
1356}
1357
1358/// The `gainkeys` lines: one per clip with a volume envelope, as
1359/// `gainkeys <kind> <ord> <index> <at>:<db> ...`, the points in source order.
1360/// `kind` and `ord` name the lane the way [`clip_gain_lines`] does; `index`
1361/// counts the lane's clips from `0`. Written after the lanes they name, and
1362/// only for a clip with points, so a project with none is the bytes a v27 one
1363/// was bar the version line.
1364fn gain_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1365 let mut out = Vec::new();
1366 let (mut video, mut audio) = (0u32, 0u32);
1367 for (kind, clips) in lanes {
1368 let (keyword, ord) = match kind {
1369 LaneKind::Video => {
1370 video += 1;
1371 ("video", video)
1372 }
1373 LaneKind::Audio => {
1374 audio += 1;
1375 ("audio", audio)
1376 }
1377 LaneKind::Subtitle => continue,
1378 };
1379 for (idx, c) in clips.iter().enumerate() {
1380 if c.gain_keys.is_empty() {
1381 continue;
1382 }
1383 let points: String = c
1384 .gain_keys
1385 .iter()
1386 .map(|k| match k.ease {
1387 KeyEase::Linear => format!(" {}:{}", k.at, k.db),
1388 ease => format!(" {}:{}:{}", k.at, k.db, ease.token()),
1389 })
1390 .collect();
1391 out.extend_from_slice(format!("gainkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1392 }
1393 }
1394 out
1395}
1396
1397/// The `tkeys` lines: one per clip with a placement animation, as
1398/// `speedkeys <kind> <ord> <index> <at>:<permille> ...`, the keys in frame order. The
1399/// speeds are thousandths, as a clip's own `speed` field is, so they read back exactly.
1400/// Only a clip with keys gets a line, and such a project is a v35 one.
1401fn speed_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1402 let mut out = Vec::new();
1403 let (mut video, mut audio) = (0u32, 0u32);
1404 for (kind, clips) in lanes {
1405 let (keyword, ord) = match kind {
1406 LaneKind::Video => {
1407 video += 1;
1408 ("video", video)
1409 }
1410 LaneKind::Audio => {
1411 audio += 1;
1412 ("audio", audio)
1413 }
1414 LaneKind::Subtitle => continue,
1415 };
1416 for (idx, c) in clips.iter().enumerate() {
1417 if c.speed_keys.is_empty() {
1418 continue;
1419 }
1420 let points: String = c
1421 .speed_keys
1422 .iter()
1423 .map(|k| format!(" {}:{}", k.at, k.speed.permille()))
1424 .collect();
1425 out.extend_from_slice(format!("speedkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1426 }
1427 }
1428 out
1429}
1430
1431/// The `transition` lines: one per clip whose transition is not a dissolve, as
1432/// `transition <kind> <ord> <index> <name>`. Such a project is a v37 one.
1433fn transition_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1434 let mut out = Vec::new();
1435 let (mut video, mut audio) = (0u32, 0u32);
1436 for (kind, clips) in lanes {
1437 let (keyword, ord) = match kind {
1438 LaneKind::Video => {
1439 video += 1;
1440 ("video", video)
1441 }
1442 LaneKind::Audio => {
1443 audio += 1;
1444 ("audio", audio)
1445 }
1446 LaneKind::Subtitle => continue,
1447 };
1448 for (idx, c) in clips.iter().enumerate() {
1449 if c.transition_kind != TransitionKind::Dissolve {
1450 out.extend_from_slice(
1451 format!("transition {keyword} {ord} {idx} {}\n", c.transition_kind.name()).as_bytes(),
1452 );
1453 }
1454 }
1455 }
1456 out
1457}
1458
1459/// Whether a clip needs the v39 dialect: an opacity or colour animation, or a
1460/// key easing that v35 has no word for (`in`, `out`, `hold` on a placement key,
1461/// anything but linear on a volume point).
1462fn needs_v39(c: &Clip) -> bool {
1463 !c.opacity_keys.is_empty()
1464 || !c.color_keys.is_empty()
1465 || c.gain_keys.iter().any(|k| k.ease != KeyEase::Linear)
1466 || c.transform_keys
1467 .iter()
1468 .any(|k| matches!(k.ease, KeyEase::EaseIn | KeyEase::EaseOut | KeyEase::Hold))
1469}
1470
1471/// Whether a clip has a key with a custom bezier easing, which only v56 can
1472/// hold: a placement, opacity, colour, volume or mask key.
1473fn has_bezier(c: &Clip) -> bool {
1474 let bezier = |e: KeyEase| matches!(e, KeyEase::Bezier(_));
1475 c.transform_keys.iter().any(|k| bezier(k.ease))
1476 || c.opacity_keys.iter().any(|k| bezier(k.ease))
1477 || c.color_keys.iter().any(|k| bezier(k.ease))
1478 || c.gain_keys.iter().any(|k| bezier(k.ease))
1479 || c.effects.iter().any(|e| e.keys.iter().any(|k| bezier(k.ease)))
1480}
1481
1482/// One line per video clip that `points` returns something for, as
1483/// `<name> video <ord> <index>{points}`: the shape of the `okeys` and `ckeys` lines.
1484fn video_key_lines(
1485 lanes: &[(LaneKind, Vec<Clip>)],
1486 name: &str,
1487 points: impl Fn(&Clip) -> String,
1488) -> Vec<u8> {
1489 let mut out = Vec::new();
1490 let mut video = 0u32;
1491 for (kind, clips) in lanes {
1492 if *kind != LaneKind::Video {
1493 continue;
1494 }
1495 video += 1;
1496 for (idx, c) in clips.iter().enumerate() {
1497 let points = points(c);
1498 if !points.is_empty() {
1499 out.extend_from_slice(format!("{name} video {video} {idx}{points}\n").as_bytes());
1500 }
1501 }
1502 }
1503 out
1504}
1505
1506/// The `reverse` lines: one per clip that plays backwards, as `reverse <kind> <ord>
1507/// <index>`. Only a reversed clip gets a line, and such a project is a v38 one.
1508fn reverse_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1509 let mut out = Vec::new();
1510 let (mut video, mut audio) = (0u32, 0u32);
1511 for (kind, clips) in lanes {
1512 let (keyword, ord) = match kind {
1513 LaneKind::Video => {
1514 video += 1;
1515 ("video", video)
1516 }
1517 LaneKind::Audio => {
1518 audio += 1;
1519 ("audio", audio)
1520 }
1521 LaneKind::Subtitle => continue,
1522 };
1523 for (idx, _) in clips.iter().enumerate().filter(|(_, c)| c.reversed) {
1524 out.extend_from_slice(format!("reverse {keyword} {ord} {idx}\n").as_bytes());
1525 }
1526 }
1527 out
1528}
1529
1530/// `deint video <ord> <index> <mode>`: one per clip whose mode is not `frame`, and such a
1531/// project is a v46 one.
1532fn deint_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1533 video_key_lines(lanes, "deint", |c| match c.deinterlace {
1534 Deinterlace::Frame => String::new(),
1535 d => format!(" {}", d.name()),
1536 })
1537}
1538
1539/// `lanename <kind> <ord> <name>`: one per lane that has a name.
1540fn lane_name_lines(lanes: &[(LaneKind, Vec<Clip>)], names: &[String]) -> Vec<u8> {
1541 let mut out = Vec::new();
1542 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
1543 for ((kind, _), name) in lanes.iter().zip(names) {
1544 let (keyword, ord) = match kind {
1545 LaneKind::Video => {
1546 video += 1;
1547 ("video", video)
1548 }
1549 LaneKind::Audio => {
1550 audio += 1;
1551 ("audio", audio)
1552 }
1553 LaneKind::Subtitle => {
1554 sub += 1;
1555 ("sub", sub)
1556 }
1557 };
1558 if !name.is_empty() {
1559 out.extend_from_slice(format!("lanename {keyword} {ord} ").as_bytes());
1560 escape_text(name, &mut out);
1561 out.push(b'\n');
1562 }
1563 }
1564 out
1565}
1566
1567/// `stab video <ord> <index> <strength> <crop>`: one per stabilised clip, and such a
1568/// project is a v44 one.
1569fn stab_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1570 video_key_lines(lanes, "stab", |c| {
1571 c.stabilise.map_or(String::new(), |st| format!(" {} {}", st.amount(), st.crop().name()))
1572 })
1573}
1574
1575/// The `mark` lines: one per clip that has a colour label or is switched off, as `mark <kind>
1576/// <ord> <index> <label> <on|off>` with the label 0 to 8. Only such a clip gets a line, and such a
1577/// project is a v48 one.
1578fn mark_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1579 let mut out = Vec::new();
1580 let (mut video, mut audio) = (0u32, 0u32);
1581 for (kind, clips) in lanes {
1582 let (keyword, ord) = match kind {
1583 LaneKind::Video => {
1584 video += 1;
1585 ("video", video)
1586 }
1587 LaneKind::Audio => {
1588 audio += 1;
1589 ("audio", audio)
1590 }
1591 LaneKind::Subtitle => continue,
1592 };
1593 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.mark.is_default()) {
1594 let state = if c.mark.off { "off" } else { "on" };
1595 out.extend_from_slice(format!("mark {keyword} {ord} {idx} {} {state}\n", c.mark.label).as_bytes());
1596 }
1597 }
1598 out
1599}
1600
1601/// The `angle` lines: one per clip that shows another angle than the first, as `angle <kind> <ord>
1602/// <index> <picture> <sound>` with angles counted from 1 and `-` for a sound that follows the
1603/// picture. Only such a clip gets a line, and such a project is a v47 one.
1604fn angle_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1605 let mut out = Vec::new();
1606 let (mut video, mut audio) = (0u32, 0u32);
1607 for (kind, clips) in lanes {
1608 let (keyword, ord) = match kind {
1609 LaneKind::Video => {
1610 video += 1;
1611 ("video", video)
1612 }
1613 LaneKind::Audio => {
1614 audio += 1;
1615 ("audio", audio)
1616 }
1617 LaneKind::Subtitle => continue,
1618 };
1619 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.angle.is_default()) {
1620 let sound = c.angle.audio.map_or("-".to_string(), |a| (u32::from(a) + 1).to_string());
1621 out.extend_from_slice(format!("angle {keyword} {ord} {idx} {} {sound}\n", u32::from(c.angle.video) + 1).as_bytes());
1622 }
1623 }
1624 out
1625}
1626
1627/// `okeys video <ord> <index> <at>:<ease>:<opacity> ...`, the opacity keys in
1628/// source order. Only a clip with keys gets a line, and such a project is a v39 one.
1629fn opacity_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1630 video_key_lines(lanes, "okeys", |c| {
1631 c.opacity_keys
1632 .iter()
1633 .map(|k| format!(" {}:{}:{}", k.at, k.ease.token(), k.opacity))
1634 .collect()
1635 })
1636}
1637
1638/// `ckeys video <ord> <index> <at>:<ease>:<brightness>,<contrast>,<saturation>,<tint> ...`,
1639/// the colour keys in source order. Only a clip with keys gets a line, and such
1640/// a project is a v39 one.
1641fn color_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1642 video_key_lines(lanes, "ckeys", |c| {
1643 c.color_keys
1644 .iter()
1645 .map(|k| {
1646 let p = &k.params;
1647 format!(
1648 " {}:{}:{},{},{},{}",
1649 k.at,
1650 k.ease.token(),
1651 p.brightness,
1652 p.contrast,
1653 p.saturation,
1654 p.tint
1655 )
1656 })
1657 .collect()
1658 })
1659}
1660
1661/// The `effect` lines (v42): `effect video <ord> <index> <kind> <on> <value>...`, one per
1662/// effect of a clip's stack, in stack order. Only a clip with effects gets any.
1663fn effect_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1664 let mut out = String::new();
1665 let mut video = 0u32;
1666 for (kind, clips) in lanes {
1667 if *kind != LaneKind::Video {
1668 continue;
1669 }
1670 video += 1;
1671 for (idx, c) in clips.iter().enumerate() {
1672 for e in &c.effects {
1673 out += &format!("effect video {video} {idx} {} {}", e.kind.name(), u8::from(e.on));
1674 for v in &e.values[..e.kind.params().len()] {
1675 out += &format!(" {v}");
1676 }
1677 out.push('\n');
1678 }
1679 }
1680 }
1681 out.into_bytes()
1682}
1683
1684/// The `ekeys` lines (v56): `ekeys video <ord> <index> <slot> <at>:<ease>:<v0>,<v1>,... ...`,
1685/// the keys of the effect at stack position `slot`, in source order, with one value for each
1686/// of its [`crate::effects::EffectKind::params`]. Only an effect with keys gets a line.
1687fn effect_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1688 let mut out = String::new();
1689 let mut video = 0u32;
1690 for (kind, clips) in lanes {
1691 if *kind != LaneKind::Video {
1692 continue;
1693 }
1694 video += 1;
1695 for (idx, c) in clips.iter().enumerate() {
1696 for (slot, e) in c.effects.iter().enumerate() {
1697 if e.keys.is_empty() {
1698 continue;
1699 }
1700 out += &format!("ekeys video {video} {idx} {slot}");
1701 let count = e.kind.params().len();
1702 for k in &e.keys {
1703 let values: Vec<String> = k.values[..count].iter().map(|v| v.to_string()).collect();
1704 out += &format!(" {}:{}:{}", k.at, k.ease.token(), values.join(","));
1705 }
1706 out.push('\n');
1707 }
1708 }
1709 }
1710 out.into_bytes()
1711}
1712
1713/// The v43 look lines, one group per colour line that has one, named by the
1714/// colour line's position:
1715///
1716/// * `wheels <color> <lift> <gamma> <gain>`, each `<master>:<red>:<green>:<blue>`,
1717/// * `curve <color> <channel> <x>:<y>,<x>:<y>...`, one per channel (`master`,
1718/// `red`, `green`, `blue`) that holds points,
1719/// * `lut <color> <mix> <path>`, the path written as a source's is (relative
1720/// when inside the project's folder) and running to the end of the line.
1721fn look_lines(color: &[ColorParams], dir: &Path) -> Vec<u8> {
1722 let quad = |q: &[f32; 4]| format!("{:?}:{:?}:{:?}:{:?}", q[0], q[1], q[2], q[3]);
1723 let mut out = Vec::new();
1724 for (i, p) in color.iter().enumerate() {
1725 let look = &p.look;
1726 if look.wheels != crate::color::Wheels::default() {
1727 let w = &look.wheels;
1728 out.extend_from_slice(
1729 format!("wheels {i} {} {} {}\n", quad(&w.lift), quad(&w.gamma), quad(&w.gain)).as_bytes(),
1730 );
1731 }
1732 for (c, curve) in look.curves.iter().enumerate() {
1733 if curve.points().is_empty() {
1734 continue;
1735 }
1736 let pts: Vec<String> = curve.points().iter().map(|q| format!("{:?}:{:?}", q[0], q[1])).collect();
1737 out.extend_from_slice(
1738 format!("curve {i} {} {}\n", crate::color::CHANNELS[c], pts.join(",")).as_bytes(),
1739 );
1740 }
1741 if let Some(lut) = look.lut {
1742 out.extend_from_slice(format!("lut {i} {:?} ", look.lut_mix).as_bytes());
1743 escape(&written_path(&lut.path(), dir), &mut out);
1744 out.push(b'\n');
1745 }
1746 }
1747 out
1748}
1749
1750/// A `wheels`, `curve` or `lut` line (v43): see [`look_lines`]. A LUT file that is
1751/// missing or broken still loads -- the clip plays without it and
1752/// [`crate::Project::lut_problems`] names it -- but a malformed line is refused.
1753fn parse_look(head: &[u8], rest: &[u8], n: usize, dir: &Path, doc: &mut Document) -> crate::Result<()> {
1754 let sp = rest.iter().position(|&b| b == b' ').unwrap_or(rest.len());
1755 let at = number(&rest[..sp], n)? as usize;
1756 let rest = rest.get(sp + 1..).unwrap_or(&[]);
1757 let what = String::from_utf8_lossy(head).into_owned();
1758 if at >= doc.color.len() {
1759 return Err(format!("line {n}: {what} names color {at}, and there are {}", doc.color.len()).into());
1760 }
1761 let look = &mut doc.color[at].look;
1762 match head {
1763 b"wheels" => {
1764 let f = fields(rest, 3, "wheels", n)?;
1765 let mut q = [[0f32; 4]; 3];
1766 for (k, field) in f.iter().enumerate() {
1767 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
1768 if parts.len() != 4 {
1769 return Err(format!("line {n}: a wheel wants 4 values").into());
1770 }
1771 for (c, part) in parts.iter().enumerate() {
1772 let v = float(part, n)?;
1773 if !(-1.0..=1.0).contains(&v) {
1774 return Err(format!("line {n}: wheels has a value outside -1..1").into());
1775 }
1776 q[k][c] = v;
1777 }
1778 }
1779 look.wheels = crate::color::Wheels { lift: q[0], gamma: q[1], gain: q[2] };
1780 }
1781 b"curve" => {
1782 let f = fields(rest, 2, "curve", n)?;
1783 let channel = crate::color::CHANNELS
1784 .iter()
1785 .position(|c| c.as_bytes() == f[0])
1786 .ok_or_else(|| format!("line {n}: curve channel {:?} is not master, red, green or blue", String::from_utf8_lossy(f[0])))?;
1787 let mut pts = Vec::new();
1788 for pair in f[1].split(|&b| b == b',') {
1789 let xy: Vec<&[u8]> = pair.split(|&b| b == b':').collect();
1790 if xy.len() != 2 {
1791 return Err(format!("line {n}: a curve point is <x>:<y>").into());
1792 }
1793 pts.push([float(xy[0], n)?, float(xy[1], n)?]);
1794 }
1795 look.curves[channel] = crate::color::Curve::new(&pts).map_err(|e| format!("line {n}: {e}"))?;
1796 }
1797 _ => {
1798 let sp = rest.iter().position(|&b| b == b' ').ok_or_else(|| format!("line {n}: lut wants <mix> <path>"))?;
1799 let mix = float(&rest[..sp], n)?;
1800 if !(0.0..=1.0).contains(&mix) {
1801 return Err(format!("line {n}: lut mix must be 0..=1").into());
1802 }
1803 let path = unescape(&rest[sp + 1..], n)?;
1804 if path.as_os_str().is_empty() {
1805 return Err(format!("line {n}: lut without a path").into());
1806 }
1807 let path = if path.is_absolute() { path } else { dir.join(path) };
1808 look.lut = Some(crate::cube::LutRef::open(&path));
1809 look.lut_mix = mix;
1810 }
1811 }
1812 Ok(())
1813}
1814
1815/// `tkeys <kind> <ord> <index> <at>:<ease>:<pos_x>,<pos_y>,<scale>,<rotate>,<crop_l>,<crop_r>,<crop_t>,<crop_b>,<opacity> ...`,
1816/// the keys in source order. `ease` is `lin` or `ease`. Floats are written the
1817/// way the `transform` table writes them, `{}`, which reads back exactly. Only a
1818/// clip with keys gets a line, and such a project is a v32 one.
1819fn tkey_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1820 let mut out = Vec::new();
1821 let (mut video, mut audio) = (0u32, 0u32);
1822 for (kind, clips) in lanes {
1823 let (keyword, ord) = match kind {
1824 LaneKind::Video => {
1825 video += 1;
1826 ("video", video)
1827 }
1828 LaneKind::Audio => {
1829 audio += 1;
1830 ("audio", audio)
1831 }
1832 LaneKind::Subtitle => continue,
1833 };
1834 for (idx, c) in clips.iter().enumerate() {
1835 if c.transform_keys.is_empty() {
1836 continue;
1837 }
1838 let points: String = c
1839 .transform_keys
1840 .iter()
1841 .map(|k| {
1842 let p = &k.params;
1843 let ease = k.ease.token();
1844 format!(
1845 " {}:{ease}:{},{},{},{},{},{},{},{},{}",
1846 k.at,
1847 p.pos_x,
1848 p.pos_y,
1849 p.scale,
1850 p.rotate,
1851 p.crop_l,
1852 p.crop_r,
1853 p.crop_t,
1854 p.crop_b,
1855 p.opacity
1856 )
1857 })
1858 .collect();
1859 out.extend_from_slice(format!("tkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1860 }
1861 }
1862 out
1863}
1864
1865/// The `chapter` lines: one per chapter, in frame order, as [`save_flagged`]
1866/// writes them after the titles. A project with none writes nothing.
1867fn chapter_lines(chapters: &[Chapter]) -> Vec<u8> {
1868 let mut out = Vec::new();
1869 for c in chapters {
1870 out.extend_from_slice(format!("chapter {} ", c.frame).as_bytes());
1871 escape_text(&c.title, &mut out);
1872 out.push(b'\n');
1873 }
1874 out
1875}
1876
1877/// The `marker` lines, one per marker in frame order, then a `marknote` line for each one
1878/// that has a note, as [`save_flagged`] writes them after the chapters. None for a project with none.
1879/// The `capstyle` line, `capstyle <animation> <rrggbb> <box 0|1> <uppercase 0|1> <words per
1880/// line>`: how burned captions animate. None for the default style, so a project that never
1881/// touched it is the bytes it was before v40, bar the version line.
1882fn capstyle_line(cs: &CaptionStyle) -> Vec<u8> {
1883 if *cs == CaptionStyle::default() {
1884 return Vec::new();
1885 }
1886 let [r, g, b] = cs.highlight;
1887 format!(
1888 "capstyle {} {r:02x}{g:02x}{b:02x} {} {} {}\n",
1889 cs.anim.name(),
1890 u8::from(cs.hl_box),
1891 u8::from(cs.uppercase),
1892 cs.words_per_line
1893 )
1894 .into_bytes()
1895}
1896
1897fn marker_lines(markers: &[Marker]) -> Vec<u8> {
1898 let mut out = Vec::new();
1899 for m in markers {
1900 out.extend_from_slice(format!("marker {} {} {} ", m.frame, m.length, m.color.name()).as_bytes());
1901 escape_text(&m.name, &mut out);
1902 out.push(b'\n');
1903 }
1904 for (i, m) in markers.iter().enumerate().filter(|(_, m)| !m.note.is_empty()) {
1905 out.extend_from_slice(format!("marknote {i} ").as_bytes());
1906 escape_text(&m.note, &mut out);
1907 out.push(b'\n');
1908 }
1909 out
1910}
1911
1912/// The `title` lines: one per title, in list order, as [`save_flagged`] writes
1913/// them. A project with none is the bytes a v25 one was bar the version line.
1914fn title_lines(titles: &[Title]) -> Vec<u8> {
1915 let mut out = Vec::new();
1916 for t in titles {
1917 let outline = match t.style.outline {
1918 Outline::None => "none",
1919 Outline::Thin => "thin",
1920 Outline::Thick => "thick",
1921 };
1922 let place = match t.style.place {
1923 Place::Bottom => "bottom",
1924 Place::Top => "top",
1925 Place::Centre => "centre",
1926 };
1927 out.extend_from_slice(
1928 format!(
1929 "title {} {} {} {} {} {outline} {} {place} ",
1930 t.start,
1931 t.frames,
1932 t.fade_in,
1933 t.fade_out,
1934 t.style.size,
1935 u8::from(t.style.boxed)
1936 )
1937 .as_bytes(),
1938 );
1939 escape_text(&t.text, &mut out);
1940 out.push(b'\n');
1941 }
1942 // A title's colour, weight, alignment, position and box colour, one line per title that has
1943 // any of them off the default, so a project without them is the bytes it was.
1944 for (i, t) in titles.iter().enumerate() {
1945 let st = &t.style;
1946 if title_look_is_default(st) {
1947 continue;
1948 }
1949 let hplace = match st.hplace {
1950 HPlace::Centre => "centre",
1951 HPlace::Left => "left",
1952 HPlace::Right => "right",
1953 };
1954 let align = match st.align {
1955 Align::Centre => "centre",
1956 Align::Left => "left",
1957 Align::Right => "right",
1958 };
1959 let weight = match st.weight {
1960 Weight::Regular => "regular",
1961 Weight::Bold => "bold",
1962 };
1963 let [r, g, b] = st.ink;
1964 let [br, bg, bb, ba] = st.box_color;
1965 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());
1966 }
1967 // A title's entrance and exit, one line per title that has either.
1968 for (i, t) in titles.iter().enumerate() {
1969 if t.in_anim == TitleAnim::None && t.out_anim == TitleAnim::None {
1970 continue;
1971 }
1972 out.extend_from_slice(format!("titleanim {i} {} {} {}\n", t.in_anim.name(), t.out_anim.name(), t.anim_frames).as_bytes());
1973 }
1974 // A title's own keys, one line per title that has any, after its `titleanim` line.
1975 for (i, t) in titles.iter().enumerate() {
1976 if t.keys.is_empty() {
1977 continue;
1978 }
1979 out.extend_from_slice(format!("ttkeys {i}").as_bytes());
1980 for k in &t.keys {
1981 out.extend_from_slice(format!(" {}:{}:{},{},{},{}", k.at, k.ease.token(), k.x, k.y, k.scale, k.opacity).as_bytes());
1982 }
1983 out.push(b'\n');
1984 }
1985 out
1986}
1987
1988/// Whether a style has none of the v49 title looks: white, regular, centred, on the black box.
1989fn title_look_is_default(st: &TextStyle) -> bool {
1990 let d = TextStyle::default();
1991 st.hplace == d.hplace && st.align == d.align && st.weight == d.weight && st.ink == d.ink && st.box_color == d.box_color
1992}
1993
1994/// The `flags` lines: one per lane that has a switch set, in lane order. Only a
1995/// lane somebody has switched gets one, so a project with none is the bytes a
1996/// v23 one was bar the version line.
1997fn flag_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1998 let mut out = Vec::new();
1999 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
2000 for ((kind, _), f) in lanes.iter().zip(flags) {
2001 let (keyword, ord) = match kind {
2002 LaneKind::Video => {
2003 video += 1;
2004 ("video", video)
2005 }
2006 LaneKind::Audio => {
2007 audio += 1;
2008 ("audio", audio)
2009 }
2010 LaneKind::Subtitle => {
2011 sub += 1;
2012 ("sub", sub)
2013 }
2014 };
2015 let words: Vec<&str> = [
2016 (f.hidden, "hidden"),
2017 (f.muted, "muted"),
2018 (f.locked, "locked"),
2019 ]
2020 .into_iter()
2021 .filter_map(|(on, word)| on.then_some(word))
2022 .collect();
2023 if !words.is_empty() {
2024 out.extend_from_slice(
2025 format!("flags {keyword} {ord} {}\n", words.join(" ")).as_bytes(),
2026 );
2027 }
2028 }
2029 out
2030}
2031
2032#[allow(clippy::too_many_arguments)]
2033fn emit(
2034 dir: &Path,
2035 sources: &[Source],
2036 lanes: &[(LaneKind, Vec<Clip>)],
2037 gains: &[f32],
2038 subs: &[Vec<SubClip>],
2039 subtitles: &[SubtitleTrack],
2040 eq: &[EqParams],
2041 color: &[ColorParams],
2042 transform: &[TransformParams],
2043 resolution: (u32, u32),
2044 fps: Option<f64>,
2045 tone: crate::tonemap::Preset,
2046 proxy: bool,
2047 auto_proxy: bool,
2048 encoder: crate::export::EncoderSeat,
2049 limiter: Limiter,
2050 sample_rate: Option<u32>,
2051 playhead: u32,
2052) -> Vec<u8> {
2053 let mut out = Vec::new();
2054 // The file says which dialect it is by whether it needs the newest one:
2055 // a transform's opacity is the only thing v31 adds, so a project without
2056 // one is the bytes a v30 project always was, bar none, and an older reader
2057 // still opens it.
2058 // The newest dialect is only for a project that has placement keys
2059 // (`tkeys` lines, [`tkeys_lines`]); one with opacity alone is still v31.
2060 let needs_v33 = subtitles.iter().any(|t| !t.language.is_empty());
2061 let needs_v32 = lanes
2062 .iter()
2063 .any(|(_, clips)| clips.iter().any(|c| !c.transform_keys.is_empty()));
2064 let needs_v31 = transform.iter().any(|p| p.opacity != 1.0);
2065 out.extend_from_slice(if needs_v33 {
2066 MAGIC_V33
2067 } else if needs_v32 {
2068 MAGIC_V32
2069 } else if needs_v31 {
2070 MAGIC_V31
2071 } else {
2072 MAGIC_V30
2073 });
2074 out.push(b'\n');
2075 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
2076 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
2077 // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read
2078 // back as the very number, or every clip on it lands on another frame.
2079 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
2080 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
2081 }
2082 // Beside it, and by the same rule: a project nobody chose a sound rate for
2083 // is the mix the source's own probe always gave it, which is what leaving
2084 // this line out still means.
2085 if let Some(rate) = sample_rate.filter(|&r| (1_000..=384_000).contains(&r)) {
2086 out.extend_from_slice(format!("samplerate {rate}\n").as_bytes());
2087 }
2088 // Beside the rate, and written only when it is not the default: a project
2089 // holding no HDR media has nothing to say here, and saying nothing is what
2090 // a v10 file already said.
2091 if tone != crate::tonemap::Preset::default() {
2092 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
2093 }
2094 // Beside it and by the same rule: a project cut on the films themselves --
2095 // every project before there were stand-ins -- says nothing here.
2096 if proxy {
2097 out.extend_from_slice(b"proxy on\n");
2098 }
2099 // Beside it and by the same rule the other way up: making them by itself is
2100 // what every project before this line did, so only a project told to stop
2101 // has anything to say here.
2102 if !auto_proxy {
2103 out.extend_from_slice(b"autoproxy off\n");
2104 }
2105 // ...and which encoder writes the picture, by the same rule again: `auto`
2106 // is what every project before this line did, so only a project whose owner
2107 // picked a seat says anything here.
2108 if encoder != crate::export::EncoderSeat::default() {
2109 out.extend_from_slice(format!("encoder {}\n", encoder.name()).as_bytes());
2110 }
2111 // Written only when it is not the default, so a project nobody has limited
2112 // is the same bytes it was in v8 bar the version line.
2113 if limiter != Limiter::default() {
2114 out.extend_from_slice(
2115 format!(
2116 "limiter {:?} {}\n",
2117 limiter.ceiling_db,
2118 match limiter.on {
2119 true => "on",
2120 false => "off",
2121 }
2122 )
2123 .as_bytes(),
2124 );
2125 }
2126 for s in sources {
2127 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
2128 escape(&written_path(&s.path, dir), &mut out);
2129 out.push(b'\n');
2130 }
2131 // The subtitle tracks, by reference: which track of which file, and never
2132 // the cues (see the module docs). Beside the sources because that is what
2133 // they are -- a file this project reads from -- although nothing indexes
2134 // them and their order is only the order they were added in.
2135 for t in subtitles {
2136 let track = t.track.map_or("-".to_string(), |n| n.to_string());
2137 out.extend_from_slice(format!("subtitle {track} ").as_bytes());
2138 escape(&written_path(&t.path, dir), &mut out);
2139 out.push(b'\n');
2140 }
2141 // The language of each track that has one, as `sublang` lines after the
2142 // subtitle lines they name: a standalone file's is set by an import or a
2143 // retype, and an embedded track's is its container's until a retype
2144 // replaces it. Only a track with one is written, and the header only says
2145 // v33 when one is, so a project with none is written exactly as before.
2146 for (track, t) in subtitles.iter().enumerate() {
2147 if t.language.is_empty() {
2148 continue;
2149 }
2150 out.extend_from_slice(format!("sublang {track} ").as_bytes());
2151 escape_text(&t.language, &mut out);
2152 out.push(b'\n');
2153 }
2154 // Before the clips, for the reason the sources are: a clip names one by the
2155 // position of its line, so the line has to be there first.
2156 for params in eq {
2157 out.extend_from_slice(b"eq");
2158 for b in &params.bands {
2159 // `{:?}` rather than `{}`: it is the formatting that promises the
2160 // shortest string parsing back to this exact f32, and it never
2161 // prints a bare integer, which would read as another field's shape.
2162 let kind = match b.kind {
2163 BandKind::LowShelf => "ls",
2164 BandKind::Peak => "pk",
2165 BandKind::HighShelf => "hs",
2166 BandKind::LowCut => "lc",
2167 BandKind::HighCut => "hc",
2168 };
2169 out.extend_from_slice(
2170 format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
2171 );
2172 }
2173 out.push(b'\n');
2174 }
2175 // ...and the colour table, for the same reason and by the same rules.
2176 for p in color {
2177 out.extend_from_slice(
2178 format!(
2179 "color {:?}:{:?}:{:?}:{:?}\n",
2180 p.brightness, p.contrast, p.saturation, p.tint
2181 )
2182 .as_bytes(),
2183 );
2184 }
2185 // ...and the transform table, for the same reason and by the same rules.
2186 for p in transform {
2187 let mut line = format!(
2188 "transform {:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}",
2189 p.pos_x, p.pos_y, p.scale, p.rotate, p.crop_l, p.crop_r, p.crop_t, p.crop_b
2190 );
2191 // The ninth field only where it says something: an opacity of 1 is the
2192 // eight-field line every dialect since v20 wrote.
2193 if p.opacity != 1.0 {
2194 line.push_str(&format!(":{:?}", p.opacity));
2195 }
2196 line.push('\n');
2197 out.extend_from_slice(line.as_bytes());
2198 }
2199 // Lane by lane rather than interleaved by time: a lane reads as a list, the
2200 // parser gets its sortedness check for free from the order it is in, and
2201 // the lanes come back out in the order they are displayed in.
2202 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
2203 for (at, (kind, clips)) in lanes.iter().enumerate() {
2204 let (keyword, ord) = match kind {
2205 LaneKind::Video => {
2206 video += 1;
2207 ("video", video)
2208 }
2209 LaneKind::Audio => {
2210 audio += 1;
2211 ("audio", audio)
2212 }
2213 LaneKind::Subtitle => {
2214 subtitle += 1;
2215 ("sub", subtitle)
2216 }
2217 };
2218 // A subtitle lane holds no `Clip` at all ([`LaneKind::Subtitle`]): what
2219 // is on it is in `subs`, one list per lane and in step with this one,
2220 // and it is written here so the lane comes back in its place among the
2221 // others.
2222 if *kind == LaneKind::Subtitle {
2223 let placed = subs.get(at).map_or(&[][..], Vec::as_slice);
2224 if placed.is_empty() {
2225 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2226 }
2227 for s in placed {
2228 // The group field only when the caption is in one, for the
2229 // clip line's reason: a project nobody grouped a caption in is
2230 // the same bytes it was in v15.
2231 let link = s.link.map_or(String::new(), |l| format!(" {l}"));
2232 out.extend_from_slice(
2233 format!(
2234 "{keyword} {ord} {} {} {} {} {}{link}\n",
2235 s.start, s.frames, s.track, s.in_us, s.out_us
2236 )
2237 .as_bytes(),
2238 );
2239 }
2240 continue;
2241 }
2242 // A lane is declared by its clips; one holding nothing has to say so on
2243 // a line of its own, or the lane itself would not survive the round trip.
2244 if clips.is_empty() {
2245 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2246 }
2247 for c in clips {
2248 let link = c.link.map_or("-".to_string(), |l| l.to_string());
2249 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
2250 let color = c.color.map_or("-".to_string(), |e| e.to_string());
2251 let transform = c.transform.map_or("-".to_string(), |e| e.to_string());
2252 out.extend_from_slice(
2253 format!(
2254 "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {} {} {transform} {} {}\n",
2255 c.start,
2256 c.in_frame,
2257 c.out_frame,
2258 c.source,
2259 fit_name(c.fit),
2260 c.speed.permille(),
2261 c.fade_in,
2262 c.fade_out,
2263 c.transition_out,
2264 c.visualizer,
2265 c.viz_paint,
2266 )
2267 .as_bytes(),
2268 );
2269 }
2270 }
2271 // After the lanes, not before them: a gain line names a lane that has to be
2272 // there already, and a lane is declared by its own lines. Only the lanes
2273 // somebody has turned get one.
2274 let (mut video, mut audio) = (0, 0);
2275 for ((kind, _), &db) in lanes.iter().zip(gains) {
2276 let (keyword, ord) = match kind {
2277 LaneKind::Video => {
2278 video += 1;
2279 ("video", video)
2280 }
2281 LaneKind::Audio => {
2282 audio += 1;
2283 ("audio", audio)
2284 }
2285 // In the list -- the two are zipped, so it has to be -- and never
2286 // written: a subtitle lane has no volume at all
2287 // (`Project::set_lane_gain_db` refuses one), so its entry is the
2288 // `0.0` no lane writes a line for.
2289 LaneKind::Subtitle => continue,
2290 };
2291 if db != 0.0 {
2292 out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes());
2293 }
2294 }
2295 out
2296}
2297
2298fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
2299 // One trailing newline is the line terminator of the last line, not an
2300 // empty line -- any further one is, and is refused below.
2301 let body = data.strip_suffix(b"\n").unwrap_or(data);
2302 let mut lines = body.split(|&b| b == b'\n').enumerate();
2303 let (_, first) = lines.next().unwrap_or((0, &[]));
2304 let v1 = first == MAGIC_V1;
2305 // The dialects that wrote a source line without its stream field. Reading
2306 // one is the whole of what "an old project still opens" means here.
2307 let streamless = v1 || first == MAGIC_V2;
2308 // The one that carries a clip's volume envelope, as `gainkeys` lines...
2309 // The one that lets a lane be ducked under several keys, as several `duck`
2310 // lines naming one lane; a v29 reader refuses it by name.
2311 // The one that carries a transform's opacity, as a ninth field on a
2312 // `transform` line; a v30 reader refuses it by its field count.
2313 // The one that carries a clip's placement animation, as `tkeys` lines...
2314 // The one that carries a clip's stabilisation, as `stab` lines...
2315 // The one that carries a clip's pitch shift, as `pitch` lines...
2316 let v57 = first == MAGIC;
2317 let v56 = v57 || first == MAGIC_V56;
2318 let v55 = v56 || first == MAGIC_V55;
2319 let v54 = v55 || first == MAGIC_V54;
2320 let v53 = v54 || first == MAGIC_V53;
2321 let v52 = v53 || first == MAGIC_V52;
2322 let v51 = v52 || first == MAGIC_V51;
2323 let v50 = v51 || first == MAGIC_V50;
2324 let v49 = v50 || first == MAGIC_V49;
2325 let v48 = v49 || first == MAGIC_V48;
2326 let v47 = v48 || first == MAGIC_V47;
2327 let v46 = v47 || first == MAGIC_V46;
2328 let v45 = v46 || first == MAGIC_V45;
2329 let v44 = v45 || first == MAGIC_V44;
2330 let v43 = v44 || first == MAGIC_V43;
2331 let v42 = v43 || first == MAGIC_V42;
2332 let v41 = v42 || first == MAGIC_V41;
2333 let v40 = v41 || first == MAGIC_V40;
2334 let v39 = v40 || first == MAGIC_V39;
2335 let v38 = v39 || first == MAGIC_V38;
2336 let v37 = v38 || first == MAGIC_V37;
2337 let v36 = v37 || first == MAGIC_V36;
2338 let v35 = v36 || first == MAGIC_V35;
2339 let v34 = v35 || first == MAGIC_V34;
2340 let v33 = v34 || first == MAGIC_V33;
2341 let v32 = v33 || first == MAGIC_V32;
2342 let v31 = v32 || first == MAGIC_V31;
2343 let v30 = v31 || first == MAGIC_V30;
2344 let v29 = v30 || first == MAGIC_V29;
2345 let v28 = v29 || first == MAGIC_V28;
2346 // The one that carries a clip's own gain in dB, as `clipgain` lines...
2347 let v27 = v28 || first == MAGIC_V27;
2348 // The one that carries the title cards and text overlays...
2349 let v26 = v27 || first == MAGIC_V26;
2350 // The one that says which lanes are ducked under which...
2351 let v25 = v26 || first == MAGIC_V25;
2352 // The one that says which lanes are hidden, muted or locked...
2353 let v24 = v25 || first == MAGIC_V24;
2354 // The one that carries a strand colour of its own above the packed
2355 // visualizer paint (hue/sat, with the top bit as the flag)...
2356 let v23 = v24 || first == MAGIC_V23;
2357 // The one that carries packed visualizer paint (hue/sat/strands/glow)...
2358 let v22 = v23 || first == MAGIC_V22;
2359 // The one that carries per-clip visualizer flags...
2360 let v21 = v22 || first == MAGIC_V21;
2361 // The one that carries a per-clip transform (position/scale/rotate/crop)...
2362 let v20 = v21 || first == MAGIC_V20;
2363 // ...the one that carries a per-clip cross-dissolve into its successor...
2364 let v19 = v20 || first == MAGIC_V19;
2365 // ...the one that carries a per-clip fade envelope...
2366 let v18 = v19 || first == MAGIC_V18;
2367 // ...the one that carries an explicit sound rate...
2368 let v17 = v18 || first == MAGIC_V17;
2369 // ...the one whose captions may carry a group id...
2370 let v16 = v17 || first == MAGIC_V16;
2371 // ...the one that places the words it names...
2372 let v15 = v16 || first == MAGIC_V15;
2373 // ...the ones that say which encoder an export takes...
2374 let v14 = v15 || first == MAGIC_V14;
2375 // ...the ones that say whether the stand-ins are made by themselves...
2376 let v13 = v14 || first == MAGIC_V13;
2377 // ...the ones that say whether it is cut on stand-ins...
2378 let v12 = v13 || first == MAGIC_V12;
2379 // ...the ones that carry an HDR rendition...
2380 let v11 = v12 || first == MAGIC_V11;
2381 // ...the ones that carry subtitle tracks...
2382 let v10 = v11 || first == MAGIC_V10;
2383 // ...the ones that carry the mix -- lane volumes, the master limiter and
2384 // the rate the timeline was cut at...
2385 let v9 = v10 || first == MAGIC_V9;
2386 // ...the ones that carry a per-clip speed...
2387 let v8 = v9 || first == MAGIC_V8;
2388 // ...the ones that carry a project resolution and per-clip fit policies...
2389 let v7 = v8 || first == MAGIC_V7;
2390 // ...the ones that carry colour grades...
2391 let v6 = v7 || first == MAGIC_V6;
2392 // ...the ones that carry equalizer settings...
2393 let v5 = v6 || first == MAGIC_V5;
2394 // ...and the ones that number their lanes. Every older one held two.
2395 let numbered = v5 || first == MAGIC_V4;
2396 if !numbered && !streamless && first != MAGIC_V3 {
2397 return Err(match first.strip_prefix(b"edith ") {
2398 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
2399 None => "line 1: not an edith file".to_string(),
2400 }
2401 .into());
2402 }
2403
2404 let mut doc = Document {
2405 sources: Vec::new(),
2406 // v4 on declares its lanes as they come; every dialect before it held
2407 // exactly `V1` and `A1`, either of which could be empty.
2408 lanes: if numbered {
2409 Vec::new()
2410 } else {
2411 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
2412 },
2413 // Resized to the lanes as they arrive, and once more at the end, so a
2414 // caller may zip the two exactly as it zips the gains. Nothing before
2415 // v15 places a word anywhere: those projects have the palette and no
2416 // subtitle lane to put any of it on.
2417 subs: Vec::new(),
2418 // Nothing before v5 equalizes anything, and nothing before v6 grades.
2419 eq: Vec::new(),
2420 color: Vec::new(),
2421 // Nothing before v20 places any clip anywhere but its fit policy's own
2422 // spot: the identity transform is what leaving a clip's index out
2423 // still means.
2424 transform: Vec::new(),
2425 // Nothing before v7 has a resolution of its own: source 0's picture is
2426 // what those projects were, and `None` is how the loader is told so.
2427 resolution: None,
2428 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
2429 // no limiter, and the rate inferred from the scaffold as it always was.
2430 gains: Vec::new(),
2431 // Nothing before v24 could hide, mute or lock a lane: every lane is
2432 // showing, audible and unlocked, which is what leaving a line out means.
2433 flags: Vec::new(),
2434 // Nothing before v25 ducks a lane under another: every lane plays at
2435 // its own level, which is what leaving a line out means.
2436 ducks: Vec::new(),
2437 titles: Vec::new(),
2438 chapters: Vec::new(),
2439 markers: Vec::new(),
2440 caption_style: CaptionStyle::default(),
2441 voices: Vec::new(),
2442 names: Vec::new(),
2443 // Nothing before v10 shows a subtitle, and nothing before v11 was shown
2444 // in any rendition but the published one.
2445 subtitles: Vec::new(),
2446 sub_langs: Vec::new(),
2447 cue_edits: Vec::new(),
2448 cue_adds: Vec::new(),
2449 cue_words: Vec::new(),
2450 limiter: Limiter::default(),
2451 tone: crate::tonemap::Preset::default(),
2452 proxy: false,
2453 // ...and nothing before v13 could be told *not* to make one: an import
2454 // that wanted a stand-in got one, which is what leaving the line out
2455 // still means.
2456 auto_proxy: true,
2457 // ...and nothing before v14 could be told *which* encoder: an export
2458 // took the seat this machine had, which is what leaving the line out
2459 // still means.
2460 encoder: crate::export::EncoderSeat::default(),
2461 fps: None,
2462 // Nothing before v17 chose a sound rate: the source's own probe is
2463 // still what the mix is cut at, which is what `None` means everywhere
2464 // else it reaches (`PlaybackSession::open_project`).
2465 sample_rate: None,
2466 playhead: 0,
2467 seq_active: None,
2468 seq_order: Vec::new(),
2469 sequences: Vec::new(),
2470 mcams: Vec::new(),
2471 bins: Vec::new(),
2472 notes: String::new(),
2473 still_secs: None,
2474 speech_model: None,
2475 speech_device: crate::speech::DeviceChoice::Auto,
2476 };
2477 // The block of a parked sequence being read: its id, name and the lines so far.
2478 let mut block: Option<(u32, String, Vec<u8>)> = None;
2479 let mut playhead_seen = false;
2480 // Where the next v1 clip is placed: that dialect had no `start` field, the
2481 // clips simply queued up.
2482 let mut queued = 0u32;
2483 for (i, line) in lines {
2484 let n = i + 1;
2485 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
2486 Some(at) => (&line[..at], &line[at + 1..]),
2487 None => (line, &line[line.len()..]),
2488 };
2489 if let Some((id, name, buf)) = block.as_mut() {
2490 if line == b"endseq" {
2491 if doc.sequences.len() >= MAX_SEQUENCES {
2492 return Err(format!("line {n}: a project holds at most {MAX_SEQUENCES} sequences").into());
2493 }
2494 let sub = parse(buf, dir).map_err(|e| format!("sequence \"{name}\": {e}"))?;
2495 doc.sequences.push(SeqDoc { id: *id, name: std::mem::take(name), doc: sub });
2496 block = None;
2497 } else {
2498 buf.extend_from_slice(line);
2499 buf.push(b'\n');
2500 }
2501 continue;
2502 }
2503 match keyword {
2504 b"seqactive" if v45 => {
2505 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2506 let id = number(id, n)?;
2507 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2508 doc.seq_active = Some((id, name));
2509 }
2510 b"seqorder" if v45 => {
2511 for f in rest.split(|&b| b == b' ').filter(|f| !f.is_empty()) {
2512 if doc.seq_order.len() >= MAX_SEQUENCES {
2513 return Err(format!("line {n}: seqorder names more than {MAX_SEQUENCES} sequences").into());
2514 }
2515 doc.seq_order.push(number(f, n)?);
2516 }
2517 }
2518 b"seq" if v45 => {
2519 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2520 let id = number(id, n)?;
2521 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2522 block = Some((id, name, Vec::new()));
2523 }
2524 b"playhead" => {
2525 if playhead_seen || !doc.sources.is_empty() {
2526 return Err(
2527 format!("line {n}: playhead belongs once, before the sources").into(),
2528 );
2529 }
2530 doc.playhead = number(rest, n)?;
2531 playhead_seen = true;
2532 }
2533 b"resolution" if v7 => {
2534 if doc.resolution.is_some() || !doc.sources.is_empty() {
2535 return Err(
2536 format!("line {n}: resolution belongs once, before the sources").into(),
2537 );
2538 }
2539 let f = fields(rest, 2, "resolution", n)?;
2540 let (width, height) = (number(f[0], n)?, number(f[1], n)?);
2541 // The same bound the keystroke has (`crate::is_resolution`):
2542 // unbounded here, this line reached `open_black` and panicked
2543 // the open with a capacity overflow.
2544 if !crate::is_resolution(width, height) {
2545 return Err(format!("line {n}: {width}x{height} is not a picture").into());
2546 }
2547 doc.resolution = Some((width, height));
2548 }
2549 b"fps" if v9 => {
2550 if doc.fps.is_some() || !doc.sources.is_empty() {
2551 return Err(format!("line {n}: fps belongs once, before the sources").into());
2552 }
2553 let f = fields(rest, 1, "fps", n)?;
2554 let fps = std::str::from_utf8(f[0])
2555 .ok()
2556 .and_then(|s| s.parse::<f64>().ok())
2557 .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0)
2558 .ok_or_else(|| {
2559 format!(
2560 "line {n}: {:?} is not a frame rate",
2561 String::from_utf8_lossy(f[0])
2562 )
2563 })?;
2564 doc.fps = Some(fps);
2565 }
2566 b"samplerate" if v17 => {
2567 if doc.sample_rate.is_some() || !doc.sources.is_empty() {
2568 return Err(
2569 format!("line {n}: samplerate belongs once, before the sources").into(),
2570 );
2571 }
2572 let f = fields(rest, 1, "samplerate", n)?;
2573 let rate = number(f[0], n)?;
2574 if !(1_000..=384_000).contains(&rate) {
2575 return Err(format!("line {n}: {rate} Hz is not a sound rate").into());
2576 }
2577 doc.sample_rate = Some(rate);
2578 }
2579 b"tonemap" if v11 => {
2580 if !doc.sources.is_empty() {
2581 return Err(
2582 format!("line {n}: tonemap belongs once, before the sources").into(),
2583 );
2584 }
2585 let f = fields(rest, 1, "tonemap", n)?;
2586 doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| {
2587 format!(
2588 "line {n}: {:?} is not a tone map",
2589 String::from_utf8_lossy(f[0])
2590 )
2591 })?;
2592 }
2593 b"proxy" if v12 => {
2594 if !doc.sources.is_empty() {
2595 return Err(format!("line {n}: proxy belongs once, before the sources").into());
2596 }
2597 let f = fields(rest, 1, "proxy", n)?;
2598 doc.proxy = match f[0] {
2599 b"on" => true,
2600 b"off" => false,
2601 other => {
2602 return Err(format!(
2603 "line {n}: proxy is on or off, not {:?}",
2604 String::from_utf8_lossy(other)
2605 )
2606 .into());
2607 }
2608 };
2609 }
2610 b"autoproxy" if v13 => {
2611 if !doc.sources.is_empty() {
2612 return Err(
2613 format!("line {n}: autoproxy belongs once, before the sources").into(),
2614 );
2615 }
2616 let f = fields(rest, 1, "autoproxy", n)?;
2617 doc.auto_proxy = match f[0] {
2618 b"on" => true,
2619 b"off" => false,
2620 other => {
2621 return Err(format!(
2622 "line {n}: autoproxy is on or off, not {:?}",
2623 String::from_utf8_lossy(other)
2624 )
2625 .into());
2626 }
2627 };
2628 }
2629 b"encoder" if v14 => {
2630 if !doc.sources.is_empty() {
2631 return Err(
2632 format!("line {n}: encoder belongs once, before the sources").into(),
2633 );
2634 }
2635 let f = fields(rest, 1, "encoder", n)?;
2636 doc.encoder = crate::export::EncoderSeat::from_name(f[0]).ok_or_else(|| {
2637 format!(
2638 "line {n}: encoder is auto, hardware or software, not {:?}",
2639 String::from_utf8_lossy(f[0])
2640 )
2641 })?;
2642 }
2643 b"limiter" if v9 => {
2644 if !doc.sources.is_empty() {
2645 return Err(
2646 format!("line {n}: limiter belongs once, before the sources").into(),
2647 );
2648 }
2649 let f = fields(rest, 2, "limiter", n)?;
2650 let on = match f[1] {
2651 b"on" => true,
2652 b"off" => false,
2653 other => {
2654 return Err(format!(
2655 "line {n}: limiter is on or off, not {:?}",
2656 String::from_utf8_lossy(other)
2657 )
2658 .into());
2659 }
2660 };
2661 // Through the same clamp a nudge goes through: a hand-written
2662 // ceiling above full scale is a ceiling that limits nothing.
2663 doc.limiter = Limiter {
2664 on,
2665 ..Limiter::default()
2666 }
2667 .with_ceiling(float(f[0], n)?);
2668 }
2669 // After the lanes it names, which is where `emit` writes it: a lane
2670 // is declared by its own lines, and a gain declares nothing.
2671 b"gain" if v9 => {
2672 let f = fields(rest, 3, "gain", n)?;
2673 let kind = match f[0] {
2674 b"video" => LaneKind::Video,
2675 b"audio" => LaneKind::Audio,
2676 other => {
2677 return Err(format!(
2678 "line {n}: gain names {:?}, not a lane kind",
2679 String::from_utf8_lossy(other)
2680 )
2681 .into());
2682 }
2683 };
2684 let ord = number(f[1], n)?;
2685 let at = doc
2686 .lanes
2687 .iter()
2688 .enumerate()
2689 .filter(|(_, (k, _))| *k == kind)
2690 .nth(ord.saturating_sub(1) as usize)
2691 .map(|(at, _)| at)
2692 .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?;
2693 doc.gains.resize(doc.lanes.len(), 0.0);
2694 doc.gains[at] = float(f[2], n)?;
2695 }
2696 // After the lanes, for the reason a gain is: it names one. A line
2697 // carries the switches that are set, in any order and each once, and
2698 // a switch the kind of lane cannot have is refused by name.
2699 // After the lanes, for the reason a gain is: it names one, and the key
2700 // it names is checked once the whole file is read.
2701 b"duck" if v25 => {
2702 let f = fields(rest, 7, "duck", n)?;
2703 if f[0] != b"audio" {
2704 return Err(format!(
2705 "line {n}: duck names {:?}, not an audio lane",
2706 String::from_utf8_lossy(f[0])
2707 )
2708 .into());
2709 }
2710 let ord = number(f[1], n)?;
2711 let at = doc
2712 .lanes
2713 .iter()
2714 .enumerate()
2715 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2716 .nth(ord.saturating_sub(1) as usize)
2717 .map(|(at, _)| at)
2718 .ok_or_else(|| format!("line {n}: duck names a lane that is not there"))?;
2719 // 1-based in the file, as a gain's lane is; 0-based in the struct.
2720 let under = number(f[2], n)?;
2721 let duck = Duck {
2722 under: under.checked_sub(1).ok_or_else(|| {
2723 format!("line {n}: duck names audio lane 0, and lanes count from 1")
2724 })? as usize,
2725 depth_db: float(f[3], n)?,
2726 threshold_db: float(f[4], n)?,
2727 attack_ms: float(f[5], n)?,
2728 release_ms: float(f[6], n)?,
2729 };
2730 let in_range = (MIN_DEPTH_DB..=MAX_DEPTH_DB).contains(&duck.depth_db)
2731 && (MIN_THRESHOLD_DB..=MAX_THRESHOLD_DB).contains(&duck.threshold_db)
2732 && duck.attack_ms >= MIN_TIME_MS
2733 && duck.attack_ms <= MAX_ATTACK_MS
2734 && duck.release_ms >= MIN_TIME_MS
2735 && duck.release_ms <= MAX_RELEASE_MS;
2736 if !in_range {
2737 return Err(format!("line {n}: duck has a number out of its range").into());
2738 }
2739 doc.ducks.resize(doc.lanes.len(), Vec::new());
2740 // Several keys for one lane are a v30 dialect; before it a lane
2741 // had one duck, and a second line for it is a file that says
2742 // something its dialect cannot.
2743 if !v30 && !doc.ducks[at].is_empty() {
2744 return Err(format!("line {n}: duck names a lane twice").into());
2745 }
2746 if doc.ducks[at].iter().any(|d| d.under == duck.under) {
2747 return Err(format!("line {n}: duck names the same key twice").into());
2748 }
2749 doc.ducks[at].push(duck);
2750 }
2751 b"voice" if v41 => parse_voice(rest, n, &mut doc)?,
2752 b"effect" if v42 => parse_effect(rest, n, &mut doc)?,
2753 b"wheels" | b"curve" | b"lut" if v43 => parse_look(keyword, rest, n, dir, &mut doc)?,
2754 // After the lanes, which is where `clip_gain_lines` writes it: a line
2755 // names a clip, and a clip is declared by its lane's lines. Only audio
2756 // clips take one, the setter's own rule.
2757 b"lanepan" | b"clippan" if v50 => {
2758 let clip = keyword == b"clippan";
2759 let f = fields(rest, if clip { 4 } else { 3 }, if clip { "clippan" } else { "lanepan" }, n)?;
2760 if f[0] != b"audio" {
2761 return Err(format!("line {n}: pan names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2762 }
2763 let ord = number(f[1], n)?;
2764 let at = doc
2765 .lanes
2766 .iter()
2767 .enumerate()
2768 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2769 .nth(ord.saturating_sub(1) as usize)
2770 .map(|(at, _)| at)
2771 .ok_or_else(|| format!("line {n}: pan names a lane that is not there"))?;
2772 let pan = float(f[if clip { 3 } else { 2 }], n)?;
2773 if !(-1.0..=1.0).contains(&pan) {
2774 return Err(format!("line {n}: pan has a number out of its range").into());
2775 }
2776 if clip {
2777 let idx = number(f[2], n)? as usize;
2778 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;
2779 } else {
2780 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
2781 doc.flags[at].pan = pan;
2782 }
2783 }
2784 // After the lanes, which is where `pitch_lines` writes it, as `clippan` is.
2785 b"pitch" if v55 => {
2786 let f = fields(rest, 4, "pitch", n)?;
2787 if f[0] != b"audio" {
2788 return Err(format!("line {n}: pitch names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2789 }
2790 let ord = number(f[1], n)?;
2791 let at = doc
2792 .lanes
2793 .iter()
2794 .enumerate()
2795 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2796 .nth(ord.saturating_sub(1) as usize)
2797 .map(|(at, _)| at)
2798 .ok_or_else(|| format!("line {n}: pitch names a lane that is not there"))?;
2799 let idx = number(f[2], n)? as usize;
2800 let semitones = std::str::from_utf8(f[3]).ok().and_then(|s| s.parse::<i8>().ok());
2801 let semitones = match semitones {
2802 Some(v) if (crate::project::MIN_CLIP_PITCH..=crate::project::MAX_CLIP_PITCH).contains(&v) => v,
2803 _ => return Err(format!("line {n}: pitch has a number out of its range").into()),
2804 };
2805 doc.lanes[at]
2806 .1
2807 .get_mut(idx)
2808 .ok_or_else(|| format!("line {n}: pitch names clip {idx}, which the lane does not have"))?
2809 .pitch = semitones;
2810 }
2811 b"clipgain" if v27 => {
2812 let f = fields(rest, 4, "clipgain", n)?;
2813 if f[0] != b"audio" {
2814 return Err(format!(
2815 "line {n}: clipgain names {:?}, not an audio lane",
2816 String::from_utf8_lossy(f[0])
2817 )
2818 .into());
2819 }
2820 let ord = number(f[1], n)?;
2821 let at = doc
2822 .lanes
2823 .iter()
2824 .enumerate()
2825 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2826 .nth(ord.saturating_sub(1) as usize)
2827 .map(|(at, _)| at)
2828 .ok_or_else(|| format!("line {n}: clipgain names a lane that is not there"))?;
2829 let idx = number(f[2], n)? as usize;
2830 let db = float(f[3], n)?;
2831 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&db) {
2832 return Err(format!("line {n}: clipgain has a number out of its range").into());
2833 }
2834 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2835 format!("line {n}: clipgain names clip {idx}, which the lane does not have")
2836 })?;
2837 clip.gain_db = db;
2838 }
2839 // After the lanes, which is where `tkey_lines` writes it: a placement
2840 // key is source-ordered and unique by source frame, at most
2841 // `MAX_TRANSFORM_KEYS` of them, each a finite placement with an opacity
2842 // in `0..=1`. Only a video clip can carry them.
2843 b"tkeys" if v32 => {
2844 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2845 if f.len() < 4 {
2846 return Err(format!("line {n}: tkeys wants a clip and a key").into());
2847 }
2848 let lane_kind = match f[0] {
2849 b"video" => LaneKind::Video,
2850 other => {
2851 return Err(format!(
2852 "line {n}: tkeys names {:?}, not a video lane",
2853 String::from_utf8_lossy(other)
2854 )
2855 .into())
2856 }
2857 };
2858 let ord = number(f[1], n)?;
2859 let at = doc
2860 .lanes
2861 .iter()
2862 .enumerate()
2863 .filter(|(_, (k, _))| *k == lane_kind)
2864 .nth(ord.saturating_sub(1) as usize)
2865 .map(|(at, _)| at)
2866 .ok_or_else(|| format!("line {n}: tkeys names a lane that is not there"))?;
2867 let idx = number(f[2], n)? as usize;
2868 let points = &f[3..];
2869 if points.len() > MAX_TRANSFORM_KEYS {
2870 return Err(
2871 format!("line {n}: tkeys has more than {MAX_TRANSFORM_KEYS} keys").into(),
2872 );
2873 }
2874 let mut keys: Vec<TransformKey> = Vec::with_capacity(points.len());
2875 for point in points {
2876 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
2877 if parts.len() != 3 {
2878 return Err(format!("line {n}: tkeys key wants at:ease:values").into());
2879 }
2880 let ease = KeyEase::from_token(parts[1])
2881 .filter(|e| v39 || matches!(e, KeyEase::Linear | KeyEase::Ease))
2882 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
2883 .ok_or_else(|| format!("line {n}: tkeys ease is lin, in, out, ease or hold"))?;
2884 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
2885 if v.len() != 9 {
2886 return Err(format!("line {n}: tkeys key wants 9 values").into());
2887 }
2888 let params = TransformParams {
2889 pos_x: float(v[0], n)?,
2890 pos_y: float(v[1], n)?,
2891 scale: float(v[2], n)?,
2892 rotate: float(v[3], n)?,
2893 crop_l: float(v[4], n)?,
2894 crop_r: float(v[5], n)?,
2895 crop_t: float(v[6], n)?,
2896 crop_b: float(v[7], n)?,
2897 opacity: float(v[8], n)?,
2898 };
2899 if !(0.0..=1.0).contains(&params.opacity) {
2900 return Err(format!("line {n}: tkeys opacity must be 0..=1").into());
2901 }
2902 let key = TransformKey {
2903 at: number(parts[0], n)?,
2904 params,
2905 ease,
2906 };
2907 if keys.last().is_some_and(|k| k.at >= key.at) {
2908 return Err(
2909 format!("line {n}: tkeys keys are not in source order").into()
2910 );
2911 }
2912 keys.push(key);
2913 }
2914 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2915 format!("line {n}: tkeys names clip {idx}, which the lane does not have")
2916 })?;
2917 clip.transform_keys = keys;
2918 }
2919 // After the lanes, which is where `opacity_key_lines` and `color_key_lines`
2920 // write them: a video clip's opacity (`0..=1`) and colour animation,
2921 // source-ordered and unique by source frame, at most `MAX_TRANSFORM_KEYS`
2922 // and `MAX_COLOR_KEYS` of them, each in range.
2923 // A stabilised video clip, named as an `okeys` line names its clip.
2924 b"deint" if v46 => {
2925 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2926 if f.len() != 4 || f[0] != b"video" {
2927 return Err(format!("line {n}: deint wants a video clip and a mode").into());
2928 }
2929 let ord = number(f[1], n)?;
2930 let at = doc
2931 .lanes
2932 .iter()
2933 .enumerate()
2934 .filter(|(_, (k, _))| *k == LaneKind::Video)
2935 .nth(ord.saturating_sub(1) as usize)
2936 .map(|(at, _)| at)
2937 .ok_or_else(|| format!("line {n}: deint names a lane that is not there"))?;
2938 let idx = number(f[2], n)? as usize;
2939 let mode = std::str::from_utf8(f[3])
2940 .ok()
2941 .and_then(Deinterlace::from_name)
2942 .ok_or_else(|| format!("line {n}: deint mode must be frame, field or off"))?;
2943 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2944 format!("line {n}: deint names clip {idx}, which the lane does not have")
2945 })?;
2946 clip.deinterlace = mode;
2947 }
2948 b"lanename" if v46 => {
2949 let mut parts = rest.splitn(3, |&b| b == b' ');
2950 let kind = match parts.next().unwrap_or_default() {
2951 b"video" => LaneKind::Video,
2952 b"audio" => LaneKind::Audio,
2953 b"sub" => LaneKind::Subtitle,
2954 other => {
2955 return Err(format!("line {n}: lanename names {:?}, not a lane kind", String::from_utf8_lossy(other)).into());
2956 }
2957 };
2958 let ord = number(parts.next().unwrap_or_default(), n)?;
2959 let at = doc
2960 .lanes
2961 .iter()
2962 .enumerate()
2963 .filter(|(_, (k, _))| *k == kind)
2964 .nth(ord.saturating_sub(1) as usize)
2965 .map(|(at, _)| at)
2966 .ok_or_else(|| format!("line {n}: lanename names a lane that is not there"))?;
2967 let name = unescape_text(parts.next().unwrap_or_default(), n)?;
2968 if name.is_empty() || name.chars().count() > crate::project::MAX_LANE_NAME_CHARS || name.chars().any(char::is_control) {
2969 return Err(format!("line {n}: a lane name is 1 to {} characters", crate::project::MAX_LANE_NAME_CHARS).into());
2970 }
2971 doc.names.resize(doc.lanes.len(), String::new());
2972 doc.names[at] = name;
2973 }
2974 b"stab" if v44 => {
2975 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2976 if f.len() != 5 || f[0] != b"video" {
2977 return Err(format!("line {n}: stab wants a video clip, a strength and a crop").into());
2978 }
2979 let ord = number(f[1], n)?;
2980 let at = doc
2981 .lanes
2982 .iter()
2983 .enumerate()
2984 .filter(|(_, (k, _))| *k == LaneKind::Video)
2985 .nth(ord.saturating_sub(1) as usize)
2986 .map(|(at, _)| at)
2987 .ok_or_else(|| format!("line {n}: stab names a lane that is not there"))?;
2988 let idx = number(f[2], n)? as usize;
2989 let strength = std::str::from_utf8(f[3])
2990 .ok()
2991 .and_then(|v| v.parse::<f32>().ok())
2992 .filter(|v| (0.0..=1.0).contains(v))
2993 .ok_or_else(|| format!("line {n}: stab strength must be a number from 0 to 1"))?;
2994 let crop = std::str::from_utf8(f[4])
2995 .ok()
2996 .and_then(crate::stabilise::Crop::from_name)
2997 .ok_or_else(|| format!("line {n}: stab crop must be zoom or full"))?;
2998 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2999 format!("line {n}: stab names clip {idx}, which the lane does not have")
3000 })?;
3001 clip.stabilise = Some(crate::stabilise::Stabilise::new(strength, crop));
3002 }
3003 // A v53 mask's keys: five values, the mask's invert stays at its static value.
3004 b"mkeys" if v53 => {
3005 use crate::effects::EffectKind;
3006 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3007 if f.len() < 5 || f[0] != b"video" {
3008 return Err(format!("line {n}: mkeys wants a video clip, a slot and a key").into());
3009 }
3010 let ord = number(f[1], n)?;
3011 let at = doc
3012 .lanes
3013 .iter()
3014 .enumerate()
3015 .filter(|(_, (k, _))| *k == LaneKind::Video)
3016 .nth(ord.saturating_sub(1) as usize)
3017 .map(|(at, _)| at)
3018 .ok_or_else(|| format!("line {n}: mkeys names a lane that is not there"))?;
3019 let idx = number(f[2], n)? as usize;
3020 let slot = number(f[3], n)? as usize;
3021 let clip = doc.lanes[at]
3022 .1
3023 .get_mut(idx)
3024 .ok_or_else(|| format!("line {n}: mkeys names clip {idx}, which the lane does not have"))?;
3025 let effect = clip
3026 .effects
3027 .get_mut(slot)
3028 .filter(|e| matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask))
3029 .ok_or_else(|| format!("line {n}: mkeys names an effect that is not a mask"))?;
3030 let invert = effect.values[5];
3031 let mut keys = read_effect_keys("mkeys", &f[4..], &EffectKind::RectMask.params()[..5], n, v56)?;
3032 for k in &mut keys {
3033 k.values[5] = invert;
3034 }
3035 effect.keys = keys;
3036 }
3037 b"ekeys" if v56 => {
3038 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3039 if f.len() < 4 || f[0] != b"video" {
3040 return Err(format!("line {n}: ekeys wants a video clip, a slot and a key").into());
3041 }
3042 let ord = number(f[1], n)?;
3043 let at = doc
3044 .lanes
3045 .iter()
3046 .enumerate()
3047 .filter(|(_, (k, _))| *k == LaneKind::Video)
3048 .nth(ord.saturating_sub(1) as usize)
3049 .map(|(at, _)| at)
3050 .ok_or_else(|| format!("line {n}: ekeys names a lane that is not there"))?;
3051 let idx = number(f[2], n)? as usize;
3052 let slot = number(f[3], n)? as usize;
3053 let clip = doc.lanes[at]
3054 .1
3055 .get_mut(idx)
3056 .ok_or_else(|| format!("line {n}: ekeys names clip {idx}, which the lane does not have"))?;
3057 let effect = clip
3058 .effects
3059 .get_mut(slot)
3060 .ok_or_else(|| format!("line {n}: ekeys names an effect the clip does not have"))?;
3061 let specs = effect.kind.params();
3062 let mut keys = read_effect_keys("ekeys", &f[4..], specs, n, v56)?;
3063 // A parameter that cannot be keyed (a switch or a choice) keeps its static value.
3064 for k in &mut keys {
3065 for (i, _) in specs.iter().enumerate().filter(|(_, s)| !s.keyable()) {
3066 k.values[i] = effect.values[i];
3067 }
3068 }
3069 effect.keys = keys;
3070 }
3071 b"okeys" | b"ckeys" if v39 => {
3072 let colour = keyword == b"ckeys";
3073 let name = if colour { "ckeys" } else { "okeys" };
3074 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3075 if f.len() < 4 || f[0] != b"video" {
3076 return Err(format!("line {n}: {name} wants a video clip and a key").into());
3077 }
3078 let ord = number(f[1], n)?;
3079 let at = doc
3080 .lanes
3081 .iter()
3082 .enumerate()
3083 .filter(|(_, (k, _))| *k == LaneKind::Video)
3084 .nth(ord.saturating_sub(1) as usize)
3085 .map(|(at, _)| at)
3086 .ok_or_else(|| format!("line {n}: {name} names a lane that is not there"))?;
3087 let idx = number(f[2], n)? as usize;
3088 let points = &f[3..];
3089 let cap = if colour { MAX_COLOR_KEYS } else { MAX_TRANSFORM_KEYS };
3090 if points.len() > cap {
3091 return Err(format!("line {n}: {name} has more than {cap} keys").into());
3092 }
3093 let mut okeys: Vec<OpacityKey> = Vec::new();
3094 let mut ckeys: Vec<ColorKey> = Vec::new();
3095 for point in points {
3096 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3097 if parts.len() != 3 {
3098 return Err(format!("line {n}: {name} key wants at:ease:values").into());
3099 }
3100 let at_frame = number(parts[0], n)?;
3101 let ease = KeyEase::from_token(parts[1])
3102 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
3103 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease or hold"))?;
3104 let last = if colour { ckeys.last().map(|k| k.at) } else { okeys.last().map(|k| k.at) };
3105 if last.is_some_and(|l| l >= at_frame) {
3106 return Err(format!("line {n}: {name} keys are not in source order").into());
3107 }
3108 if colour {
3109 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3110 if v.len() != 4 {
3111 return Err(format!("line {n}: ckeys key wants 4 values").into());
3112 }
3113 let params = ColorParams {
3114 brightness: float(v[0], n)?,
3115 contrast: float(v[1], n)?,
3116 saturation: float(v[2], n)?,
3117 tint: float(v[3], n)?,
3118 ..Default::default()
3119 };
3120 if !((-1.0..=1.0).contains(&params.brightness)
3121 && (0.0..=2.0).contains(&params.contrast)
3122 && (0.0..=2.0).contains(&params.saturation)
3123 && (-1.0..=1.0).contains(&params.tint))
3124 {
3125 return Err(format!("line {n}: ckeys has a value out of its range").into());
3126 }
3127 ckeys.push(ColorKey { at: at_frame, params, ease });
3128 } else {
3129 let opacity = float(parts[2], n)?;
3130 if !(0.0..=1.0).contains(&opacity) {
3131 return Err(format!("line {n}: okeys opacity must be 0..=1").into());
3132 }
3133 okeys.push(OpacityKey { at: at_frame, opacity, ease });
3134 }
3135 }
3136 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3137 format!("line {n}: {name} names clip {idx}, which the lane does not have")
3138 })?;
3139 if colour {
3140 clip.color_keys = ckeys;
3141 } else {
3142 clip.opacity_keys = okeys;
3143 }
3144 }
3145 // After the lanes, which is where `gain_key_lines` writes it: a line
3146 // names a clip, and a clip is declared by its lane's lines. Its points
3147 // are source-ordered and unique by source frame, as the setters keep
3148 // them, and at most `MAX_GAIN_KEYS` of them, each in range.
3149 b"gainkeys" if v28 => {
3150 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3151 if f.len() < 4 {
3152 return Err(format!("line {n}: gainkeys wants a clip and a point").into());
3153 }
3154 let kind = match f[0] {
3155 b"audio" => LaneKind::Audio,
3156 b"video" => LaneKind::Video,
3157 other => {
3158 return Err(format!(
3159 "line {n}: gainkeys names {:?}, not a lane kind",
3160 String::from_utf8_lossy(other)
3161 )
3162 .into());
3163 }
3164 };
3165 let ord = number(f[1], n)?;
3166 let at = doc
3167 .lanes
3168 .iter()
3169 .enumerate()
3170 .filter(|(_, (k, _))| *k == kind)
3171 .nth(ord.saturating_sub(1) as usize)
3172 .map(|(at, _)| at)
3173 .ok_or_else(|| format!("line {n}: gainkeys names a lane that is not there"))?;
3174 let idx = number(f[2], n)? as usize;
3175 let points = &f[3..];
3176 if points.len() > MAX_GAIN_KEYS {
3177 return Err(
3178 format!("line {n}: gainkeys has more than {MAX_GAIN_KEYS} points").into(),
3179 );
3180 }
3181 let mut keys = Vec::with_capacity(points.len());
3182 for point in points {
3183 let colon = point
3184 .iter()
3185 .position(|&b| b == b':')
3186 .ok_or_else(|| format!("line {n}: gainkeys point wants at:db"))?;
3187 let (a, d) = (&point[..colon], &point[colon + 1..]);
3188 // A v39 point may end in the ease of the segment that leaves it.
3189 let (d, ease) = match d.iter().position(|&b| b == b':') {
3190 Some(c) if v39 => (
3191 &d[..c],
3192 KeyEase::from_token(&d[c + 1..])
3193 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
3194 .ok_or_else(|| format!("line {n}: gainkeys ease is lin, in, out, ease or hold"))?,
3195 ),
3196 _ => (d, KeyEase::Linear),
3197 };
3198 let key = GainKey {
3199 at: number(a, n)?,
3200 db: float(d, n)?,
3201 ease,
3202 };
3203 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&key.db) {
3204 return Err(format!("line {n}: gainkeys has a dB out of its range").into());
3205 }
3206 if keys.last().is_some_and(|k: &GainKey| k.at >= key.at) {
3207 return Err(
3208 format!("line {n}: gainkeys points are not in source order").into()
3209 );
3210 }
3211 keys.push(key);
3212 }
3213 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3214 format!("line {n}: gainkeys names clip {idx}, which the lane does not have")
3215 })?;
3216 clip.gain_keys = keys;
3217 }
3218 // After the lanes and the subtitle palette: a title names neither,
3219 // and its text is the rest of the line, so it is the ninth field.
3220 b"title" if v26 => {
3221 let f: Vec<&[u8]> = rest.splitn(9, |&b| b == b' ').collect();
3222 if f.len() != 9 {
3223 return Err(format!("line {n}: title wants 9 fields, found {}", f.len()).into());
3224 }
3225 let outline = match f[5] {
3226 b"none" => Outline::None,
3227 b"thin" => Outline::Thin,
3228 b"thick" => Outline::Thick,
3229 other => {
3230 return Err(format!(
3231 "line {n}: title outline {:?} is none, thin or thick",
3232 String::from_utf8_lossy(other)
3233 )
3234 .into());
3235 }
3236 };
3237 let boxed = match f[6] {
3238 b"0" => false,
3239 b"1" => true,
3240 other => {
3241 return Err(format!(
3242 "line {n}: title boxed {:?} is 0 or 1",
3243 String::from_utf8_lossy(other)
3244 )
3245 .into());
3246 }
3247 };
3248 let place = match f[7] {
3249 b"bottom" => Place::Bottom,
3250 b"top" => Place::Top,
3251 b"centre" => Place::Centre,
3252 other => {
3253 return Err(format!(
3254 "line {n}: title place {:?} is bottom, top or centre",
3255 String::from_utf8_lossy(other)
3256 )
3257 .into());
3258 }
3259 };
3260 let title = Title {
3261 start: number(f[0], n)?,
3262 frames: number(f[1], n)?,
3263 text: unescape_text(f[8], n)?,
3264 style: TextStyle {
3265 size: number(f[4], n)?,
3266 outline,
3267 boxed,
3268 place,
3269 ..TextStyle::default()
3270 },
3271 fade_in: number(f[2], n)?,
3272 fade_out: number(f[3], n)?,
3273 in_anim: TitleAnim::None,
3274 out_anim: TitleAnim::None,
3275 anim_frames: 0,
3276 keys: Vec::new(),
3277 };
3278 check_title(&title).map_err(|e| format!("line {n}: {e}"))?;
3279 doc.titles.push(title);
3280 }
3281 // A chapter is a frame and a name: the name is the rest of the line, escaped
3282 // as a `cue` line's is. Written in frame order, one per frame.
3283 // A clip's speed ramp, as `speedkeys` lines, after the lanes they name.
3284 // Its keys are clip-relative and sorted, at most `MAX_SPEED_KEYS` of them, each
3285 // speed in range; the clip's footprint grows with the ramp, so the lane is
3286 // checked again here, where the ramp lands.
3287 b"speedkeys" if v35 => {
3288 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3289 if f.len() < 4 {
3290 return Err(format!("line {n}: speedkeys wants a clip and a point").into());
3291 }
3292 let kind = match f[0] {
3293 b"audio" => LaneKind::Audio,
3294 b"video" => LaneKind::Video,
3295 other => {
3296 return Err(format!(
3297 "line {n}: speedkeys names {:?}, not a lane kind",
3298 String::from_utf8_lossy(other)
3299 )
3300 .into());
3301 }
3302 };
3303 let ord = number(f[1], n)?;
3304 let at = doc
3305 .lanes
3306 .iter()
3307 .enumerate()
3308 .filter(|(_, (k, _))| *k == kind)
3309 .nth(ord.saturating_sub(1) as usize)
3310 .map(|(at, _)| at)
3311 .ok_or_else(|| format!("line {n}: speedkeys names a lane that is not there"))?;
3312 let idx = number(f[2], n)? as usize;
3313 let points = &f[3..];
3314 if points.len() > MAX_SPEED_KEYS {
3315 return Err(format!("line {n}: speedkeys has more than {MAX_SPEED_KEYS} points").into());
3316 }
3317 let mut keys = Vec::with_capacity(points.len());
3318 for point in points {
3319 let colon = point
3320 .iter()
3321 .position(|&b| b == b':')
3322 .ok_or_else(|| format!("line {n}: speedkeys point wants at:permille"))?;
3323 let (a, p) = (&point[..colon], &point[colon + 1..]);
3324 let permille = number(p, n)?;
3325 if permille < u32::from(Speed::MIN.permille())
3326 || permille > u32::from(Speed::MAX.permille())
3327 {
3328 return Err(format!("line {n}: speedkeys speed {permille} is out of range").into());
3329 }
3330 let key = SpeedKey {
3331 at: number(a, n)?,
3332 speed: Speed::from_permille(permille as u16),
3333 };
3334 if keys.last().is_some_and(|k: &SpeedKey| k.at >= key.at) {
3335 return Err(format!("line {n}: speedkeys points are not in frame order").into());
3336 }
3337 keys.push(key);
3338 }
3339 let lane = &mut doc.lanes[at].1;
3340 let clip = lane.get_mut(idx).ok_or_else(|| {
3341 format!("line {n}: speedkeys names clip {idx}, which the lane does not have")
3342 })?;
3343 clip.speed_keys = keys;
3344 let end = clip.start.checked_add(clip.frames()).ok_or_else(|| {
3345 format!("line {n}: speed ramp runs past the last frame there is")
3346 })?;
3347 if lane.get(idx + 1).is_some_and(|next| next.start < end) {
3348 return Err(format!("line {n}: speed ramp runs into the next clip on its lane").into());
3349 }
3350 }
3351 // How a clip's transition is drawn, after the lanes it names.
3352 b"transition" if v37 => {
3353 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3354 if f.len() != 4 {
3355 return Err(format!("line {n}: transition wants a clip and a kind").into());
3356 }
3357 let kind = match f[0] {
3358 b"audio" => LaneKind::Audio,
3359 b"video" => LaneKind::Video,
3360 other => {
3361 return Err(format!(
3362 "line {n}: transition names {:?}, not a lane kind",
3363 String::from_utf8_lossy(other)
3364 )
3365 .into());
3366 }
3367 };
3368 let ord = number(f[1], n)?;
3369 let at = doc
3370 .lanes
3371 .iter()
3372 .enumerate()
3373 .filter(|(_, (k, _))| *k == kind)
3374 .nth(ord.saturating_sub(1) as usize)
3375 .map(|(at, _)| at)
3376 .ok_or_else(|| format!("line {n}: transition names a lane that is not there"))?;
3377 let idx = number(f[2], n)? as usize;
3378 let name = String::from_utf8_lossy(f[3]);
3379 let kind = TransitionKind::parse(&name)
3380 .ok_or_else(|| format!("line {n}: transition kind {name:?} is not one"))?;
3381 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3382 format!("line {n}: transition names clip {idx}, which the lane does not have")
3383 })?;
3384 clip.transition_kind = kind;
3385 }
3386 // A reversed clip: named like a `speedkeys` line names its clip. The
3387 // window, speed and ramp are the clip's own lines; this is the direction.
3388 b"reverse" if v38 => {
3389 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3390 if f.len() != 3 {
3391 return Err(format!("line {n}: reverse wants a lane and a clip").into());
3392 }
3393 let kind = match f[0] {
3394 b"audio" => LaneKind::Audio,
3395 b"video" => LaneKind::Video,
3396 other => {
3397 return Err(format!(
3398 "line {n}: reverse names {:?}, not a lane kind",
3399 String::from_utf8_lossy(other)
3400 )
3401 .into());
3402 }
3403 };
3404 let ord = number(f[1], n)?;
3405 let at = doc
3406 .lanes
3407 .iter()
3408 .enumerate()
3409 .filter(|(_, (k, _))| *k == kind)
3410 .nth(ord.saturating_sub(1) as usize)
3411 .map(|(at, _)| at)
3412 .ok_or_else(|| format!("line {n}: reverse names a lane that is not there"))?;
3413 let idx = number(f[2], n)? as usize;
3414 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3415 format!("line {n}: reverse names clip {idx}, which the lane does not have")
3416 })?;
3417 clip.reversed = true;
3418 }
3419 b"angle" if v47 => {
3420 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3421 if f.len() != 5 {
3422 return Err(format!("line {n}: angle wants a lane, a clip, a picture angle and a sound angle").into());
3423 }
3424 let kind = match f[0] {
3425 b"audio" => LaneKind::Audio,
3426 b"video" => LaneKind::Video,
3427 _ => return Err(format!("line {n}: angle names a lane kind that is not video or audio").into()),
3428 };
3429 let ord = number(f[1], n)?;
3430 let at = doc
3431 .lanes
3432 .iter()
3433 .enumerate()
3434 .filter(|(_, (k, _))| *k == kind)
3435 .nth(ord.saturating_sub(1) as usize)
3436 .map(|(at, _)| at)
3437 .ok_or_else(|| format!("line {n}: angle names a lane that is not there"))?;
3438 let idx = number(f[2], n)? as usize;
3439 let one_based = |f: &[u8]| -> crate::Result<u8> {
3440 let v = number(f, n)?;
3441 u8::try_from(v.wrapping_sub(1))
3442 .ok()
3443 .filter(|a| usize::from(*a) < crate::project::MAX_ANGLES)
3444 .ok_or_else(|| format!("line {n}: an angle is a number from 1 to {}", crate::project::MAX_ANGLES).into())
3445 };
3446 let video = one_based(f[3])?;
3447 let audio = if f[4] == b"-" { None } else { Some(one_based(f[4])?) };
3448 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3449 format!("line {n}: angle names clip {idx}, which the lane does not have")
3450 })?;
3451 clip.angle = crate::project::Angle { video, audio };
3452 }
3453 // A title's look: which title (by its position in the list), where its block sits,
3454 // how its lines line up, its weight, its colour and its box colour.
3455 b"titlestyle" if v49 => {
3456 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3457 if f.len() != 6 {
3458 return Err(format!("line {n}: titlestyle wants a title, a position, an alignment, a weight and two colours").into());
3459 }
3460 let idx = number(f[0], n)? as usize;
3461 let side = |b: &[u8], what: &str| -> crate::Result<u8> {
3462 match b {
3463 b"centre" => Ok(0),
3464 b"left" => Ok(1),
3465 b"right" => Ok(2),
3466 other => Err(format!("line {n}: title {what} {:?} is centre, left or right", String::from_utf8_lossy(other)).into()),
3467 }
3468 };
3469 let hplace = match side(f[1], "position")? {
3470 1 => HPlace::Left,
3471 2 => HPlace::Right,
3472 _ => HPlace::Centre,
3473 };
3474 let align = match side(f[2], "alignment")? {
3475 1 => Align::Left,
3476 2 => Align::Right,
3477 _ => Align::Centre,
3478 };
3479 let weight = match f[3] {
3480 b"regular" => Weight::Regular,
3481 b"bold" => Weight::Bold,
3482 other => return Err(format!("line {n}: title weight {:?} is regular or bold", String::from_utf8_lossy(other)).into()),
3483 };
3484 let hex = |b: &[u8], len: usize| -> crate::Result<Vec<u8>> {
3485 let ok = b.len() == len * 2 && b.iter().all(u8::is_ascii_hexdigit);
3486 if !ok {
3487 return Err(format!("line {n}: a title colour is {} hex digits", len * 2).into());
3488 }
3489 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())
3490 };
3491 let c = hex(f[4], 3)?;
3492 let bc = hex(f[5], 4)?;
3493 let title = doc
3494 .titles
3495 .get_mut(idx)
3496 .ok_or_else(|| format!("line {n}: titlestyle names title {idx}, which the file does not have"))?;
3497 title.style.hplace = hplace;
3498 title.style.align = align;
3499 title.style.weight = weight;
3500 title.style.ink = [c[0], c[1], c[2]];
3501 title.style.box_color = [bc[0], bc[1], bc[2], bc[3]];
3502 }
3503 // A title's entrance and exit: which title (by its place in the list), the two animations
3504 // and how many frames each takes.
3505 b"titleanim" if v54 => {
3506 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3507 if f.len() != 4 {
3508 return Err(format!("line {n}: titleanim wants a title, an entrance, an exit and a length").into());
3509 }
3510 let idx = number(f[0], n)? as usize;
3511 let anim = |b: &[u8]| {
3512 let name = String::from_utf8_lossy(b).into_owned();
3513 TitleAnim::from_name(&name).ok_or_else(|| format!("line {n}: title animation {name:?} is not one of the known ones"))
3514 };
3515 let (in_anim, out_anim) = (anim(f[1])?, anim(f[2])?);
3516 let anim_frames = number(f[3], n)?;
3517 let title = doc
3518 .titles
3519 .get_mut(idx)
3520 .ok_or_else(|| format!("line {n}: titleanim names title {idx}, which the file does not have"))?;
3521 title.in_anim = in_anim;
3522 title.out_anim = out_anim;
3523 title.anim_frames = anim_frames;
3524 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3525 }
3526 // A title's own keys (v56): the title by its place in the list, then each key as
3527 // `at:ease:x,y,scale,opacity`, in frame order. `check_title` holds the ranges and order.
3528 b"ttkeys" if v56 => {
3529 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3530 if f.is_empty() {
3531 return Err(format!("line {n}: ttkeys wants a title and its keys").into());
3532 }
3533 let idx = number(f[0], n)? as usize;
3534 let mut keys = Vec::with_capacity(f.len() - 1);
3535 for point in &f[1..] {
3536 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3537 if parts.len() != 3 {
3538 return Err(format!("line {n}: ttkeys key wants at:ease:x,y,scale,opacity").into());
3539 }
3540 let at = number(parts[0], n)?;
3541 let ease = KeyEase::from_token(parts[1])
3542 .ok_or_else(|| format!("line {n}: ttkeys ease is lin, in, out, ease, hold or a bezier curve"))?;
3543 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3544 if v.len() != 4 {
3545 return Err(format!("line {n}: ttkeys key wants 4 values").into());
3546 }
3547 let (x, y, scale, opacity) = (float(v[0], n)?, float(v[1], n)?, float(v[2], n)?, float(v[3], n)?);
3548 keys.push(TitleKey { at, x, y, scale, opacity, ease });
3549 }
3550 let title = doc
3551 .titles
3552 .get_mut(idx)
3553 .ok_or_else(|| format!("line {n}: ttkeys names title {idx}, which the file does not have"))?;
3554 title.keys = keys;
3555 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3556 }
3557 b"mark" if v48 => {
3558 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3559 if f.len() != 5 {
3560 return Err(format!("line {n}: mark wants a lane, a clip, a label and on or off").into());
3561 }
3562 let kind = match f[0] {
3563 b"audio" => LaneKind::Audio,
3564 b"video" => LaneKind::Video,
3565 _ => return Err(format!("line {n}: mark names a lane kind that is not video or audio").into()),
3566 };
3567 let ord = number(f[1], n)?;
3568 let at = doc
3569 .lanes
3570 .iter()
3571 .enumerate()
3572 .filter(|(_, (k, _))| *k == kind)
3573 .nth(ord.saturating_sub(1) as usize)
3574 .map(|(at, _)| at)
3575 .ok_or_else(|| format!("line {n}: mark names a lane that is not there"))?;
3576 let idx = number(f[2], n)? as usize;
3577 let label = u8::try_from(number(f[3], n)?)
3578 .ok()
3579 .filter(|l| *l <= crate::project::LABEL_COUNT)
3580 .ok_or_else(|| format!("line {n}: a label is a number from 0 to {}", crate::project::LABEL_COUNT))?;
3581 let off = match f[4] {
3582 b"on" => false,
3583 b"off" => true,
3584 _ => return Err(format!("line {n}: mark ends with on or off").into()),
3585 };
3586 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3587 format!("line {n}: mark names clip {idx}, which the lane does not have")
3588 })?;
3589 clip.mark = crate::project::ClipMark { label, off };
3590 }
3591 // The library (v51): `bin <id> <parent> <name>`, then `srcbin <source> <bin>` and
3592 // `srcfav <source>` for the sources that are filed or starred.
3593 // The project notes (v52): one `notes` line, its text escaped as a cue's is, so a
3594 // note of several lines is one line in the file.
3595 b"notes" if v52 => {
3596 if !doc.notes.is_empty() {
3597 return Err(format!("line {n}: notes is given twice").into());
3598 }
3599 doc.notes = unescape_text(rest, n)?;
3600 }
3601 // The length a still is placed at (v52), in seconds, within the range the editor allows.
3602 b"still" if v52 => {
3603 let f = fields(rest, 1, "still", n)?;
3604 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"))?;
3605 if !(STILL_MIN_SECS..=STILL_MAX_SECS).contains(&secs) {
3606 return Err(format!("line {n}: a still is {STILL_MIN_SECS} to {STILL_MAX_SECS} s long, not {secs}").into());
3607 }
3608 doc.still_secs = Some(secs);
3609 }
3610 b"speech" if v57 => {
3611 let text = std::str::from_utf8(rest).map_err(|_| format!("line {n}: speech is not text"))?;
3612 let f: Vec<&str> = text.split(' ').collect();
3613 doc.speech_device = f
3614 .first()
3615 .and_then(|d| crate::speech::DeviceChoice::parse(d))
3616 .ok_or_else(|| format!("line {n}: speech wants a device, auto, cpu or gpu"))?;
3617 doc.speech_model = match f.get(1) {
3618 None => None,
3619 Some(m) if crate::speech::MODELS.contains(m) && f.len() == 2 => Some(m.to_string()),
3620 Some(m) => return Err(format!("line {n}: speech model `{m}` is not one of {}", crate::speech::MODELS.join(", ")).into()),
3621 };
3622 }
3623 b"bin" if v51 => {
3624 let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect();
3625 if f.len() != 3 {
3626 return Err(format!("line {n}: bin wants an id, a parent and a name").into());
3627 }
3628 let id = number(f[0], n)?;
3629 let parent = number(f[1], n)?;
3630 let name = unescape_text(f[2], n)?;
3631 if id == 0 || doc.bins.iter().any(|b| b.id == id) {
3632 return Err(format!("line {n}: bin {id} is not a new id").into());
3633 }
3634 if parent != 0 && !doc.bins.iter().any(|b| b.id == parent && b.parent == 0) {
3635 return Err(format!("line {n}: bin {id} is inside bin {parent}, which is not a top-level bin before it").into());
3636 }
3637 let name = crate::project::clean_bin_name(&name).map_err(|e| format!("line {n}: {e}"))?;
3638 if doc.bins.iter().any(|b| b.parent == parent && b.name.eq_ignore_ascii_case(&name)) {
3639 return Err(format!("line {n}: two bins named {name} in one place").into());
3640 }
3641 if doc.bins.len() >= crate::project::MAX_BINS {
3642 return Err(format!("line {n}: a project holds at most {} bins", crate::project::MAX_BINS).into());
3643 }
3644 doc.bins.push(crate::project::Bin { id, parent, name });
3645 }
3646 b"srcbin" if v51 => {
3647 let f = fields(rest, 2, "srcbin", n)?;
3648 let (src, bin) = (number(f[0], n)? as usize, number(f[1], n)?);
3649 if !doc.bins.iter().any(|b| b.id == bin) {
3650 return Err(format!("line {n}: srcbin names bin {bin}, which is not defined before it").into());
3651 }
3652 doc.sources
3653 .get_mut(src)
3654 .ok_or_else(|| format!("line {n}: srcbin names source {src}, which the file does not have"))?
3655 .bin = bin;
3656 }
3657 b"srcfav" if v51 => {
3658 let f = fields(rest, 1, "srcfav", n)?;
3659 let src = number(f[0], n)? as usize;
3660 doc.sources
3661 .get_mut(src)
3662 .ok_or_else(|| format!("line {n}: srcfav names source {src}, which the file does not have"))?
3663 .fav = true;
3664 }
3665 b"mcam" if v47 => {
3666 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
3667 let id = number(id, n)?;
3668 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
3669 doc.mcams.push((id, name));
3670 }
3671 b"chapter" if v34 => {
3672 let mut fields = rest.splitn(2, |&b| b == b' ');
3673 let frame = number(fields.next().unwrap_or_default(), n)?;
3674 let title = unescape_text(fields.next().unwrap_or_default(), n)?;
3675 let chapter = Chapter { frame, title };
3676 check_chapter(&chapter).map_err(|e| format!("line {n}: {e}"))?;
3677 if doc.chapters.last().is_some_and(|c| c.frame >= frame) {
3678 return Err(format!("line {n}: chapter at frame {frame} is not after the one before it").into());
3679 }
3680 if doc.chapters.len() >= MAX_LIST_ENTRIES {
3681 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} chapters").into());
3682 }
3683 doc.chapters.push(chapter);
3684 }
3685 b"marker" if v36 => {
3686 let f: Vec<&[u8]> = rest.splitn(4, |&b| b == b' ').collect();
3687 if f.len() < 4 {
3688 return Err(format!("line {n}: marker wants a frame, a length, a colour and a name").into());
3689 }
3690 let color = std::str::from_utf8(f[2])
3691 .ok()
3692 .and_then(MarkerColor::from_name)
3693 .ok_or_else(|| format!("line {n}: marker names {:?}, not a colour", String::from_utf8_lossy(f[2])))?;
3694 let marker = Marker {
3695 frame: number(f[0], n)?,
3696 length: number(f[1], n)?,
3697 name: unescape_text(f[3], n)?,
3698 note: String::new(),
3699 color,
3700 };
3701 check_marker(&marker).map_err(|e| format!("line {n}: {e}"))?;
3702 if doc.markers.last().is_some_and(|m| m.frame > marker.frame) {
3703 return Err(format!("line {n}: marker at frame {} is before the one above it", marker.frame).into());
3704 }
3705 if doc.markers.len() >= MAX_LIST_ENTRIES {
3706 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} markers").into());
3707 }
3708 doc.markers.push(marker);
3709 }
3710 b"cuewords" if v40 => {
3711 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3712 if f.len() < 5 || !(f.len() - 2).is_multiple_of(3) {
3713 return Err(format!("line {n}: cuewords wants a track, a cue and whole (start, end, word) triples").into());
3714 }
3715 if (f.len() - 2) / 3 > MAX_CUE_WORDS {
3716 return Err(format!("line {n}: cuewords carries more than {MAX_CUE_WORDS} words").into());
3717 }
3718 let track = number(f[0], n)? as usize;
3719 if track >= doc.subtitles.len() {
3720 return Err(format!("line {n}: cuewords names subtitle track {track} of {}", doc.subtitles.len()).into());
3721 }
3722 let mut words = Vec::new();
3723 for w in f[2..].chunks(3) {
3724 let time = |b: &[u8]| -> crate::Result<i64> {
3725 std::str::from_utf8(b)
3726 .ok()
3727 .and_then(|t| t.parse::<i64>().ok())
3728 .ok_or_else(|| format!("line {n}: cuewords time is not a number").into())
3729 };
3730 words.push((time(w[0])?, time(w[1])?, unescape_text(w[2], n)?));
3731 }
3732 doc.cue_words.push((track, number(f[1], n)? as usize, words));
3733 }
3734 b"capstyle" if v40 => {
3735 let f: Vec<&str> = fields(rest, 5, "capstyle", n)?
3736 .into_iter()
3737 .map(|b| std::str::from_utf8(b).unwrap_or(""))
3738 .collect();
3739 let anim = CaptionAnim::from_name(f[0])
3740 .ok_or_else(|| format!("line {n}: capstyle names {:?}, not an animation", f[0]))?;
3741 let hex = f[1];
3742 let rgb = (hex.len() == 6)
3743 .then(|| u32::from_str_radix(hex, 16).ok())
3744 .flatten()
3745 .ok_or_else(|| format!("line {n}: capstyle colour {hex:?} is not six hex digits"))?;
3746 let flag = |s: &str| match s {
3747 "0" => Ok(false),
3748 "1" => Ok(true),
3749 other => Err(format!("line {n}: capstyle flag {other:?} is not 0 or 1")),
3750 };
3751 let words_per_line: u8 = f[4]
3752 .parse()
3753 .ok()
3754 .filter(|&w| w <= MAX_WORDS_PER_LINE)
3755 .ok_or_else(|| format!("line {n}: capstyle words per line {:?} is not 0 to {MAX_WORDS_PER_LINE}", f[4]))?;
3756 doc.caption_style = CaptionStyle {
3757 anim,
3758 highlight: [(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8],
3759 hl_box: flag(f[2])?,
3760 uppercase: flag(f[3])?,
3761 words_per_line,
3762 };
3763 }
3764 b"marknote" if v36 => {
3765 let mut fields = rest.splitn(2, |&b| b == b' ');
3766 let idx = number(fields.next().unwrap_or_default(), n)? as usize;
3767 let note = unescape_text(fields.next().unwrap_or_default(), n)?;
3768 let marker = doc
3769 .markers
3770 .get_mut(idx)
3771 .ok_or_else(|| format!("line {n}: marknote names marker {idx}, which the file does not have"))?;
3772 marker.note = note;
3773 check_marker(marker).map_err(|e| format!("line {n}: {e}"))?;
3774 }
3775 b"flags" if v24 => {
3776 let mut words = rest.split(|&b| b == b' ');
3777 let kind = match words.next().unwrap_or_default() {
3778 b"video" => LaneKind::Video,
3779 b"audio" => LaneKind::Audio,
3780 b"sub" => LaneKind::Subtitle,
3781 other => {
3782 return Err(format!(
3783 "line {n}: flags names {:?}, not a lane kind",
3784 String::from_utf8_lossy(other)
3785 )
3786 .into());
3787 }
3788 };
3789 let ord = number(words.next().unwrap_or_default(), n)?;
3790 let at = doc
3791 .lanes
3792 .iter()
3793 .enumerate()
3794 .filter(|(_, (k, _))| *k == kind)
3795 .nth(ord.saturating_sub(1) as usize)
3796 .map(|(at, _)| at)
3797 .ok_or_else(|| format!("line {n}: flags names a lane that is not there"))?;
3798 let mut set = LaneFlags::default();
3799 let mut any = false;
3800 for word in words {
3801 let (slot, name) = match word {
3802 b"hidden" if kind != LaneKind::Audio => (&mut set.hidden, "hidden"),
3803 b"muted" if kind == LaneKind::Audio => (&mut set.muted, "muted"),
3804 b"locked" => (&mut set.locked, "locked"),
3805 other => {
3806 return Err(format!(
3807 "line {n}: flags {:?} cannot be set on that lane",
3808 String::from_utf8_lossy(other)
3809 )
3810 .into());
3811 }
3812 };
3813 if std::mem::replace(slot, true) {
3814 return Err(format!("line {n}: flags names {name} twice").into());
3815 }
3816 any = true;
3817 }
3818 if !any {
3819 return Err(format!("line {n}: flags names no switch").into());
3820 }
3821 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
3822 set.pan = doc.flags[at].pan;
3823 doc.flags[at] = set;
3824 }
3825 // Beside the source lines and read the same way: fields first, the
3826 // path last, because a path runs to the end of the line.
3827 b"subtitle" if v10 => {
3828 let at = rest
3829 .iter()
3830 .position(|&b| b == b' ')
3831 .ok_or_else(|| format!("line {n}: subtitle without a path"))?;
3832 let track = match &rest[..at] {
3833 b"-" => None,
3834 field => Some(u64::from(number(field, n)?)),
3835 };
3836 let path = unescape(&rest[at + 1..], n)?;
3837 if path.as_os_str().is_empty() {
3838 return Err(format!("line {n}: subtitle without a path").into());
3839 }
3840 doc.subtitles.push((
3841 // Relative to the project file, as a source path is.
3842 if path.is_absolute() {
3843 path
3844 } else {
3845 dir.join(path)
3846 },
3847 track,
3848 ));
3849 }
3850 // After the subtitle lines, which declare the tracks it names. The
3851 // text is the rest of the line, so it may hold spaces: the track and
3852 // the cue are the two fields before it.
3853 b"cue" if v24 => {
3854 let mut fields = rest.splitn(3, |&b| b == b' ');
3855 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3856 let cue = number(
3857 fields
3858 .next()
3859 .ok_or_else(|| format!("line {n}: cue without a cue index"))?,
3860 n,
3861 )? as usize;
3862 let text = fields
3863 .next()
3864 .ok_or_else(|| format!("line {n}: cue without its text"))?;
3865 if track >= doc.subtitles.len() {
3866 return Err(format!(
3867 "line {n}: cue names subtitle track {track} of {}",
3868 doc.subtitles.len()
3869 )
3870 .into());
3871 }
3872 doc.cue_edits.push((track, cue, unescape_text(text, n)?));
3873 }
3874 // After the subtitle lines, which declare the tracks it names: the
3875 // track, then the language as the rest of the line, escaped as a cue's
3876 // text is. A language is one field to a reader, not a list of words.
3877 b"sublang" if v33 => {
3878 let mut fields = rest.splitn(2, |&b| b == b' ');
3879 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3880 let lang = fields
3881 .next()
3882 .ok_or_else(|| format!("line {n}: sublang without a language"))?;
3883 if track >= doc.subtitles.len() {
3884 return Err(format!(
3885 "line {n}: sublang names subtitle track {track} of {}",
3886 doc.subtitles.len()
3887 )
3888 .into());
3889 }
3890 let lang = unescape_text(lang, n)?;
3891 if lang.is_empty() {
3892 return Err(format!("line {n}: sublang without a language").into());
3893 }
3894 doc.sub_langs.push((track, lang));
3895 }
3896 // After the subtitle lines, which declare the tracks it names, and
3897 // the `cue` lines, so an added cue lands after the file's own cues.
3898 // The text is the rest of the line, as a `cue` line's is.
3899 b"cueadd" if v29 => {
3900 let mut fields = rest.splitn(4, |&b| b == b' ');
3901 let mut field = |what: &str| fields.next().ok_or_else(|| format!("line {n}: cueadd without {what}"));
3902 let track = number(field("a track")?, n)? as usize;
3903 let start_us = number64(field("a start")?, n)? as i64;
3904 let end_us = number64(field("an end")?, n)? as i64;
3905 let text = field("its text")?;
3906 if track >= doc.subtitles.len() {
3907 return Err(format!(
3908 "line {n}: cueadd names subtitle track {track} of {}",
3909 doc.subtitles.len()
3910 )
3911 .into());
3912 }
3913 if end_us <= start_us {
3914 return Err(format!("line {n}: cueadd ends at {end_us} µs, not after its start {start_us} µs").into());
3915 }
3916 doc.cue_adds.push(crate::project::AddedCue {
3917 track,
3918 start_us,
3919 end_us,
3920 text: unescape_text(text, n)?,
3921 });
3922 }
3923 b"source" => {
3924 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3925 return Err(format!("line {n}: source after a clip").into());
3926 }
3927 // The stream comes first and the path is everything after it,
3928 // spaces and all; an older dialect wrote no stream and meant 0.
3929 let (audio_stream, rest) = if streamless {
3930 (0, rest)
3931 } else {
3932 // No space at all still has to reach `number`, so a v2 line
3933 // in a v3 file is refused as the missing field it is rather
3934 // than as a missing path.
3935 let at = rest.iter().position(|&b| b == b' ');
3936 (
3937 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
3938 &rest[at.map_or(rest.len(), |at| at + 1)..],
3939 )
3940 };
3941 if rest.is_empty() {
3942 return Err(format!("line {n}: source without a path").into());
3943 }
3944 let path = unescape(rest, n)?;
3945 // Relative means "next to the project file", which is what
3946 // makes a whole folder relocatable.
3947 doc.sources.push(Source {
3948 path: if path.is_absolute() {
3949 path
3950 } else {
3951 dir.join(path)
3952 },
3953 audio_stream,
3954 ..Default::default()
3955 });
3956 }
3957 b"eq" if v5 => {
3958 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3959 return Err(format!("line {n}: eq after a clip").into());
3960 }
3961 // A bare `eq` is the empty cascade -- a setting that moves
3962 // nothing, which is not the same thing as no setting at all.
3963 if rest.split(|&b| b == b' ').count() > MAX_EQ_BANDS {
3964 return Err(format!("line {n}: an equalizer holds at most {MAX_EQ_BANDS} bands").into());
3965 }
3966 let bands = match rest.is_empty() {
3967 true => Vec::new(),
3968 false => rest
3969 .split(|&b| b == b' ')
3970 .map(|field| band(field, n))
3971 .collect::<crate::Result<Vec<Band>>>()?,
3972 };
3973 doc.eq.push(EqParams { bands });
3974 }
3975 b"color" if v6 => {
3976 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3977 return Err(format!("line {n}: color after a clip").into());
3978 }
3979 let f = fields(rest, 1, "color", n)?;
3980 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
3981 if parts.len() != 4 {
3982 return Err(
3983 format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
3984 );
3985 }
3986 doc.color.push(ColorParams {
3987 brightness: float(parts[0], n)?,
3988 contrast: float(parts[1], n)?,
3989 saturation: float(parts[2], n)?,
3990 tint: float(parts[3], n)?,
3991 ..Default::default()
3992 });
3993 }
3994 b"transform" if v20 => {
3995 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3996 return Err(format!("line {n}: transform after a clip").into());
3997 }
3998 let f = fields(rest, 1, "transform", n)?;
3999 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
4000 // v31 may add the opacity as a ninth field; an earlier dialect
4001 // has eight, and a ninth there is a line it never wrote.
4002 let want = if v31 { 8..=9 } else { 8..=8 };
4003 if !want.contains(&parts.len()) {
4004 return Err(format!(
4005 "line {n}: transform wants 8 fields, found {}",
4006 parts.len()
4007 )
4008 .into());
4009 }
4010 let opacity = match parts.get(8) {
4011 Some(p) => float(p, n)?,
4012 None => 1.0,
4013 };
4014 if !(0.0..=1.0).contains(&opacity) {
4015 return Err(format!("line {n}: transform opacity must be 0..=1").into());
4016 }
4017 doc.transform.push(TransformParams {
4018 pos_x: float(parts[0], n)?,
4019 pos_y: float(parts[1], n)?,
4020 scale: float(parts[2], n)?,
4021 rotate: float(parts[3], n)?,
4022 crop_l: float(parts[4], n)?,
4023 crop_r: float(parts[5], n)?,
4024 crop_t: float(parts[6], n)?,
4025 crop_b: float(parts[7], n)?,
4026 opacity,
4027 });
4028 }
4029 // v1: one lane, no placement, no groups. Every clip becomes one
4030 // grouped video+audio pair laid where the queue reached, which is
4031 // what the file always meant.
4032 b"clip" if v1 => {
4033 let f = fields(rest, 3, "clip", n)?;
4034 let clip = check(
4035 Clip {
4036 speed_keys: Vec::new(),
4037 reversed: false,
4038 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4039 angle: Default::default(),
4040 fade_in: 0,
4041 fade_out: 0,
4042 transition_out: 0,
4043 transition_kind: Default::default(),
4044 visualizer: 0,
4045 viz_paint: 0,
4046 gain_db: 0.0,
4047 gain_keys: Vec::new(),
4048 pan: 0,
4049 transform_keys: Vec::new(),
4050 opacity_keys: Vec::new(),
4051 color_keys: Vec::new(),
4052 effects: Vec::new(),
4053 start: queued,
4054 in_frame: number(f[0], n)?,
4055 out_frame: number(f[1], n)?,
4056 source: number(f[2], n)? as usize,
4057 link: Some(doc.lanes[0].1.len() as u32),
4058 eq: None,
4059 color: None,
4060 transform: None,
4061 fit: FitPolicy::default(),
4062 speed: Speed::NORMAL,
4063 pitch: 0,
4064 },
4065 &doc,
4066 n,
4067 )?;
4068 queued = clip.end();
4069 doc.lanes[0].1.push(clip.clone());
4070 doc.lanes[1].1.push(clip);
4071 }
4072 // A lane line like the two below it, in its place among them, and
4073 // read into `subs` rather than into the clips: the lane holds
4074 // words, and no media path may ever meet one
4075 // ([`crate::project::LaneKind::Subtitle`]).
4076 b"sub" if v15 => {
4077 let at = rest.iter().position(|&b| b == b' ');
4078 let ord = number(&rest[..at.unwrap_or(rest.len())], n)?;
4079 let rest = &rest[at.map_or(rest.len(), |at| at + 1)..];
4080 let at = lane_of(&mut doc.lanes, LaneKind::Subtitle, ord, n)?;
4081 doc.subs.resize(doc.lanes.len(), Vec::new());
4082 // The bare line is the empty lane's whole existence, exactly as
4083 // it is for a video one.
4084 if rest.is_empty() {
4085 continue;
4086 }
4087 // v16 on may carry a sixth field -- the caption's group id, the
4088 // same spelling a clip's link takes (`-` for none). A v15 line
4089 // stops at five, and a sixth field in one is a file this parser
4090 // never wrote.
4091 let all: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4092 let ok = all.len() == 5 || (v16 && all.len() == 6);
4093 if !ok {
4094 return Err(format!(
4095 "line {n}: sub wants {} fields, found {}",
4096 if v16 { "5 or 6" } else { "5" },
4097 all.len()
4098 )
4099 .into());
4100 }
4101 let link = match all.get(5) {
4102 None => None,
4103 Some(f) if *f == b"-" => None,
4104 Some(f) => Some(number(f, n)?),
4105 };
4106 let f = &all;
4107 let sub = SubClip {
4108 start: number(f[0], n)?,
4109 frames: number(f[1], n)?,
4110 track: number(f[2], n)? as usize,
4111 in_us: micros(f[3], n)?,
4112 out_us: micros(f[4], n)?,
4113 link,
4114 };
4115 // The never-empty invariant at both clocks, which is what
4116 // [`crate::Project::place_sub`] refuses on the live timeline.
4117 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
4118 return Err(format!(
4119 "line {n}: caption at {} is empty: {} frames of [{}, {})",
4120 sub.start, sub.frames, sub.in_us, sub.out_us
4121 )
4122 .into());
4123 }
4124 // The width of that window, which the check above cannot see:
4125 // it asks whether the window is *open*, never how wide it is,
4126 // and a `sub` line is the one number in this format a hand (or
4127 // a hostile actor) can set to `i64::MAX` and have accepted.
4128 // Every cut, split, ripple and group trim re-derives the two
4129 // halves of the window by proportion
4130 // ([`crate::project::SubClip::window_at`]), a multiply that
4131 // overflowed on the first frame inside the caption -- a panic
4132 // on the UI thread the first time a hand ripple-deleted across
4133 // it, and in a release build a silently wrapped clock. The
4134 // same bound [`crate::is_resolution`] holds a `resolution`
4135 // line to, and for the same reason: refused by name at the
4136 // door rather than clamped into something nobody wrote.
4137 if sub.out_us - sub.in_us > crate::project::MAX_WINDOW_US {
4138 return Err(format!(
4139 "line {n}: caption at {} is a {}us window, past the {}us a caption can hold",
4140 sub.start,
4141 sub.out_us - sub.in_us,
4142 crate::project::MAX_WINDOW_US
4143 )
4144 .into());
4145 }
4146 // The palette bound, which is a clip's source bound for words:
4147 // the `subtitle` lines are written before these and a caption
4148 // names one of them by position.
4149 if sub.track >= doc.subtitles.len() {
4150 return Err(format!(
4151 "line {n}: caption names subtitle track {} of {}",
4152 sub.track,
4153 doc.subtitles.len()
4154 )
4155 .into());
4156 }
4157 if sub.start.checked_add(sub.frames).is_none() {
4158 return Err(format!(
4159 "line {n}: caption at {} runs past the last frame there is",
4160 sub.start
4161 )
4162 .into());
4163 }
4164 let lane = &mut doc.subs[at];
4165 if lane.last().is_some_and(|prev| prev.end() > sub.start) {
4166 return Err(format!(
4167 "line {n}: caption at {} overlaps the one before it, or comes before it",
4168 sub.start
4169 )
4170 .into());
4171 }
4172 lane.push(sub);
4173 }
4174 b"video" | b"audio" if !v1 => {
4175 let kind = match keyword {
4176 b"video" => LaneKind::Video,
4177 _ => LaneKind::Audio,
4178 };
4179 // v4 on names the lane, and a line naming nothing else is an
4180 // empty lane's whole existence. Older dialects had one lane per
4181 // kind.
4182 let (ord, rest) = if numbered {
4183 let at = rest.iter().position(|&b| b == b' ');
4184 (
4185 number(&rest[..at.unwrap_or(rest.len())], n)?,
4186 &rest[at.map_or(rest.len(), |at| at + 1)..],
4187 )
4188 } else {
4189 (1, rest)
4190 };
4191 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
4192 if numbered && rest.is_empty() {
4193 continue;
4194 }
4195 // v20 grew the transform field, v18 the two fade fields, v19
4196 // the transition one, v8 the speed one, v7 the fit one, v6
4197 // the colour one and v5 the eq one; every older dialect ends
4198 // at the link.
4199 let want = 5
4200 + usize::from(v5)
4201 + usize::from(v6)
4202 + usize::from(v7)
4203 + usize::from(v8)
4204 + 2 * usize::from(v18)
4205 + usize::from(v19)
4206 + usize::from(v20)
4207 + usize::from(v21)
4208 + usize::from(v22);
4209 let f = fields(rest, want, "clip", n)?;
4210 let in_frame = number(f[1], n)?;
4211 let out_frame = number(f[2], n)?;
4212 let speed = speed_of(f.get(8).copied(), n)?;
4213 // Clamped to the clip's own timeline length,
4214 // [`Project::set_fade_in`]'s rule: a crafted or hand-edited
4215 // file asking for more ramp than the clip has frames gets the
4216 // clip's whole length rather than a refusal.
4217 // A v35 clip's ramp comes on a later line and may lengthen it, so its
4218 // fades are clamped once the ramps are in (after the last line).
4219 let frames = if v35 {
4220 u32::MAX
4221 } else {
4222 speed.frames(out_frame.saturating_sub(in_frame))
4223 };
4224 let clip = check(
4225 Clip {
4226 speed_keys: Vec::new(),
4227 reversed: false,
4228 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4229 angle: Default::default(),
4230 fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames),
4231 fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames),
4232 transition_out: number(f.get(11).copied().unwrap_or(b"0"), n)?.min(frames),
4233 transition_kind: Default::default(),
4234 visualizer: flags_byte(f.get(13).copied().unwrap_or(b"0"), n)?,
4235 viz_paint: number64(f.get(14).copied().unwrap_or(b"0"), n)?,
4236 gain_db: 0.0,
4237 gain_keys: Vec::new(),
4238 pan: 0,
4239 transform_keys: Vec::new(),
4240 opacity_keys: Vec::new(),
4241 color_keys: Vec::new(),
4242 effects: Vec::new(),
4243 start: number(f[0], n)?,
4244 in_frame,
4245 out_frame,
4246 source: number(f[3], n)? as usize,
4247 link: match f[4] {
4248 b"-" => None,
4249 field => Some(number(field, n)?),
4250 },
4251 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
4252 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
4253 transform: table_index(
4254 f.get(12).copied(),
4255 doc.transform.len(),
4256 "transform",
4257 n,
4258 )?,
4259 fit: fit_policy(f.get(7).copied(), n)?,
4260 speed,
4261 pitch: 0,
4262 },
4263 &doc,
4264 n,
4265 )?;
4266 let lane = &mut doc.lanes[at].1;
4267 // The sorted, non-overlapping placement invariant, checked at
4268 // the only door untrusted clips come in through.
4269 // A v35 file's `speedkeys` lines follow the clips, so a ramped clip still
4270 // has its constant footprint here, which a shorter ramp undercuts: only
4271 // the order is checked at this door, and the footprints after the last line.
4272 let behind = |prev: &Clip| {
4273 if v35 {
4274 prev.start >= clip.start
4275 } else {
4276 prev.end() > clip.start
4277 }
4278 };
4279 if lane.last().is_some_and(behind) {
4280 return Err(format!(
4281 "line {n}: clip at {} overlaps the one before it, or comes before it",
4282 clip.start
4283 )
4284 .into());
4285 }
4286 lane.push(clip);
4287 }
4288 // Empty lines land here too: nothing in this format is optional
4289 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
4290 // is a file mixing dialects, and is refused the same way.
4291 _ => {
4292 return Err(format!(
4293 "line {n}: unknown keyword {:?}",
4294 String::from_utf8_lossy(keyword)
4295 )
4296 .into());
4297 }
4298 }
4299 }
4300 // The ramps are in now: every clip ends before the next one starts.
4301 if v35 {
4302 for (_, clips) in &mut doc.lanes {
4303 for c in clips.iter_mut() {
4304 let frames = c.frames();
4305 c.fade_in = c.fade_in.min(frames);
4306 c.fade_out = c.fade_out.min(frames);
4307 c.transition_out = c.transition_out.min(frames);
4308 }
4309 if let Some(w) = clips.windows(2).find(|w| w[0].end() > w[1].start) {
4310 return Err(format!("clip at {} overlaps the one before it", w[1].start).into());
4311 }
4312 }
4313 }
4314 if block.is_some() {
4315 return Err("a sequence block never ends: the file is cut short".into());
4316 }
4317 // One per lane whatever the file said, so a caller may zip the two -- and
4318 // the same for the placements, whose lanes are the very same list.
4319 doc.gains.resize(doc.lanes.len(), 0.0);
4320 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
4321 doc.ducks.resize(doc.lanes.len(), Vec::new());
4322 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4323 doc.names.resize(doc.lanes.len(), String::new());
4324 doc.subs.resize(doc.lanes.len(), Vec::new());
4325 // A key is another audio lane of this file, named by its position among
4326 // them, and never the lane it ducks: a file that says otherwise would ask
4327 // the mixer to duck under nothing.
4328 let audio_lanes = doc
4329 .lanes
4330 .iter()
4331 .filter(|(k, _)| *k == LaneKind::Audio)
4332 .count();
4333 for (i, lane_ducks) in doc.ducks.iter().enumerate() {
4334 let own_ord = doc.lanes[..i]
4335 .iter()
4336 .filter(|(k, _)| *k == LaneKind::Audio)
4337 .count();
4338 for duck in lane_ducks {
4339 if duck.under >= audio_lanes || duck.under == own_ord {
4340 return Err(format!(
4341 "duck names audio lane {}, which is not another audio lane of this project",
4342 duck.under + 1
4343 )
4344 .into());
4345 }
4346 }
4347 }
4348 // A file whose lanes are all empty *is* a project -- the emptied timeline,
4349 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
4350 // refuses that one, by the name it has there.
4351 Ok(doc)
4352}
4353
4354/// Where the lane a v4 line names sits, appending it if this is its first line.
4355/// Lanes arrive in display order, so a number that skips one of its kind is a
4356/// lane that was never declared, and is refused by the name it would have had.
4357fn lane_of(
4358 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
4359 kind: LaneKind,
4360 ord: u32,
4361 line: usize,
4362) -> crate::Result<usize> {
4363 let mut seen = 0;
4364 for (at, (k, _)) in lanes.iter().enumerate() {
4365 if *k == kind {
4366 seen += 1;
4367 if seen == ord {
4368 return Ok(at);
4369 }
4370 }
4371 }
4372 if ord != seen + 1 {
4373 return Err(match ord.checked_sub(1) {
4374 Some(prev) => format!(
4375 "line {line}: lane {} comes before {}",
4376 Lane::new(kind, prev as usize).label(),
4377 Lane::new(kind, seen as usize).label()
4378 ),
4379 None => format!("line {line}: lane numbers start at 1"),
4380 }
4381 .into());
4382 }
4383 lanes.push((kind, Vec::new()));
4384 Ok(lanes.len() - 1)
4385}
4386
4387/// Splits a line's fields, refusing the wrong count by name.
4388fn fields<'a>(
4389 rest: &'a [u8],
4390 want: usize,
4391 what: &str,
4392 line: usize,
4393) -> crate::Result<Vec<&'a [u8]>> {
4394 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4395 if fields.len() != want {
4396 return Err(format!(
4397 "line {line}: {what} wants {want} fields, found {}",
4398 fields.len()
4399 )
4400 .into());
4401 }
4402 Ok(fields)
4403}
4404
4405/// The per-clip structure checks both dialects share.
4406fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
4407 if clip.out_frame <= clip.in_frame {
4408 return Err(format!(
4409 "line {line}: clip [{}, {}) is empty",
4410 clip.in_frame, clip.out_frame
4411 )
4412 .into());
4413 }
4414 if clip.source >= doc.sources.len() && !crate::project::is_sequence_source(clip.source) {
4415 return Err(format!(
4416 "line {line}: clip names source {} of {}",
4417 clip.source,
4418 doc.sources.len()
4419 )
4420 .into());
4421 }
4422 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
4423 // adds `start + len` as plain `u32`, which panics in debug and wraps in
4424 // release on a crafted file. Bound it here, at the door.
4425 if clip.start.checked_add(clip.frames()).is_none() {
4426 return Err(format!(
4427 "line {line}: clip at {} runs past the last frame there is",
4428 clip.start
4429 )
4430 .into());
4431 }
4432 Ok(clip)
4433}
4434
4435/// A clip's `<speed>` field: thousandths of real time, as
4436/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A
4437/// dialect with no such field (everything before v8) means real time, which is
4438/// what such a project always played at. A number outside the range the editor
4439/// can set is *refused* rather than clamped: a project file is generated, so
4440/// that is a corrupt line and not a dialect.
4441fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result<Speed> {
4442 let Some(field) = field else {
4443 return Ok(Speed::NORMAL);
4444 };
4445 let permille = number(field, line)?;
4446 let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16);
4447 if u32::from(speed.permille()) != permille {
4448 return Err(format!(
4449 "line {line}: speed {permille} is outside {}-{} thousandths",
4450 Speed::MIN.permille(),
4451 Speed::MAX.permille()
4452 )
4453 .into());
4454 }
4455 Ok(speed)
4456}
4457
4458/// How a fit policy is spelled in the file. One word each, so a clip line stays
4459/// readable, and the same word the parser takes back.
4460fn fit_name(fit: FitPolicy) -> &'static str {
4461 match fit {
4462 FitPolicy::Fit => "fit",
4463 FitPolicy::Fill => "fill",
4464 FitPolicy::Stretch => "stretch",
4465 FitPolicy::Center => "center",
4466 }
4467}
4468
4469/// A clip's `<fit>` field. A dialect that has no such field at all means the
4470/// default -- those projects held one resolution, so no clip of theirs was ever
4471/// placed on anything.
4472fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
4473 let Some(field) = field else {
4474 return Ok(FitPolicy::default());
4475 };
4476 match field {
4477 b"fit" => Ok(FitPolicy::Fit),
4478 b"fill" => Ok(FitPolicy::Fill),
4479 b"stretch" => Ok(FitPolicy::Stretch),
4480 b"center" => Ok(FitPolicy::Center),
4481 other => Err(format!(
4482 "line {line}: {:?} is not a fit policy",
4483 String::from_utf8_lossy(other)
4484 )
4485 .into()),
4486 }
4487}
4488
4489/// An `effect` line (v42): see [`effect_lines`]. The kind must be one, the switch `0` or
4490/// `1`, every value in its range and a clip's stack no longer than
4491/// [`crate::effects::MAX_EFFECTS`].
4492fn parse_effect(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4493 use crate::effects::{Effect, EffectKind, MAX_EFFECTS, MAX_PARAMS};
4494 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4495 if f.len() < 5 || f[0] != b"video" {
4496 return Err(format!("line {n}: effect wants a video clip, a kind and a switch").into());
4497 }
4498 let ord = number(f[1], n)?;
4499 let at = doc
4500 .lanes
4501 .iter()
4502 .enumerate()
4503 .filter(|(_, (k, _))| *k == LaneKind::Video)
4504 .nth(ord.saturating_sub(1) as usize)
4505 .map(|(at, _)| at)
4506 .ok_or_else(|| format!("line {n}: effect names a lane that is not there"))?;
4507 let idx = number(f[2], n)? as usize;
4508 let name = String::from_utf8_lossy(f[3]);
4509 let kind = EffectKind::from_name(&name).ok_or_else(|| format!("line {n}: effect {name:?} is not one"))?;
4510 let on = match f[4] {
4511 b"1" => true,
4512 b"0" => false,
4513 _ => return Err(format!("line {n}: effect switch is not 0 or 1").into()),
4514 };
4515 let specs = kind.params();
4516 if f.len() - 5 != specs.len() {
4517 return Err(format!("line {n}: effect {name} wants {} values, found {}", specs.len(), f.len() - 5).into());
4518 }
4519 let mut values = [0.0; MAX_PARAMS];
4520 for ((v, field), spec) in values.iter_mut().zip(&f[5..]).zip(specs) {
4521 *v = float(field, n)?;
4522 if !(spec.min..=spec.max).contains(v) {
4523 return Err(format!("line {n}: effect {name} {} is out of its range", spec.name).into());
4524 }
4525 }
4526 let clip = doc.lanes[at]
4527 .1
4528 .get_mut(idx)
4529 .ok_or_else(|| format!("line {n}: effect names clip {idx}, which the lane does not have"))?;
4530 if clip.effects.len() >= MAX_EFFECTS {
4531 return Err(format!("line {n}: a clip holds at most {MAX_EFFECTS} effects").into());
4532 }
4533 clip.effects.push(Effect { kind, on, values, keys: Vec::new() });
4534 Ok(())
4535}
4536
4537/// A `voice` line (v41): see [`voice_lines`]. Every number is range-checked the way the
4538/// setter clamps it, and a noise reduction that is on must carry its profile.
4539fn parse_voice(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4540 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4541 if f.len() < 3 {
4542 return Err(format!("line {n}: voice wants a lane, a number and a processor").into());
4543 }
4544 if f[0] != b"audio" {
4545 return Err(format!("line {n}: voice names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
4546 }
4547 let ord = number(f[1], n)?;
4548 let at = doc
4549 .lanes
4550 .iter()
4551 .enumerate()
4552 .filter(|(_, (k, _))| *k == LaneKind::Audio)
4553 .nth(ord.saturating_sub(1) as usize)
4554 .map(|(at, _)| at)
4555 .ok_or_else(|| format!("line {n}: voice names a lane that is not there"))?;
4556 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4557 let flag = |field: &[u8]| match field {
4558 b"0" => Ok(false),
4559 b"1" => Ok(true),
4560 _ => Err(format!("line {n}: {:?} is not 0 or 1", String::from_utf8_lossy(field))),
4561 };
4562 let want = |count: usize, what: &str| {
4563 if f.len() == count + 3 {
4564 Ok(())
4565 } else {
4566 Err(format!("line {n}: voice {what} wants {count} fields, found {}", f.len() - 3))
4567 }
4568 };
4569 let range = || format!("line {n}: voice has a number out of its range");
4570 let voice = &mut doc.voices[at];
4571 match f[2] {
4572 b"gate" => {
4573 want(6, "gate")?;
4574 let g = Gate {
4575 on: flag(f[3])?,
4576 threshold_db: float(f[4], n)?,
4577 attack_ms: float(f[5], n)?,
4578 release_ms: float(f[6], n)?,
4579 hold_ms: float(f[7], n)?,
4580 range_db: float(f[8], n)?,
4581 };
4582 if g.clamped() != Some(g) {
4583 return Err(range().into());
4584 }
4585 voice.gate = g;
4586 }
4587 b"nr" => {
4588 want(4, "nr")?;
4589 let profile = match f[6] {
4590 b"-" => Vec::new(),
4591 list => list.split(|&b| b == b',').map(|v| float(v, n)).collect::<crate::Result<Vec<f32>>>()?,
4592 };
4593 let nr = NoiseReduction { on: flag(f[3])?, strength: float(f[4], n)?, floor_db: float(f[5], n)?, profile };
4594 if nr.clamped().as_ref() != Some(&nr) {
4595 return Err(range().into());
4596 }
4597 if nr.on && nr.profile.is_empty() {
4598 return Err(format!("line {n}: voice nr is on but has no noise profile").into());
4599 }
4600 voice.nr = nr;
4601 }
4602 b"comp" => {
4603 want(8, "comp")?;
4604 let c = Compressor {
4605 on: flag(f[3])?,
4606 threshold_db: float(f[4], n)?,
4607 ratio: float(f[5], n)?,
4608 attack_ms: float(f[6], n)?,
4609 release_ms: float(f[7], n)?,
4610 knee_db: float(f[8], n)?,
4611 makeup_db: float(f[9], n)?,
4612 auto_makeup: flag(f[10])?,
4613 };
4614 if c.clamped() != Some(c) {
4615 return Err(range().into());
4616 }
4617 voice.comp = c;
4618 }
4619 b"deess" => {
4620 want(5, "deess")?;
4621 let d = DeEsser {
4622 on: flag(f[3])?,
4623 threshold_db: float(f[4], n)?,
4624 amount: float(f[5], n)?,
4625 lo_hz: float(f[6], n)?,
4626 hi_hz: float(f[7], n)?,
4627 };
4628 if d.clamped() != Some(d) {
4629 return Err(range().into());
4630 }
4631 voice.deess = d;
4632 }
4633 other => {
4634 return Err(format!("line {n}: voice names {:?}, not a processor", String::from_utf8_lossy(other)).into());
4635 }
4636 }
4637 Ok(())
4638}
4639
4640/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
4641/// at all), or a line of a table that is already declared. Refused by the name
4642/// of what it points at, so the message reads as the file does.
4643fn table_index(
4644 field: Option<&[u8]>,
4645 len: usize,
4646 what: &str,
4647 line: usize,
4648) -> crate::Result<Option<u16>> {
4649 let field = match field {
4650 None | Some(b"-") => return Ok(None),
4651 Some(field) => field,
4652 };
4653 let i = number(field, line)?;
4654 if i as usize >= len || i > u32::from(u16::MAX) {
4655 return Err(format!("line {line}: clip names {what} {i} of {len}").into());
4656 }
4657 Ok(Some(i as u16))
4658}
4659
4660/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
4661fn band(field: &[u8], line: usize) -> crate::Result<Band> {
4662 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
4663 if parts.len() != 4 {
4664 return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
4665 }
4666 Ok(Band {
4667 freq_hz: float(parts[0], line)?,
4668 gain_db: float(parts[1], line)?,
4669 q: float(parts[2], line)?,
4670 kind: match parts[3] {
4671 b"ls" => BandKind::LowShelf,
4672 b"pk" => BandKind::Peak,
4673 b"hs" => BandKind::HighShelf,
4674 b"lc" => BandKind::LowCut,
4675 b"hc" => BandKind::HighCut,
4676 other => {
4677 return Err(format!(
4678 "line {line}: {:?} is not a band shape",
4679 String::from_utf8_lossy(other)
4680 )
4681 .into());
4682 }
4683 },
4684 })
4685}
4686
4687/// The `at:ease:values` points of an `mkeys` or `ekeys` line (`name`), in source order.
4688/// Each point holds one value per spec in `specs`, each within that spec's range, and the
4689/// rest of the key is zero. A custom bezier ease is read only from v56 on, and at most
4690/// [`MAX_TRANSFORM_KEYS`] points are read.
4691fn read_effect_keys(
4692 name: &str,
4693 points: &[&[u8]],
4694 specs: &[crate::effects::ParamSpec],
4695 n: usize,
4696 v56: bool,
4697) -> crate::Result<Vec<crate::effects::EffectKey>> {
4698 if points.len() > MAX_TRANSFORM_KEYS {
4699 return Err(format!("line {n}: {name} has more than {MAX_TRANSFORM_KEYS} keys").into());
4700 }
4701 let mut keys: Vec<crate::effects::EffectKey> = Vec::new();
4702 for point in points {
4703 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
4704 if parts.len() != 3 {
4705 return Err(format!("line {n}: {name} key wants at:ease:values").into());
4706 }
4707 let at = number(parts[0], n)?;
4708 let ease = KeyEase::from_token(parts[1])
4709 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
4710 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease, hold or a bezier curve"))?;
4711 if keys.last().is_some_and(|k| k.at >= at) {
4712 return Err(format!("line {n}: {name} keys are not in source order").into());
4713 }
4714 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
4715 if v.len() != specs.len() {
4716 return Err(format!("line {n}: {name} key wants {} values", specs.len()).into());
4717 }
4718 let mut values = [0.0f32; crate::effects::MAX_PARAMS];
4719 for (i, (x, field)) in values.iter_mut().zip(&v).enumerate() {
4720 *x = float(field, n)?;
4721 if !(specs[i].min..=specs[i].max).contains(x) {
4722 return Err(format!("line {n}: {name} {} is out of its range", specs[i].name).into());
4723 }
4724 }
4725 keys.push(crate::effects::EffectKey { at, values, ease });
4726 }
4727 Ok(keys)
4728}
4729
4730/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
4731/// and NaN are refused rather than carried -- they are the values a coefficient
4732/// cannot be built from, and the ones that would not compare equal to
4733/// themselves on the way back.
4734fn float(field: &[u8], line: usize) -> crate::Result<f32> {
4735 match std::str::from_utf8(field)
4736 .ok()
4737 .and_then(|s| s.parse::<f32>().ok())
4738 .filter(|f| f.is_finite())
4739 {
4740 Some(f) => Ok(f),
4741 None => Err(format!(
4742 "line {line}: {:?} is not a number",
4743 String::from_utf8_lossy(field)
4744 )
4745 .into()),
4746 }
4747}
4748
4749/// A clip's visualizer field: every bit of the byte is a flag
4750/// ([`crate::decode::VIZ_STYLE_FILL`]'s low bits, the fast bit, the ink
4751/// nibble), so a line naming one past what a byte holds is a look this
4752/// program does not have rather than a 300 that quietly loads as a 44.
4753fn flags_byte(field: &[u8], line: usize) -> crate::Result<u8> {
4754 let n = number(field, line)?;
4755 u8::try_from(n).map_err(|_| format!("line {line}: {n} is not a set of visualizer flags").into())
4756}
4757
4758fn number(field: &[u8], line: usize) -> crate::Result<u32> {
4759 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4760 Some(n) => Ok(n),
4761 None => Err(format!(
4762 "line {line}: {:?} is not a number",
4763 String::from_utf8_lossy(field)
4764 )
4765 .into()),
4766 }
4767}
4768
4769/// [`number`] for the one field wider than a `u32`: the clip's packed
4770/// visualizer look, whose strand-colour half needs the width (v23).
4771fn number64(field: &[u8], line: usize) -> crate::Result<u64> {
4772 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4773 Some(n) => Ok(n),
4774 None => Err(format!(
4775 "line {line}: {:?} is not a number",
4776 String::from_utf8_lossy(field)
4777 )
4778 .into()),
4779 }
4780}
4781
4782/// A `sub` line's window field: microseconds, which is the clock a cue is timed
4783/// in ([`crate::subtitle::Cue`]) and the one thing in this format counted in
4784/// something other than frames. Signed as the cues are, and the negative half
4785/// is refused by the never-empty check at the line, not here.
4786fn micros(field: &[u8], line: usize) -> crate::Result<i64> {
4787 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4788 Some(n) => Ok(n),
4789 None => Err(format!(
4790 "line {line}: {:?} is not a number",
4791 String::from_utf8_lossy(field)
4792 )
4793 .into()),
4794 }
4795}
4796
4797/// A `cue` line's text: the backslash that escapes it and the two line breaks,
4798/// which are the only bytes a line cannot hold (and `\r` is spelled too, so a
4799/// text ending in one does not look like a CRLF file to a hand-editor).
4800fn escape_text(text: &str, out: &mut Vec<u8>) {
4801 for c in text.chars() {
4802 match c {
4803 '\\' => out.extend_from_slice(b"\\\\"),
4804 '\n' => out.extend_from_slice(b"\\n"),
4805 '\r' => out.extend_from_slice(b"\\r"),
4806 c => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
4807 }
4808 }
4809}
4810
4811/// Undoes [`escape_text`]. Anything but the three escapes is refused by name,
4812/// so a hand-edited typo does not quietly become a different word.
4813fn unescape_text(field: &[u8], line: usize) -> crate::Result<String> {
4814 let mut out = Vec::with_capacity(field.len());
4815 let mut bytes = field.iter().copied();
4816 while let Some(b) = bytes.next() {
4817 if b != b'\\' {
4818 out.push(b);
4819 continue;
4820 }
4821 match bytes.next() {
4822 Some(b'\\') => out.push(b'\\'),
4823 Some(b'n') => out.push(b'\n'),
4824 Some(b'r') => out.push(b'\r'),
4825 _ => return Err(format!("line {line}: cue text has a bad escape").into()),
4826 }
4827 }
4828 String::from_utf8(out)
4829 .map_err(|_| -> crate::Error { format!("line {line}: cue text is not UTF-8").into() })
4830}
4831
4832/// The two bytes a line-based format cannot hold, and the escape byte itself.
4833fn escape(path: &Path, out: &mut Vec<u8>) {
4834 for &b in path.as_os_str().as_bytes() {
4835 match b {
4836 b'%' => out.extend_from_slice(b"%25"),
4837 b'\n' => out.extend_from_slice(b"%0A"),
4838 _ => out.push(b),
4839 }
4840 }
4841}
4842
4843/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
4844/// may spell a space or a quote that way, and there is no reason to refuse it.
4845fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
4846 let mut out = Vec::with_capacity(field.len());
4847 let mut i = 0;
4848 while i < field.len() {
4849 if field[i] != b'%' {
4850 out.push(field[i]);
4851 i += 1;
4852 continue;
4853 }
4854 let byte = field
4855 .get(i + 1..i + 3)
4856 .and_then(|h| std::str::from_utf8(h).ok())
4857 .and_then(|h| u8::from_str_radix(h, 16).ok())
4858 .ok_or_else(|| -> crate::Error {
4859 format!("line {line}: truncated % escape in the path").into()
4860 })?;
4861 out.push(byte);
4862 i += 3;
4863 }
4864 Ok(PathBuf::from(OsString::from_vec(out)))
4865}
4866
4867#[cfg(test)]
4868mod tests {
4869 use super::*;
4870
4871 /// [`super::emit`] for a project whose mix is flat: every lane at unity, no
4872 /// limiter, no rate written. Shadows the real one for the tests that were
4873 /// written before there was a mix to write -- the dialect they are about is
4874 /// the one this emits, and a v9 file with flat settings is a v8 file bar
4875 /// its version line, which is exactly what they assert.
4876 #[allow(clippy::too_many_arguments)]
4877 fn emit(
4878 dir: &Path,
4879 sources: &[Source],
4880 lanes: &[(LaneKind, Vec<Clip>)],
4881 eq: &[EqParams],
4882 color: &[ColorParams],
4883 resolution: (u32, u32),
4884 playhead: u32,
4885 ) -> Vec<u8> {
4886 super::emit(
4887 dir,
4888 sources,
4889 lanes,
4890 &[],
4891 &[],
4892 &[],
4893 eq,
4894 color,
4895 &[],
4896 resolution,
4897 None,
4898 crate::tonemap::Preset::default(),
4899 false,
4900 true,
4901 crate::export::EncoderSeat::default(),
4902 Limiter::default(),
4903 None,
4904 playhead,
4905 )
4906 }
4907
4908 /// A subtitle track as a save hands one over: the cues are not written and
4909 /// so are not here either.
4910 fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack {
4911 SubtitleTrack {
4912 path: PathBuf::from(path),
4913 track,
4914 language: String::new(),
4915 name: String::new(),
4916 label: String::new(),
4917 cues: Vec::new(),
4918 bitmap: false,
4919 refused: None,
4920 }
4921 }
4922
4923 /// The v24 `cue` line: a retyped cue's words escape the backslash and the
4924 /// two line breaks, come back exactly, and a line that names no track it
4925 /// has, or spells an escape it does not know, is refused by name.
4926 #[test]
4927 fn cue_lines_round_trip_their_text_and_refuse_what_they_cannot_name() {
4928 let dir = PathBuf::from("/proj");
4929 let doc = parse(
4930 b"edith 24\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
4931 cue 0 2 a \\\\ b\\nc\\r\\nd\ncue 0 0 \n",
4932 &dir,
4933 )
4934 .expect("two cue lines parse");
4935 assert_eq!(
4936 doc.cue_edits,
4937 [(0, 2, "a \\ b\nc\r\nd".to_string()), (0, 0, String::new())]
4938 );
4939
4940 // The writer's own spelling reads back as the same text, whatever is in it.
4941 let text = "back\\slash\nnew\rline \\n is not a newline";
4942 let mut out = Vec::new();
4943 escape_text(text, &mut out);
4944 assert_eq!(unescape_text(&out, 1).expect("its own escapes"), text);
4945
4946 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
4947 let head = b"edith 24\nsubtitle - subs.srt\n";
4948 let with = |line: &[u8]| [head.as_slice(), line].concat();
4949 assert!(refuse(&with(b"cue 1 0 x\n")).contains("names subtitle track 1 of 1"));
4950 assert!(refuse(&with(b"cue 0 0 \\q\n")).contains("bad escape"));
4951 assert!(refuse(&with(b"cue 0 0\n")).contains("without its text"));
4952 assert!(refuse(&with(b"cue 0\n")).contains("without a cue index"));
4953 assert!(
4954 refuse(b"edith 23\nsubtitle - subs.srt\ncue 0 0 x\n").contains("unknown keyword"),
4955 "a cue line before v24 is not a dialect"
4956 );
4957 }
4958
4959 /// The v10 line: which track of which file, written beside the sources and
4960 /// read back as the pair a load opens. And what a v9 file is -- one with no
4961 /// subtitles at all, which still opens and re-saves as v10.
4962 #[test]
4963 fn subtitles_round_trip_as_references_and_a_v9_file_has_none() {
4964 let dir = PathBuf::from("/proj");
4965 let (_, sources, lanes) = doc();
4966 let tracks = [
4967 subtitle("/proj/subs.srt", None),
4968 subtitle("/proj/a.mp4", Some(3)),
4969 subtitle("/elsewhere/od d name.ass", None),
4970 ];
4971 let bytes = super::emit(
4972 &dir,
4973 &sources,
4974 &lanes,
4975 &[],
4976 &[],
4977 &tracks,
4978 &[],
4979 &[],
4980 &[],
4981 (1280, 720),
4982 None,
4983 crate::tonemap::Preset::default(),
4984 false,
4985 true,
4986 crate::export::EncoderSeat::default(),
4987 Limiter::default(),
4988 None,
4989 0,
4990 );
4991 let text = String::from_utf8_lossy(&bytes);
4992 assert!(
4993 text.contains(
4994 "subtitle - subs.srt\n\
4995 subtitle 3 a.mp4\n\
4996 subtitle - /elsewhere/od d name.ass\n"
4997 ),
4998 "the path is relative where it can be, and runs to the end of its \
4999 line, spaces and all: {text}"
5000 );
5001 let back = parse(&bytes, &dir).expect("v10 parses");
5002 assert_eq!(
5003 back.subtitles,
5004 vec![
5005 (PathBuf::from("/proj/subs.srt"), None),
5006 (PathBuf::from("/proj/a.mp4"), Some(3)),
5007 (PathBuf::from("/elsewhere/od d name.ass"), None),
5008 ]
5009 );
5010
5011 // A v9 file is a project with no subtitles, and re-saving it writes v10.
5012 let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5013 video 1 0 0 30 0 - - - fit 1000\n";
5014 let old = parse(v9, &dir).expect("v9 still loads");
5015 assert_eq!(old.subtitles, Vec::new());
5016 assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 30\n"));
5017 // ...and the line itself is not a v9 line: a dialect may not be mixed.
5018 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
5019 .unwrap_err()
5020 .to_string();
5021 assert_eq!(mixed, "line 3: unknown keyword \"subtitle\"");
5022 // A subtitle line with no path is refused, as a source with none is.
5023 for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] {
5024 let file = format!("edith 10\nsource 0 a.mp4\n{line}");
5025 assert!(
5026 parse(file.as_bytes(), &dir).is_err(),
5027 "{line:?} is not a subtitle line"
5028 );
5029 }
5030 }
5031
5032 /// The v33 `sublang` line: a track's language is written after the subtitle
5033 /// lines and comes back on that track. A project with no language writes no
5034 /// line and keeps its old header, and a line that names no track, has no
5035 /// language, or sits in a dialect before v33 is refused.
5036 #[test]
5037 fn sublang_lines_round_trip_and_a_project_with_none_is_unchanged() {
5038 let dir = PathBuf::from("/proj");
5039 let (_, sources, lanes) = doc();
5040 let save = |tracks: &[SubtitleTrack]| {
5041 super::emit(
5042 &dir,
5043 &sources,
5044 &lanes,
5045 &[],
5046 &[],
5047 tracks,
5048 &[],
5049 &[],
5050 &[],
5051 (1280, 720),
5052 None,
5053 crate::tonemap::Preset::default(),
5054 false,
5055 true,
5056 crate::export::EncoderSeat::default(),
5057 Limiter::default(),
5058 None,
5059 0,
5060 )
5061 };
5062 let mut eng = subtitle("/proj/subs.srt", None);
5063 eng.language = "eng".into();
5064 let mut fra = subtitle("/proj/a.mp4", Some(3));
5065 fra.language = "fra".into();
5066 let bytes = save(&[eng, fra]);
5067 let text = String::from_utf8_lossy(&bytes);
5068 assert!(text.starts_with("edith 33\n"), "a language makes it v33: {text}");
5069 assert!(
5070 text.contains("subtitle - subs.srt\nsubtitle 3 a.mp4\nsublang 0 eng\nsublang 1 fra\n"),
5071 "{text}"
5072 );
5073 let back = parse(&bytes, &dir).expect("v33 parses");
5074 assert_eq!(back.sub_langs, [(0, "eng".to_string()), (1, "fra".to_string())]);
5075
5076 // No language anywhere: no line, and the header is the one it was.
5077 let bare = save(&[subtitle("/proj/subs.srt", None)]);
5078 let text = String::from_utf8_lossy(&bare);
5079 assert!(!text.contains("sublang") && !text.starts_with("edith 33"), "{text}");
5080 assert!(parse(&bare, &dir).expect("parses").sub_langs.is_empty());
5081
5082 // A v32 file has no languages and loads as it did.
5083 let v32 = b"edith 32\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n";
5084 assert!(parse(v32, &dir).expect("v32 loads").sub_langs.is_empty());
5085
5086 // The refusals: a track that is not there, an empty language, and a
5087 // line in a dialect before v33.
5088 let head = "edith 33\nsource 0 a.mp4\nsubtitle - subs.srt\n";
5089 for line in ["sublang 1 eng\n", "sublang 0\n", "sublang x eng\n"] {
5090 assert!(
5091 parse(format!("{head}{line}").as_bytes(), &dir).is_err(),
5092 "{line:?} is not a sublang line"
5093 );
5094 }
5095 let old = b"edith 32\nsource 0 a.mp4\nsubtitle - subs.srt\nsublang 0 eng\n";
5096 assert_eq!(
5097 parse(old, &dir).unwrap_err().to_string(),
5098 "line 4: unknown keyword \"sublang\""
5099 );
5100 }
5101
5102 /// The caption's group field (v16): written only when the caption is in a
5103 /// group -- so a project nobody grouped a caption in is the same bytes it
5104 /// was in v15 -- read back as the id, and refused in an older dialect,
5105 /// which never wrote one.
5106 #[test]
5107 fn a_caption_group_round_trips_and_an_old_dialect_refuses_the_field() {
5108 let dir = PathBuf::from("/proj");
5109 let caption = |start: u32, frames: u32, link| SubClip {
5110 start,
5111 frames,
5112 track: 0,
5113 in_us: 0,
5114 out_us: i64::from(frames) * 1_000_000,
5115 link,
5116 };
5117 let lanes = vec![
5118 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(7))]),
5119 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(7))]),
5120 (LaneKind::Subtitle, Vec::new()),
5121 ];
5122 let subs = vec![
5123 vec![],
5124 vec![],
5125 vec![caption(0, 30, Some(7)), caption(40, 10, None)],
5126 ];
5127 let bytes = super::emit(
5128 &dir,
5129 &doc().1,
5130 &lanes,
5131 &[],
5132 &subs,
5133 &[subtitle("/proj/subs.srt", None)],
5134 &[],
5135 &[],
5136 &[],
5137 (1280, 720),
5138 None,
5139 crate::tonemap::Preset::default(),
5140 false,
5141 true,
5142 crate::export::EncoderSeat::default(),
5143 Limiter::default(),
5144 None,
5145 0,
5146 );
5147 let text = String::from_utf8_lossy(&bytes);
5148 assert!(
5149 text.contains("sub 1 0 30 0 0 30000000 7\n"),
5150 "the grouped caption carries its id: {text}"
5151 );
5152 assert!(
5153 text.contains("sub 1 40 10 0 0 10000000\n"),
5154 "a caption in no group writes no field: {text}"
5155 );
5156 let back = parse(&bytes, &dir).expect("v16 parses");
5157 assert_eq!(back.subs[2][0].link, Some(7));
5158 assert_eq!(back.subs[2][1].link, None);
5159
5160 // The older dialect never wrote a sixth field, and one claiming to be
5161 // it is a file this parser refuses by name.
5162 let v15 = parse(
5163 b"edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
5164 sub 1 0 30 0 0 30000000 7\n",
5165 &dir,
5166 )
5167 .unwrap_err()
5168 .to_string();
5169 assert_eq!(v15, "line 6: sub wants 5 fields, found 6");
5170 }
5171
5172 /// The v12 line: whether the project is cut on the stand-ins, written only
5173 /// when it is -- and the dialect before it, which had no stand-ins and
5174 /// whose bytes are therefore unchanged bar the version.
5175 #[test]
5176 fn the_proxy_switch_round_trips_and_a_v11_file_is_cut_on_its_films() {
5177 let dir = PathBuf::from("/proj");
5178 let (_, sources, lanes) = doc();
5179 let bytes = |proxy| {
5180 super::emit(
5181 &dir,
5182 &sources,
5183 &lanes,
5184 &[],
5185 &[],
5186 &[],
5187 &[],
5188 &[],
5189 &[],
5190 (1280, 720),
5191 None,
5192 crate::tonemap::Preset::default(),
5193 proxy,
5194 true,
5195 crate::export::EncoderSeat::default(),
5196 Limiter::default(),
5197 None,
5198 0,
5199 )
5200 };
5201 let on = bytes(true);
5202 assert!(
5203 String::from_utf8_lossy(&on).contains("proxy on\n"),
5204 "{}",
5205 String::from_utf8_lossy(&on)
5206 );
5207 assert!(parse(&on, &dir).expect("v12 parses").proxy);
5208 let off = bytes(false);
5209 assert!(
5210 !String::from_utf8_lossy(&off).contains("proxy"),
5211 "off is the line left out"
5212 );
5213 assert!(!parse(&off, &dir).expect("v12 parses").proxy);
5214
5215 // A v11 project is one cut on the films themselves, and it still loads.
5216 let v11 = b"edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5217 video 1 0 0 30 0 - - - fit 1000\n";
5218 let old = parse(v11, &dir).expect("v11 still loads");
5219 assert!(!old.proxy);
5220 assert_eq!(old.sources.len(), 1, "the rest of it came back too");
5221 // ...and the line is not a v11 line: a dialect may not be mixed.
5222 let mixed = parse(b"edith 11\nsource 0 a.mp4\nproxy on\n", &dir)
5223 .unwrap_err()
5224 .to_string();
5225 assert_eq!(mixed, "line 3: unknown keyword \"proxy\"");
5226 // Anything but on or off is a corrupt line, by name.
5227 for line in ["proxy\n", "proxy yes\n", "proxy On\n"] {
5228 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5229 assert!(
5230 parse(file.as_bytes(), &dir).is_err(),
5231 "{line:?} is not a proxy line"
5232 );
5233 }
5234 }
5235
5236 /// The v13 line: whether an import makes a stand-in by itself. Written the
5237 /// other way up from every other switch here -- on is the default and the
5238 /// line left out -- because that is what every dialect before it did, and a
5239 /// v12 file must come back doing it.
5240 #[test]
5241 fn the_auto_proxy_switch_round_trips_and_a_v12_file_makes_them_by_itself() {
5242 let dir = PathBuf::from("/proj");
5243 let (_, sources, lanes) = doc();
5244 let bytes = |proxy, auto| {
5245 super::emit(
5246 &dir,
5247 &sources,
5248 &lanes,
5249 &[],
5250 &[],
5251 &[],
5252 &[],
5253 &[],
5254 &[],
5255 (1280, 720),
5256 None,
5257 crate::tonemap::Preset::default(),
5258 proxy,
5259 auto,
5260 crate::export::EncoderSeat::default(),
5261 Limiter::default(),
5262 None,
5263 0,
5264 )
5265 };
5266 // The default is the line left out, and the two switches are two lines:
5267 // a project cut on stand-ins it does not make writes both.
5268 let on = bytes(false, true);
5269 assert!(
5270 !String::from_utf8_lossy(&on).contains("autoproxy"),
5271 "on is the line left out: {}",
5272 String::from_utf8_lossy(&on)
5273 );
5274 assert!(parse(&on, &dir).expect("v13 parses").auto_proxy);
5275 let off = bytes(true, false);
5276 let text = String::from_utf8_lossy(&off).to_string();
5277 assert!(text.contains("proxy on\nautoproxy off\n"), "{text}");
5278 let back = parse(&off, &dir).expect("v13 parses");
5279 assert!(back.proxy, "the other switch came back too");
5280 assert!(!back.auto_proxy);
5281
5282 // A v12 project made them by itself and could not be told otherwise.
5283 let v12 = b"edith 12\nplayhead 0\nresolution 1280 720\nproxy on\nsource 0 a.mp4\n\
5284 video 1 0 0 30 0 - - - fit 1000\n";
5285 let old = parse(v12, &dir).expect("v12 still loads");
5286 assert!(old.auto_proxy, "a v12 project made its stand-ins by itself");
5287 assert!(old.proxy, "the rest of it came back too");
5288 // ...and the line is not a v12 line: a dialect may not be mixed.
5289 let mixed = parse(b"edith 12\nsource 0 a.mp4\nautoproxy off\n", &dir)
5290 .unwrap_err()
5291 .to_string();
5292 assert_eq!(mixed, "line 3: unknown keyword \"autoproxy\"");
5293 // Anything but on or off is a corrupt line, by name.
5294 for line in ["autoproxy\n", "autoproxy no\n", "autoproxy Off\n"] {
5295 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5296 assert!(
5297 parse(file.as_bytes(), &dir).is_err(),
5298 "{line:?} is not an autoproxy line"
5299 );
5300 }
5301 }
5302
5303 /// The v14 line: which encoder an export writes the picture with, by name,
5304 /// read back as the very seat -- and the dialect before it, which had no
5305 /// way to say one and took whatever this machine had.
5306 #[test]
5307 fn the_encoder_seat_round_trips_by_name_and_a_v13_file_takes_the_machines() {
5308 use crate::export::EncoderSeat;
5309 let dir = PathBuf::from("/proj");
5310 let (_, sources, lanes) = doc();
5311 let bytes = |seat| {
5312 super::emit(
5313 &dir,
5314 &sources,
5315 &lanes,
5316 &[],
5317 &[],
5318 &[],
5319 &[],
5320 &[],
5321 &[],
5322 (1280, 720),
5323 None,
5324 crate::tonemap::Preset::default(),
5325 false,
5326 true,
5327 seat,
5328 Limiter::default(),
5329 None,
5330 0,
5331 )
5332 };
5333 // The default is the line left out, so a project nobody has picked a
5334 // seat for is the bytes a v13 file was bar the version line.
5335 let auto = bytes(EncoderSeat::Auto);
5336 assert!(
5337 !String::from_utf8_lossy(&auto).contains("encoder"),
5338 "auto is the line left out: {}",
5339 String::from_utf8_lossy(&auto)
5340 );
5341 assert_eq!(
5342 parse(&auto, &dir).expect("v14 parses").encoder,
5343 EncoderSeat::Auto
5344 );
5345 for seat in [EncoderSeat::Hardware, EncoderSeat::Software] {
5346 let written = bytes(seat);
5347 let text = String::from_utf8_lossy(&written).to_string();
5348 assert!(
5349 text.contains(&format!("encoder {}\n", seat.name())),
5350 "{text}"
5351 );
5352 assert_eq!(parse(&written, &dir).expect("v14 parses").encoder, seat);
5353 }
5354
5355 // A v13 project took the seat this machine had and could not be told
5356 // otherwise.
5357 let v13 = b"edith 13\nplayhead 0\nresolution 1280 720\nautoproxy off\nsource 0 a.mp4\n\
5358 video 1 0 0 30 0 - - - fit 1000\n";
5359 let old = parse(v13, &dir).expect("v13 still loads");
5360 assert_eq!(
5361 old.encoder,
5362 EncoderSeat::Auto,
5363 "a v13 project exported on whatever seat there was"
5364 );
5365 assert!(!old.auto_proxy, "the rest of it came back too");
5366 // ...and the line is not a v13 line: a dialect may not be mixed.
5367 let mixed = parse(b"edith 13\nsource 0 a.mp4\nencoder software\n", &dir)
5368 .unwrap_err()
5369 .to_string();
5370 assert_eq!(mixed, "line 3: unknown keyword \"encoder\"");
5371 // Anything but the three names is a corrupt line, by name.
5372 for line in ["encoder\n", "encoder gpu\n", "encoder Hardware\n"] {
5373 let file = format!("edith 15\nsource 0 a.mp4\n{line}");
5374 assert!(
5375 parse(file.as_bytes(), &dir).is_err(),
5376 "{line:?} is not an encoder line"
5377 );
5378 }
5379 }
5380
5381 /// The v17 line: an explicit sound rate, written only when picked and read
5382 /// back as the very number -- and a v16 file, which had no way to say one
5383 /// and meant the source's own probe, still opens with `None`.
5384 #[test]
5385 fn the_sample_rate_round_trips_and_a_v16_file_leaves_it_derived() {
5386 let dir = PathBuf::from("/proj");
5387 let (_, sources, lanes) = doc();
5388 let bytes = |rate| {
5389 super::emit(
5390 &dir,
5391 &sources,
5392 &lanes,
5393 &[],
5394 &[],
5395 &[],
5396 &[],
5397 &[],
5398 &[],
5399 (1280, 720),
5400 None,
5401 crate::tonemap::Preset::default(),
5402 false,
5403 true,
5404 crate::export::EncoderSeat::default(),
5405 Limiter::default(),
5406 rate,
5407 0,
5408 )
5409 };
5410 // Unset is the line left out, so a project nobody has chosen a rate for
5411 // is the bytes a v16 file was bar the version line.
5412 let unset = bytes(None);
5413 assert!(
5414 !String::from_utf8_lossy(&unset).contains("samplerate"),
5415 "no pick is the line left out: {}",
5416 String::from_utf8_lossy(&unset)
5417 );
5418 assert_eq!(parse(&unset, &dir).expect("v17 parses").sample_rate, None);
5419 for rate in [44_100, 48_000, 96_000] {
5420 let written = bytes(Some(rate));
5421 let text = String::from_utf8_lossy(&written).to_string();
5422 assert!(text.contains(&format!("samplerate {rate}\n")), "{text}");
5423 assert_eq!(
5424 parse(&written, &dir).expect("v17 parses").sample_rate,
5425 Some(rate)
5426 );
5427 }
5428 // A v16 project had no rate of its own to say: the field comes back
5429 // `None`, which is what "derive it from the source" already meant.
5430 let v16 = b"edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5431 video 1 0 0 30 0 - - - fit 1000\n";
5432 assert_eq!(parse(v16, &dir).expect("v16 still loads").sample_rate, None);
5433 // ...and the line is not a v16 line: a dialect may not be mixed.
5434 let mixed = parse(b"edith 16\nsource 0 a.mp4\nsamplerate 48000\n", &dir)
5435 .unwrap_err()
5436 .to_string();
5437 assert_eq!(mixed, "line 3: unknown keyword \"samplerate\"");
5438 // A number out of a sound rate's range is a corrupt line, by name.
5439 for line in ["samplerate 0\n", "samplerate 500000\n", "samplerate nope\n"] {
5440 let file = format!("edith 18\nsource 0 a.mp4\n{line}");
5441 assert!(
5442 parse(file.as_bytes(), &dir).is_err(),
5443 "{line:?} is not a sound rate line"
5444 );
5445 }
5446 }
5447
5448 /// The v11 line: the HDR rendition, written by name, read back as the very
5449 /// preset -- and the dialect before it, which had no way to say one and
5450 /// meant the published conversion.
5451 #[test]
5452 fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
5453 let dir = PathBuf::from("/proj");
5454 let (_, sources, lanes) = doc();
5455 for preset in crate::tonemap::Preset::ALL {
5456 let bytes = super::emit(
5457 &dir,
5458 &sources,
5459 &lanes,
5460 &[],
5461 &[],
5462 &[],
5463 &[],
5464 &[],
5465 &[],
5466 (1280, 720),
5467 None,
5468 preset,
5469 false,
5470 true,
5471 crate::export::EncoderSeat::default(),
5472 Limiter::default(),
5473 None,
5474 0,
5475 );
5476 let text = String::from_utf8_lossy(&bytes).to_string();
5477 assert_eq!(
5478 text.contains(&format!("tonemap {}\n", preset.name())),
5479 preset != crate::tonemap::Preset::default(),
5480 "the default is the line left out: {text}"
5481 );
5482 assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
5483 }
5484
5485 // A v10 file is a project shown the published way, and re-saving it
5486 // writes v11 with nothing more in it.
5487 let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5488 video 1 0 0 30 0 - - - fit 1000\n";
5489 let old = parse(v10, &dir).expect("v10 still loads");
5490 assert_eq!(old.tone, crate::tonemap::Preset::Reference);
5491 // ...and the line itself is not a v10 line: a dialect may not be mixed.
5492 let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
5493 .unwrap_err()
5494 .to_string();
5495 assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
5496 // A rendition nobody wrote is a corrupt line, by name -- not a silent
5497 // fall back to another picture.
5498 for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
5499 let file = format!("edith 11\nsource 0 a.mp4\n{line}");
5500 assert!(
5501 parse(file.as_bytes(), &dir).is_err(),
5502 "{line:?} is not a tonemap line"
5503 );
5504 }
5505 }
5506
5507 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
5508 Clip {
5509 speed_keys: Vec::new(),
5510 reversed: false,
5511 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5512 angle: Default::default(),
5513 fade_in: 0,
5514 fade_out: 0,
5515 transition_out: 0,
5516 transition_kind: Default::default(),
5517 visualizer: 0,
5518 viz_paint: 0,
5519 gain_db: 0.0,
5520 gain_keys: Vec::new(),
5521 pan: 0,
5522 transform_keys: Vec::new(),
5523 opacity_keys: Vec::new(),
5524 color_keys: Vec::new(),
5525 effects: Vec::new(),
5526 start,
5527 in_frame,
5528 out_frame,
5529 source,
5530 link,
5531 eq: None,
5532 color: None,
5533 transform: None,
5534 fit: FitPolicy::default(),
5535 speed: Speed::NORMAL,
5536 pitch: 0,
5537 }
5538 }
5539
5540 /// [`emit`] for a timeline that equalizes nothing, which is every case that
5541 /// predates the eq lines.
5542 fn flat(
5543 dir: &Path,
5544 sources: &[Source],
5545 lanes: &[(LaneKind, Vec<Clip>)],
5546 playhead: u32,
5547 ) -> Vec<u8> {
5548 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
5549 }
5550
5551 /// Two sources, one under the project's own directory and one not, a clip
5552 /// from each on the video lane, and an audio lane with a gap in the middle
5553 /// -- the shape every case below starts from.
5554 fn source(path: &str, audio_stream: usize) -> Source {
5555 Source {
5556 path: PathBuf::from(path),
5557 audio_stream,
5558 ..Default::default()
5559 }
5560 }
5561
5562 /// Lanes in display order, as [`Document::lanes`] holds them.
5563 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
5564
5565 /// `V1` then `A1`, the shape every dialect before v4 held.
5566 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
5567 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5568 }
5569
5570 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
5571 (
5572 PathBuf::from("/proj"),
5573 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
5574 two(
5575 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
5576 vec![clip(0, 0, 30, 0, Some(0))],
5577 ),
5578 )
5579 }
5580
5581 #[test]
5582 fn relative_and_absolute_paths_round_trip() {
5583 let (dir, sources, lanes) = doc();
5584 let bytes = flat(&dir, &sources, &lanes, 12);
5585 assert_eq!(
5586 String::from_utf8_lossy(&bytes),
5587 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
5588 source 2 /elsewhere/b.mp4\n\
5589 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\
5590 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
5591 "the file under the project directory is written relative to it, \
5592 each with the audio stream it plays"
5593 );
5594 let back = parse(&bytes, &dir).expect("parse");
5595 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
5596 assert_eq!(
5597 back.lanes, lanes,
5598 "both lanes, in display order; the trailing gap needs no line"
5599 );
5600 assert_eq!(back.playhead, 12);
5601 // ...and emitting the parsed document reproduces the same bytes.
5602 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5603 }
5604
5605 /// The whole of the bump: a project of any number of lanes writes and reads
5606 /// back, in display order, empty lanes and cross-lane groups included.
5607 #[test]
5608 fn any_number_of_lanes_round_trips() {
5609 let dir = PathBuf::from("/proj");
5610 let sources = vec![source("/proj/a.mp4", 0)];
5611 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
5612 // shows, not video-then-audio -- with one take grouped across V1 and A2
5613 // (no paired ord, the lanes between them empty of it) and an A1 holding
5614 // nothing at all.
5615 let lanes = vec![
5616 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
5617 (LaneKind::Audio, Vec::new()),
5618 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
5619 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
5620 ];
5621 let bytes = flat(&dir, &sources, &lanes, 7);
5622 assert_eq!(
5623 String::from_utf8_lossy(&bytes),
5624 "edith 30\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
5625 video 1 0 0 30 0 4 - - fit 1000 0 0 0 - 0 0\naudio 1\n\
5626 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",
5627 "an empty lane is a line of its own; everything else is its clips"
5628 );
5629 let back = parse(&bytes, &dir).expect("parse");
5630 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
5631 assert_eq!(back.playhead, 7);
5632 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5633
5634 // A lane number may not skip one of its kind: that lane was declared by
5635 // nothing, and the refusal names it.
5636 for (file, want) in [
5637 (
5638 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
5639 "line 3: lane V2 comes before V1",
5640 ),
5641 (
5642 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
5643 "line 4: lane A3 comes before A1",
5644 ),
5645 (
5646 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
5647 "line 3: lane numbers start at 1",
5648 ),
5649 // The clip fields are still the clip fields, one lane number on.
5650 (
5651 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
5652 "line 3: clip wants 5 fields, found 4",
5653 ),
5654 // ...and a v4 line in a v3 file reads as the garbled clip it is.
5655 (
5656 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
5657 "line 3: clip wants 5 fields, found 6",
5658 ),
5659 ] {
5660 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
5661 }
5662 // Lanes and nothing on them is the emptied timeline, saved: a project.
5663 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
5664 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
5665 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
5666 }
5667
5668 /// One band, spelled the way an eq line spells it.
5669 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
5670 Band {
5671 freq_hz,
5672 gain_db,
5673 q,
5674 kind,
5675 }
5676 }
5677
5678 /// The whole of the v5 bump: the clips name a shared equalizer table, the
5679 /// bytes are the ones documented at the top of this file, and every f32 in
5680 /// them comes back *bit* for bit -- which is what makes a re-save of a
5681 /// loaded project produce the same file rather than a drifting one.
5682 #[test]
5683 fn equalizers_round_trip_bit_exactly_and_are_shared() {
5684 let dir = PathBuf::from("/proj");
5685 let sources = vec![source("/proj/a.mp4", 0)];
5686 let eq = vec![
5687 EqParams {
5688 bands: vec![
5689 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
5690 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
5691 ],
5692 },
5693 // The awkward ones: a value needing all 24 mantissa bits, one whose
5694 // shortest spelling is exponential, a subnormal, and a negative
5695 // zero -- plus the empty cascade, which is a setting like any other.
5696 EqParams {
5697 bands: vec![band_of(
5698 16_777_215.0,
5699 -0.1,
5700 f32::MIN_POSITIVE / 3.0,
5701 BandKind::HighShelf,
5702 )],
5703 },
5704 EqParams { bands: Vec::new() },
5705 ];
5706 // Two clips share entry 0, so it is written once; one clip plays flat.
5707 let lanes = two(
5708 vec![
5709 Clip {
5710 fade_in: 0,
5711 fade_out: 0,
5712 transition_out: 0,
5713 transition_kind: Default::default(),
5714 visualizer: 0,
5715 viz_paint: 0,
5716 gain_db: 0.0,
5717 eq: Some(0),
5718 ..clip(0, 0, 30, 0, Some(0))
5719 },
5720 Clip {
5721 fade_in: 0,
5722 fade_out: 0,
5723 transition_out: 0,
5724 transition_kind: Default::default(),
5725 visualizer: 0,
5726 viz_paint: 0,
5727 gain_db: 0.0,
5728 eq: Some(1),
5729 ..clip(30, 10, 20, 0, None)
5730 },
5731 ],
5732 vec![
5733 Clip {
5734 fade_in: 0,
5735 fade_out: 0,
5736 transition_out: 0,
5737 transition_kind: Default::default(),
5738 visualizer: 0,
5739 viz_paint: 0,
5740 gain_db: 0.0,
5741 eq: Some(0),
5742 ..clip(0, 0, 30, 0, Some(0))
5743 },
5744 Clip {
5745 fade_in: 0,
5746 fade_out: 0,
5747 transition_out: 0,
5748 transition_kind: Default::default(),
5749 visualizer: 0,
5750 viz_paint: 0,
5751 gain_db: 0.0,
5752 eq: Some(2),
5753 ..clip(30, 0, 10, 0, None)
5754 },
5755 ],
5756 );
5757 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
5758 assert_eq!(
5759 String::from_utf8_lossy(&bytes),
5760 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5761 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
5762 eq 16777215.0:-0.1:3.918315e-39:hs\n\
5763 eq\n\
5764 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\
5765 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",
5766 "the table comes before the clips, and a clip names a line of it"
5767 );
5768
5769 let back = parse(&bytes, &dir).expect("parse");
5770 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
5771 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
5772 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
5773 assert_eq!(
5774 (
5775 got.freq_hz.to_bits(),
5776 got.gain_db.to_bits(),
5777 got.q.to_bits(),
5778 got.kind
5779 ),
5780 (
5781 want.freq_hz.to_bits(),
5782 want.gain_db.to_bits(),
5783 want.q.to_bits(),
5784 want.kind
5785 ),
5786 "eq {i} band {b} came back as other bits"
5787 );
5788 }
5789 }
5790 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
5791 assert_eq!(
5792 emit(
5793 &dir,
5794 &back.sources,
5795 &back.lanes,
5796 &back.eq,
5797 &back.color,
5798 (1280, 720),
5799 0
5800 ),
5801 bytes
5802 );
5803 }
5804
5805 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
5806 /// colour table, the bytes are the ones documented at the top of this file,
5807 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
5808 #[test]
5809 fn colours_round_trip_bit_exactly_and_are_shared() {
5810 let dir = PathBuf::from("/proj");
5811 let sources = vec![source("/proj/a.mp4", 0)];
5812 let color = vec![
5813 ColorParams {
5814 brightness: 0.1,
5815 contrast: 1.2,
5816 saturation: 0.9,
5817 tint: -0.3,
5818 ..Default::default()
5819 },
5820 // The awkward ones again: all 24 mantissa bits, an exponential
5821 // spelling, a subnormal and a negative zero -- and the identity,
5822 // which is a setting like any other.
5823 ColorParams {
5824 brightness: -0.000_000_1,
5825 contrast: 16_777_215.0,
5826 saturation: f32::MIN_POSITIVE / 3.0,
5827 tint: -0.0,
5828 ..Default::default()
5829 },
5830 ColorParams::default(),
5831 ];
5832 // Two clips share entry 0, so it is written once; one clip is ungraded.
5833 let lanes = two(
5834 vec![
5835 Clip {
5836 fade_in: 0,
5837 fade_out: 0,
5838 transition_out: 0,
5839 transition_kind: Default::default(),
5840 visualizer: 0,
5841 viz_paint: 0,
5842 gain_db: 0.0,
5843 color: Some(0),
5844 fit: FitPolicy::default(),
5845 speed: Speed::NORMAL,
5846 ..clip(0, 0, 30, 0, Some(0))
5847 },
5848 Clip {
5849 fade_in: 0,
5850 fade_out: 0,
5851 transition_out: 0,
5852 transition_kind: Default::default(),
5853 visualizer: 0,
5854 viz_paint: 0,
5855 gain_db: 0.0,
5856 color: Some(1),
5857 fit: FitPolicy::default(),
5858 speed: Speed::NORMAL,
5859 ..clip(30, 10, 20, 0, None)
5860 },
5861 ],
5862 vec![
5863 Clip {
5864 fade_in: 0,
5865 fade_out: 0,
5866 transition_out: 0,
5867 transition_kind: Default::default(),
5868 visualizer: 0,
5869 viz_paint: 0,
5870 gain_db: 0.0,
5871 color: Some(0),
5872 fit: FitPolicy::default(),
5873 speed: Speed::NORMAL,
5874 ..clip(0, 0, 30, 0, Some(0))
5875 },
5876 Clip {
5877 fade_in: 0,
5878 fade_out: 0,
5879 transition_out: 0,
5880 transition_kind: Default::default(),
5881 visualizer: 0,
5882 viz_paint: 0,
5883 gain_db: 0.0,
5884 color: Some(2),
5885 fit: FitPolicy::default(),
5886 speed: Speed::NORMAL,
5887 ..clip(30, 0, 10, 0, None)
5888 },
5889 ],
5890 );
5891 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
5892 assert_eq!(
5893 String::from_utf8_lossy(&bytes),
5894 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5895 color 0.1:1.2:0.9:-0.3\n\
5896 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
5897 color 0.0:1.0:1.0:0.0\n\
5898 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\
5899 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",
5900 "the table comes before the clips, and a clip names a line of it"
5901 );
5902
5903 let back = parse(&bytes, &dir).expect("parse");
5904 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
5905 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
5906 assert_eq!(
5907 (
5908 got.brightness.to_bits(),
5909 got.contrast.to_bits(),
5910 got.saturation.to_bits(),
5911 got.tint.to_bits()
5912 ),
5913 (
5914 want.brightness.to_bits(),
5915 want.contrast.to_bits(),
5916 want.saturation.to_bits(),
5917 want.tint.to_bits()
5918 ),
5919 "color {i} came back as other bits"
5920 );
5921 }
5922 assert_eq!(back.color.len(), 3);
5923 assert_eq!(
5924 emit(
5925 &dir,
5926 &back.sources,
5927 &back.lanes,
5928 &back.eq,
5929 &back.color,
5930 (1280, 720),
5931 0
5932 ),
5933 bytes
5934 );
5935 }
5936
5937 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
5938 /// intact, and re-saving it writes the new magic and a `-` colour field.
5939 #[test]
5940 fn a_v5_file_grades_nothing() {
5941 let dir = PathBuf::from("/proj");
5942 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
5943 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
5944 let old = parse(v5, &dir).expect("v5 parses");
5945 assert!(old.color.is_empty(), "nothing before v6 grades anything");
5946 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
5947 assert_eq!(old.lanes[0].1[0].eq, Some(0));
5948 assert!(old.lanes[0].1[0].color.is_none());
5949 assert_eq!(
5950 String::from_utf8_lossy(&emit(
5951 &dir,
5952 &old.sources,
5953 &old.lanes,
5954 &old.eq,
5955 &old.color,
5956 (1280, 720),
5957 old.playhead
5958 )),
5959 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5960 eq 80.0:-3.0:0.707:ls\n\
5961 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"
5962 );
5963 }
5964
5965 /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
5966 /// written on its own line, comes back as the very number that was set, and
5967 /// a v7 file -- which has no such field -- loads at real time and re-saves
5968 /// saying so.
5969 #[test]
5970 fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
5971 let dir = PathBuf::from("/proj");
5972 let sources = vec![Source::new("/proj/a.mp4", 0)];
5973 let speeded = |start, in_frame, out_frame, permille| Clip {
5974 speed_keys: Vec::new(),
5975 reversed: false,
5976 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5977 angle: Default::default(),
5978 fade_in: 0,
5979 fade_out: 0,
5980 transition_out: 0,
5981 transition_kind: Default::default(),
5982 visualizer: 0,
5983 viz_paint: 0,
5984 gain_db: 0.0,
5985 gain_keys: Vec::new(),
5986 pan: 0,
5987 transform_keys: Vec::new(),
5988 opacity_keys: Vec::new(),
5989 color_keys: Vec::new(),
5990 effects: Vec::new(),
5991 start,
5992 in_frame,
5993 out_frame,
5994 source: 0,
5995 link: None,
5996 eq: None,
5997 color: None,
5998 transform: None,
5999 fit: FitPolicy::default(),
6000 speed: Speed::from_permille(permille),
6001 pitch: 0,
6002 };
6003 // 30 source frames at 2x is 15 timeline frames, which is where the
6004 // second clip starts -- the file writes the source range and the rate,
6005 // and the length on the timeline is derived from the two.
6006 let lanes = vec![
6007 (
6008 LaneKind::Video,
6009 vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
6010 ),
6011 (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
6012 ];
6013 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6014 assert_eq!(
6015 String::from_utf8_lossy(&bytes),
6016 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6017 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\
6018 audio 1 0 0 30 0 - - - fit 2000 0 0 0 - 0 0\n",
6019 "the rate is the clip line's last field, in thousandths"
6020 );
6021 let back = parse(&bytes, &dir).expect("parse");
6022 assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
6023
6024 // ...and the dialect before it, which had no rate to name.
6025 let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6026 video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
6027 let old = parse(v7, &dir).expect("v7 parses");
6028 assert!(
6029 old.lanes
6030 .iter()
6031 .flat_map(|(_, clips)| clips)
6032 .all(|c| c.speed == Speed::NORMAL),
6033 "nothing before v8 plays at anything but real time"
6034 );
6035 assert_eq!(
6036 String::from_utf8_lossy(&emit(
6037 &dir,
6038 &old.sources,
6039 &old.lanes,
6040 &old.eq,
6041 &old.color,
6042 (1280, 720),
6043 old.playhead
6044 )),
6045 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6046 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"
6047 );
6048 // A rate outside what the editor can set is a corrupt line, by name.
6049 let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
6050 assert_eq!(
6051 parse(bad, &dir).unwrap_err().to_string(),
6052 "line 3: speed 9000 is outside 250-4000 thousandths"
6053 );
6054 }
6055
6056 #[test]
6057 fn a_v17_file_loads_with_zero_fades_and_fades_round_trip_bit_exactly() {
6058 let dir = PathBuf::from("/proj");
6059 // The v17 dialect: nine clip fields, the last the speed -- no fade
6060 // pair after it at all, not even zeroes.
6061 let v17 = b"edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6062 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6063 let old = parse(v17, &dir).expect("v17 parses");
6064 assert!(
6065 old.lanes
6066 .iter()
6067 .flat_map(|(_, clips)| clips)
6068 .all(|c| c.fade_in == 0 && c.fade_out == 0),
6069 "nothing before v18 had a fade to name"
6070 );
6071
6072 // ...and the dialect that does: nonzero fades on both edges, written
6073 // and read back as the very numbers.
6074 let sources = vec![Source::new("/proj/a.mp4", 0)];
6075 let faded = Clip {
6076 speed_keys: Vec::new(),
6077 reversed: false,
6078 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6079 angle: Default::default(),
6080 fade_in: 5,
6081 fade_out: 7,
6082 transition_out: 0,
6083 transition_kind: Default::default(),
6084 visualizer: 0,
6085 viz_paint: 0,
6086 gain_db: 0.0,
6087 gain_keys: Vec::new(),
6088 pan: 0,
6089 transform_keys: Vec::new(),
6090 opacity_keys: Vec::new(),
6091 color_keys: Vec::new(),
6092 effects: Vec::new(),
6093 start: 0,
6094 in_frame: 0,
6095 out_frame: 30,
6096 source: 0,
6097 link: None,
6098 eq: None,
6099 color: None,
6100 transform: None,
6101 fit: FitPolicy::default(),
6102 speed: Speed::NORMAL,
6103 pitch: 0,
6104 };
6105 let lanes = vec![(LaneKind::Video, vec![faded])];
6106 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6107 assert_eq!(
6108 String::from_utf8_lossy(&bytes),
6109 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6110 video 1 0 0 30 0 - - - fit 1000 5 7 0 - 0 0\n",
6111 "the fades are the clip line's last two fields"
6112 );
6113 let back = parse(&bytes, &dir).expect("parse");
6114 assert_eq!(
6115 back.lanes, lanes,
6116 "the fades round trip as the very numbers"
6117 );
6118 }
6119
6120 /// The whole of the v19 bump, the fade test's twin: a clip's dissolve into
6121 /// its successor is written as the clip line's own last field, comes back
6122 /// as the very number that was set, and a v18 file -- which has no such
6123 /// field -- loads with every clip's [`Clip::transition_out`] at zero and
6124 /// re-saves saying so.
6125 #[test]
6126 fn a_v18_file_loads_with_no_transition_and_transitions_round_trip_bit_exactly() {
6127 let dir = PathBuf::from("/proj");
6128 // The v18 dialect: eleven clip fields, the last the fade-out -- no
6129 // transition field after it at all, not even a zero.
6130 let v18 = b"edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6131 video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n";
6132 let old = parse(v18, &dir).expect("v18 parses");
6133 assert!(
6134 old.lanes
6135 .iter()
6136 .flat_map(|(_, clips)| clips)
6137 .all(|c| c.transition_out == 0),
6138 "nothing before v19 had a dissolve to name"
6139 );
6140
6141 // ...and the dialect that does: a nonzero dissolve, written and read
6142 // back as the very number.
6143 let sources = vec![Source::new("/proj/a.mp4", 0)];
6144 let dissolving = Clip {
6145 speed_keys: Vec::new(),
6146 reversed: false,
6147 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6148 angle: Default::default(),
6149 fade_in: 0,
6150 fade_out: 0,
6151 transition_out: 9,
6152 transition_kind: Default::default(),
6153 visualizer: 0,
6154 viz_paint: 0,
6155 gain_db: 0.0,
6156 gain_keys: Vec::new(),
6157 pan: 0,
6158 transform_keys: Vec::new(),
6159 opacity_keys: Vec::new(),
6160 color_keys: Vec::new(),
6161 effects: Vec::new(),
6162 start: 0,
6163 in_frame: 0,
6164 out_frame: 30,
6165 source: 0,
6166 link: None,
6167 eq: None,
6168 color: None,
6169 transform: None,
6170 fit: FitPolicy::default(),
6171 speed: Speed::NORMAL,
6172 pitch: 0,
6173 };
6174 let lanes = vec![(LaneKind::Video, vec![dissolving])];
6175 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6176 assert_eq!(
6177 String::from_utf8_lossy(&bytes),
6178 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6179 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n",
6180 "the dissolve is the clip line's own last field"
6181 );
6182 let back = parse(&bytes, &dir).expect("parse");
6183 assert_eq!(
6184 back.lanes, lanes,
6185 "the dissolve round trips as the very number"
6186 );
6187 }
6188
6189 /// The clip's packed look (v23): a chosen strand colour rides in the
6190 /// field's own bytes under the top bit and comes back bit-exact, a v22
6191 /// file's 32-bit value is the low half of that field with no strand
6192 /// colour, and a file older than the field itself is the zero it always
6193 /// was.
6194 #[test]
6195 fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() {
6196 use crate::decode::{
6197 VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue,
6198 with_viz_paint_strand_sat,
6199 };
6200 let (dir, sources, lanes) = doc();
6201 let mut painted = lanes.clone();
6202 // Azure, its dual half a chosen green rather than the automatic
6203 // complement of the clip's own hue.
6204 let chosen = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 64), 200);
6205 assert!(viz_strand_set(chosen));
6206 painted[0].1[0].viz_paint = chosen;
6207 let bytes = flat(&dir, &sources, &painted, 0);
6208 assert!(
6209 bytes.starts_with(b"edith 30\n"),
6210 "a project with a strand colour saves as v23: {}",
6211 String::from_utf8_lossy(&bytes)
6212 );
6213 let back = parse(&bytes, &dir).expect("v23 parses");
6214 assert_eq!(back.lanes, painted, "the look round-trips bit-exactly");
6215
6216 // A v22 file's field is a u32: the value lands in the low half
6217 // untouched, and a strand colour it cannot carry reads as auto.
6218 let look = VIZ_PAINT_AZURE as u32;
6219 let v22 = format!(
6220 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6221 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 {look}\n"
6222 );
6223 let old = parse(v22.as_bytes(), &dir).expect("v22 still loads");
6224 let paint = old.lanes[0].1[0].viz_paint;
6225 assert_eq!(paint, u64::from(look), "the low half is the v22 value");
6226 assert!(!viz_strand_set(paint), "a v22 look chose no strand colour");
6227 assert_eq!(viz_hue_ui(paint), 150);
6228 assert_eq!(viz_sat_ui(paint), 160);
6229 // ...and a file older than the field is the zero that means the
6230 // azure default, as it was before the field was widened.
6231 let v21 = b"edith 21\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6232 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0\n";
6233 let older = parse(v21, &dir).expect("v21 still loads");
6234 assert_eq!(older.lanes[0].1[0].viz_paint, 0);
6235 }
6236
6237 /// A v19 file is a v20 one that places no clip anywhere but its fit
6238 /// policy's own spot: it loads with every clip's [`Clip::transform`] at
6239 /// `None`, which is what a v19 file's missing field still means.
6240 #[test]
6241 fn a_v19_file_loads_untransformed() {
6242 let dir = PathBuf::from("/proj");
6243 // The v19 dialect: twelve clip fields, the last the transition -- no
6244 // transform field after it at all, not even a `-`.
6245 let v19 = b"edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6246 video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n";
6247 let old = parse(v19, &dir).expect("v19 parses");
6248 assert!(old.transform.is_empty(), "nothing before v20 has a table");
6249 assert!(
6250 old.lanes
6251 .iter()
6252 .flat_map(|(_, clips)| clips)
6253 .all(|c| c.transform.is_none()),
6254 "nothing before v20 had a placement to name"
6255 );
6256 }
6257
6258 /// [`colours_round_trip_bit_exactly_and_are_shared`]'s twin: two clips
6259 /// sharing one transform table entry write it once, and both bytes and
6260 /// values come back bit-exact.
6261 #[test]
6262 fn transforms_round_trip_bit_exactly_and_are_shared() {
6263 let dir = PathBuf::from("/proj");
6264 let sources = vec![source("/proj/a.mp4", 0)];
6265 let transform = vec![
6266 TransformParams {
6267 pos_x: 0.1,
6268 pos_y: -0.2,
6269 scale: 1.5,
6270 rotate: 90.0,
6271 crop_l: 0.1,
6272 crop_r: 0.0,
6273 crop_t: 0.0,
6274 crop_b: 0.05,
6275 opacity: 0.25,
6276 },
6277 // The awkward ones again: all 24 mantissa bits, an exponential
6278 // spelling, a subnormal and a negative zero -- and the identity,
6279 // which is a setting like any other.
6280 TransformParams {
6281 pos_x: -0.000_000_1,
6282 pos_y: 16_777_215.0,
6283 scale: f32::MIN_POSITIVE / 3.0,
6284 rotate: -0.0,
6285 crop_l: 0.0,
6286 crop_r: 0.0,
6287 crop_t: 0.0,
6288 crop_b: 0.0,
6289 opacity: 1.0,
6290 },
6291 TransformParams::default(),
6292 ];
6293 // Two clips share entry 0, so it is written once; one clip is untransformed.
6294 let lanes = two(
6295 vec![
6296 Clip {
6297 fade_in: 0,
6298 fade_out: 0,
6299 transition_out: 0,
6300 transition_kind: Default::default(),
6301 visualizer: 0,
6302 viz_paint: 0,
6303 gain_db: 0.0,
6304 transform: Some(0),
6305 fit: FitPolicy::default(),
6306 speed: Speed::NORMAL,
6307 ..clip(0, 0, 30, 0, Some(0))
6308 },
6309 Clip {
6310 fade_in: 0,
6311 fade_out: 0,
6312 transition_out: 0,
6313 transition_kind: Default::default(),
6314 visualizer: 0,
6315 viz_paint: 0,
6316 gain_db: 0.0,
6317 transform: Some(1),
6318 fit: FitPolicy::default(),
6319 speed: Speed::NORMAL,
6320 ..clip(30, 10, 20, 0, None)
6321 },
6322 ],
6323 vec![
6324 Clip {
6325 fade_in: 0,
6326 fade_out: 0,
6327 transition_out: 0,
6328 transition_kind: Default::default(),
6329 visualizer: 0,
6330 viz_paint: 0,
6331 gain_db: 0.0,
6332 transform: Some(0),
6333 fit: FitPolicy::default(),
6334 speed: Speed::NORMAL,
6335 ..clip(0, 0, 30, 0, Some(0))
6336 },
6337 Clip {
6338 fade_in: 0,
6339 fade_out: 0,
6340 transition_out: 0,
6341 transition_kind: Default::default(),
6342 visualizer: 0,
6343 viz_paint: 0,
6344 gain_db: 0.0,
6345 transform: Some(2),
6346 fit: FitPolicy::default(),
6347 speed: Speed::NORMAL,
6348 ..clip(30, 0, 10, 0, None)
6349 },
6350 ],
6351 );
6352 let bytes = super::emit(
6353 &dir,
6354 &sources,
6355 &lanes,
6356 &[],
6357 &[],
6358 &[],
6359 &[],
6360 &[],
6361 &transform,
6362 (1280, 720),
6363 None,
6364 crate::tonemap::Preset::default(),
6365 false,
6366 true,
6367 crate::export::EncoderSeat::default(),
6368 Limiter::default(),
6369 None,
6370 0,
6371 );
6372 assert_eq!(
6373 String::from_utf8_lossy(&bytes),
6374 "edith 31\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6375 transform 0.1:-0.2:1.5:90.0:0.1:0.0:0.0:0.05:0.25\n\
6376 transform -1e-7:16777215.0:3.918315e-39:-0.0:0.0:0.0:0.0:0.0\n\
6377 transform 0.0:0.0:1.0:0.0:0.0:0.0:0.0:0.0\n\
6378 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\
6379 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",
6380 "the table comes before the clips, and a clip names a line of it"
6381 );
6382
6383 let back = parse(&bytes, &dir).expect("parse");
6384 assert_eq!(back.lanes, lanes, "every clip keeps the transform it named");
6385 for (i, (got, want)) in back.transform.iter().zip(&transform).enumerate() {
6386 assert_eq!(
6387 (
6388 got.pos_x.to_bits(),
6389 got.pos_y.to_bits(),
6390 got.scale.to_bits(),
6391 got.rotate.to_bits(),
6392 got.crop_l.to_bits(),
6393 got.crop_r.to_bits(),
6394 got.crop_t.to_bits(),
6395 got.crop_b.to_bits(),
6396 got.opacity.to_bits(),
6397 ),
6398 (
6399 want.pos_x.to_bits(),
6400 want.pos_y.to_bits(),
6401 want.scale.to_bits(),
6402 want.rotate.to_bits(),
6403 want.crop_l.to_bits(),
6404 want.crop_r.to_bits(),
6405 want.crop_t.to_bits(),
6406 want.crop_b.to_bits(),
6407 want.opacity.to_bits(),
6408 ),
6409 "transform {i} came back as other bits"
6410 );
6411 }
6412 assert_eq!(back.transform.len(), 3);
6413 }
6414
6415 /// The whole of the v9 bump, the speed test's twin: the mix a project was
6416 /// left at -- every track's own volume and the master limiter -- plus the
6417 /// rate it was cut at, all written, all read back as the very numbers, and
6418 /// a v8 file (which has none of them) loading flat and unlimited.
6419 #[test]
6420 fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
6421 let dir = PathBuf::from("/proj");
6422 let sources = vec![Source::new("/proj/a.mp4", 0)];
6423 let lanes = vec![
6424 (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
6425 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6426 // A second audio track, turned down: the gain lines are per lane,
6427 // so the two must not run into one another.
6428 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6429 ];
6430 let limiter = Limiter {
6431 ceiling_db: -1.5,
6432 on: true,
6433 };
6434 let bytes = super::emit(
6435 &dir,
6436 &sources,
6437 &lanes,
6438 &[0.0, 3.0, -6.5],
6439 &[],
6440 &[],
6441 &[],
6442 &[],
6443 &[],
6444 (1280, 720),
6445 Some(23.976023976023978),
6446 crate::tonemap::Preset::default(),
6447 false,
6448 true,
6449 crate::export::EncoderSeat::default(),
6450 limiter,
6451 None,
6452 0,
6453 );
6454 assert_eq!(
6455 String::from_utf8_lossy(&bytes),
6456 "edith 30\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
6457 limiter -1.5 on\nsource 0 a.mp4\n\
6458 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\
6459 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6460 gain audio 1 3.0\ngain audio 2 -6.5\n",
6461 "the mix is lines of its own, the gains after the lanes they name"
6462 );
6463 let back = parse(&bytes, &dir).expect("parse");
6464 assert_eq!(back.lanes, lanes);
6465 assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
6466 assert_eq!(back.limiter, limiter);
6467 assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
6468
6469 // ...and the dialect before it, which carried none of the three: a v8
6470 // file mixes flat, limits nothing, and says nothing about its rate.
6471 let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6472 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6473 let old = parse(v8, &dir).expect("v8 parses");
6474 assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
6475 assert_eq!(old.limiter, Limiter::default());
6476 assert_eq!(old.fps, None);
6477 // A v9 file may leave all three out too, and means the same thing.
6478 assert_eq!(
6479 String::from_utf8_lossy(&emit(
6480 &dir,
6481 &old.sources,
6482 &old.lanes,
6483 &old.eq,
6484 &old.color,
6485 (1280, 720),
6486 old.playhead
6487 )),
6488 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6489 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"
6490 );
6491
6492 // Each of the three refuses by name, on its own line.
6493 for (text, want) in [
6494 (
6495 "edith 9\nfps nope\nsource 0 a.mp4\n",
6496 "line 2: \"nope\" is not a frame rate",
6497 ),
6498 (
6499 "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
6500 "line 2: limiter is on or off, not \"maybe\"",
6501 ),
6502 (
6503 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
6504 "line 4: gain names a lane that is not there",
6505 ),
6506 (
6507 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
6508 "line 4: gain names \"lane\", not a lane kind",
6509 ),
6510 ] {
6511 assert_eq!(
6512 parse(text.as_bytes(), &dir).unwrap_err().to_string(),
6513 want,
6514 "{text:?}"
6515 );
6516 }
6517 // A hand-written ceiling nothing could limit at is clamped, not taken.
6518 let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
6519 assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
6520 }
6521
6522 /// The refusals the colour grammar adds, each naming its line.
6523 #[test]
6524 fn a_malformed_colour_names_its_line() {
6525 let dir = PathBuf::from("/proj");
6526 let head = "edith 6\nsource 0 a.mp4\n";
6527 // v6, deliberately: the colour grammar is the same one v7 inherits, and
6528 // a v6 clip line is one field shorter.
6529 for (file, want) in [
6530 (
6531 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
6532 "line 3: color wants 4 fields, found 3",
6533 ),
6534 (
6535 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"),
6536 "line 3: color wants 1 fields, found 2",
6537 ),
6538 (
6539 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6540 "line 3: \"warm\" is not a number",
6541 ),
6542 // The two values the format cannot write and read back as itself.
6543 (
6544 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6545 "line 3: \"inf\" is not a number",
6546 ),
6547 (
6548 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
6549 "line 3: \"NaN\" is not a number",
6550 ),
6551 (
6552 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
6553 "line 4: clip names color 1 of 1",
6554 ),
6555 (
6556 format!("{head}video 1 0 0 5 0 - - 0\n"),
6557 "line 3: clip names color 0 of 0",
6558 ),
6559 // A clip's colour field is not optional in v6, and the table has to
6560 // be declared before the clip that names it.
6561 (
6562 format!("{head}video 1 0 0 5 0 - -\n"),
6563 "line 3: clip wants 7 fields, found 6",
6564 ),
6565 (
6566 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
6567 "line 4: color after a clip",
6568 ),
6569 // ...and a colour line in a file that predates them is a corrupt one.
6570 (
6571 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
6572 "line 3: unknown keyword \"color\"",
6573 ),
6574 ] {
6575 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6576 }
6577 }
6578
6579 /// The cut shapes are two more spellings of the same band grammar: they
6580 /// round-trip bit-exactly like the others, and a cut's gain is written as
6581 /// it was given even though the filter ignores it.
6582 #[test]
6583 fn cut_bands_round_trip_as_lc_and_hc() {
6584 let dir = PathBuf::from("/proj");
6585 let sources = vec![source("/proj/a.mp4", 0)];
6586 let eq = vec![EqParams {
6587 bands: vec![
6588 band_of(80.0, 0.0, 0.707, BandKind::LowCut),
6589 band_of(12_000.0, -6.5, 0.5, BandKind::HighCut),
6590 ],
6591 }];
6592 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], Vec::new());
6593 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
6594 assert!(
6595 String::from_utf8_lossy(&bytes).contains("eq 80.0:0.0:0.707:lc 12000.0:-6.5:0.5:hc\n"),
6596 "the cut shapes are spelled lc and hc"
6597 );
6598
6599 let back = parse(&bytes, &dir).expect("parse");
6600 assert_eq!(back.eq, eq, "both cut bands come back as they went in");
6601 assert_eq!(back.lanes, lanes);
6602 }
6603
6604 /// The refusals the eq grammar adds, each naming its line.
6605 #[test]
6606 fn a_malformed_equalizer_names_its_line() {
6607 let dir = PathBuf::from("/proj");
6608 let head = "edith 5\nsource 0 a.mp4\n";
6609 for (file, want) in [
6610 (
6611 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
6612 "line 3: band wants 4 fields, found 3",
6613 ),
6614 (
6615 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
6616 "line 3: \"notch\" is not a band shape",
6617 ),
6618 (
6619 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
6620 "line 3: \"wide\" is not a number",
6621 ),
6622 // Neither of the two values a coefficient cannot be built from, and
6623 // NaN would not even compare equal to itself on the way back.
6624 (
6625 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6626 "line 3: \"inf\" is not a number",
6627 ),
6628 (
6629 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6630 "line 3: \"NaN\" is not a number",
6631 ),
6632 (
6633 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
6634 "line 4: clip names eq 1 of 1",
6635 ),
6636 (
6637 format!("{head}video 1 0 0 5 0 - 0\n"),
6638 "line 3: clip names eq 0 of 0",
6639 ),
6640 // A clip's eq field is not optional in v5, and the table has to be
6641 // declared before the clip that names it.
6642 (
6643 format!("{head}video 1 0 0 5 0 -\n"),
6644 "line 3: clip wants 6 fields, found 5",
6645 ),
6646 (
6647 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
6648 "line 4: eq after a clip",
6649 ),
6650 // ...and an eq line in a file that predates them is a corrupt file.
6651 (
6652 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
6653 "line 3: unknown keyword \"eq\"",
6654 ),
6655 ] {
6656 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6657 }
6658 }
6659
6660 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
6661 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
6662 /// and not one byte else.
6663 #[test]
6664 fn a_v4_file_equalizes_nothing() {
6665 let dir = PathBuf::from("/proj");
6666 let (_, sources, lanes) = doc();
6667 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6668 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
6669 let old = parse(v4, &dir).expect("v4 parses");
6670 assert_eq!(
6671 (&old.sources, &old.lanes, old.playhead),
6672 (&sources, &lanes, 12)
6673 );
6674 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
6675 assert_eq!(
6676 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
6677 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6678 source 2 /elsewhere/b.mp4\n\
6679 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\
6680 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n"
6681 );
6682 // An empty lane's line is still the whole of that lane, eq or no eq.
6683 let empty = parse(
6684 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
6685 &dir,
6686 )
6687 .expect("parse");
6688 assert!(empty.lanes[1].1.is_empty());
6689 }
6690
6691 /// The other half of the compatibility promise: a v3 file is a v4 one
6692 /// without the lane numbers, and a v2 file names no audio stream and means
6693 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
6694 /// they always were, and saving either writes v5 with nothing else changed.
6695 #[test]
6696 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
6697 let dir = PathBuf::from("/proj");
6698 let (_, _, lanes) = doc();
6699 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6700 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6701 let old = parse(v3, &dir).expect("v3 parses");
6702 assert_eq!(
6703 (&old.sources, &old.lanes, old.playhead),
6704 (
6705 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
6706 &lanes,
6707 12
6708 ),
6709 "a v3 file loads as exactly the state its v5 twin does"
6710 );
6711 // ...and re-saved it *is* that twin: the magic and a lane number per
6712 // clip line, and not one byte else.
6713 assert_eq!(
6714 flat(&dir, &old.sources, &old.lanes, old.playhead),
6715 flat(&dir, &old.sources, &lanes, 12),
6716 );
6717
6718 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
6719 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6720 let back = parse(v2, &dir).expect("v2 parses");
6721 assert_eq!(
6722 back.sources,
6723 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
6724 );
6725 assert_eq!(back.lanes, lanes);
6726
6727 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6728 assert_eq!(
6729 String::from_utf8_lossy(&v5),
6730 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6731 source 0 /elsewhere/b.mp4\n\
6732 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\
6733 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
6734 "a re-saved v2 project differs only by its version, the lane \
6735 numbers, the streams it always meant and an equalizer it has none of"
6736 );
6737 let again = parse(&v5, &dir).expect("v5 parses");
6738 assert_eq!(again.sources, back.sources);
6739 }
6740
6741 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
6742 /// lanes, and saving it again writes v5.
6743 #[test]
6744 fn a_v1_file_loads_as_two_grouped_lanes() {
6745 let dir = PathBuf::from("/proj");
6746 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
6747 let back = parse(v1, &dir).expect("v1 parses");
6748 assert_eq!(
6749 back.lanes[0].1,
6750 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
6751 "v1 clips queue up: the second starts where the first ended"
6752 );
6753 assert_eq!(
6754 back.lanes,
6755 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
6756 "one take per clip, on both lanes"
6757 );
6758 assert_eq!(back.playhead, 5);
6759 // Saved again it is the current version, which round-trips to the
6760 // same document.
6761 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6762 assert!(v5.starts_with(b"edith 30\n"));
6763 let again = parse(&v5, &dir).expect("v5 parses");
6764 assert_eq!(again.lanes, back.lanes);
6765 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
6766 for (bytes, want) in [
6767 (
6768 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
6769 "line 3: unknown keyword \"video\"",
6770 ),
6771 (
6772 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
6773 "line 3: unknown keyword \"clip\"",
6774 ),
6775 ] {
6776 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
6777 }
6778 }
6779
6780 /// A gap is the absence of a line, so a lane's placements must arrive in
6781 /// order and never overlap -- the invariant the whole model rests on.
6782 #[test]
6783 fn a_lane_out_of_order_or_overlapping_is_refused() {
6784 let dir = PathBuf::from("/proj");
6785 for bytes in [
6786 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
6787 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
6788 ] {
6789 let err = parse(bytes, &dir).unwrap_err().to_string();
6790 assert!(err.starts_with("line 4: clip at "), "{err}");
6791 }
6792 // The lanes are independent, so a video line never crowds an audio one.
6793 assert!(
6794 parse(
6795 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
6796 &dir
6797 )
6798 .is_ok()
6799 );
6800 // ...and a lane may be empty as long as the other one is not.
6801 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
6802 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
6803 }
6804
6805 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
6806 /// and wrap in release, and a wrapped end passes the overlap check --
6807 /// crafted numbers must be refused by name, in both dialects.
6808 #[test]
6809 fn a_clip_whose_end_overflows_is_refused() {
6810 let dir = PathBuf::from("/proj");
6811 for bytes in [
6812 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
6813 // Two of them: the second would land *before* the first once wrapped.
6814 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
6815 // v1 has no `start` field, but its queue reaches the same ceiling.
6816 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
6817 ] {
6818 let err = parse(bytes, &dir).unwrap_err().to_string();
6819 assert!(
6820 err.contains("runs past the last frame there is"),
6821 "not refused by name: {err}"
6822 );
6823 }
6824 }
6825
6826 /// The relocatability promise, from the two directions a project path
6827 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
6828 /// clip.mp4`, whose parent is `""`) and a directory reached through a
6829 /// symlink. Both used to emit absolute source lines.
6830 #[test]
6831 fn a_non_canonical_project_path_still_writes_relative_sources() {
6832 assert_eq!(
6833 project_dir(Path::new("a.edith")),
6834 std::env::current_dir().expect("cwd"),
6835 "a bare filename is saved into the working directory"
6836 );
6837
6838 let dir = crate::scratch::Scratch::dir("ve_edith_link");
6839 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
6840 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
6841 let source = dir.join("real/a.mp4");
6842 let path = dir.join("link/p.edith");
6843
6844 let one = [clip(0, 0, 30, 0, None)];
6845 let entry = Source {
6846 path: source,
6847 audio_stream: 1, ..Default::default()
6848 };
6849 save(
6850 &path,
6851 &[entry],
6852 &two(one.to_vec(), one.to_vec()),
6853 &[],
6854 &[],
6855 &[],
6856 &[],
6857 &[],
6858 &[],
6859 (1280, 720),
6860 None,
6861 crate::tonemap::Preset::default(),
6862 false,
6863 true,
6864 crate::export::EncoderSeat::default(),
6865 Limiter::default(),
6866 None,
6867 0,
6868 )
6869 .expect("save");
6870 let bytes = std::fs::read(&path).expect("read back");
6871 assert_eq!(
6872 String::from_utf8_lossy(&bytes),
6873 "edith 30\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
6874 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"
6875 );
6876 // Loading rejoins the *given* directory, so the file is reached by the
6877 // way the project was opened -- the same file, through the link, still
6878 // playing the stream it was saved on.
6879 assert_eq!(
6880 load(&path).expect("load").sources,
6881 vec![Source {
6882 path: dir.join("link/a.mp4"),
6883 audio_stream: 1, ..Default::default()
6884 }]
6885 );
6886 std::fs::remove_dir_all(&dir).expect("cleanup");
6887 }
6888
6889 #[test]
6890 fn escapes_survive_the_bytes_json_would_not() {
6891 let dir = PathBuf::from("/proj");
6892 // A newline and a percent in a filename, plus a non-UTF-8 byte.
6893 let nasty = Source {
6894 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
6895 audio_stream: 0, ..Default::default()
6896 };
6897 let bytes = flat(
6898 &dir,
6899 std::slice::from_ref(&nasty),
6900 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
6901 0,
6902 );
6903 assert_eq!(
6904 bytes.iter().filter(|&&b| b == b'\n').count(),
6905 6,
6906 "the escaped newline must not become a line break: magic, playhead, \
6907 resolution, source, the clip, and the empty audio lane's own line"
6908 );
6909 let back = parse(&bytes, &dir).expect("parse");
6910 // The spaces in it are the reason the stream field leads rather than
6911 // trails: everything after the first one is path.
6912 assert_eq!(back.sources, vec![nasty]);
6913 }
6914
6915 /// A `flags` line names its lane the way a gain does and carries only the
6916 /// switches its kind of lane can have. A lane with none has no line, so a
6917 /// v23 file -- which has no such line -- parses with every switch clear, and
6918 /// one that carries the line before v24 is an unknown keyword.
6919 #[test]
6920 fn lane_switches_parse_by_kind_and_a_v23_file_has_none() {
6921 let dir = PathBuf::from("/proj");
6922 let doc = parse(
6923 b"edith 24\nvideo 1\naudio 1\nsub 1\nflags video 1 hidden locked\nflags audio 1 muted\nflags sub 1 hidden\n",
6924 &dir,
6925 )
6926 .expect("a v24 file with switches parses");
6927 assert_eq!(
6928 doc.flags,
6929 vec![
6930 LaneFlags {
6931 hidden: true,
6932 muted: false,
6933 locked: true,
6934 pan: 0.0,
6935 },
6936 LaneFlags {
6937 hidden: false,
6938 muted: true,
6939 locked: false,
6940 pan: 0.0,
6941 },
6942 LaneFlags {
6943 hidden: true,
6944 muted: false,
6945 locked: false,
6946 pan: 0.0,
6947 },
6948 ]
6949 );
6950
6951 let plain = parse(b"edith 24\nvideo 1\naudio 1\n", &dir).expect("no switches");
6952 assert_eq!(plain.flags, vec![LaneFlags::default(); 2]);
6953 let old = parse(b"edith 23\nvideo 1\naudio 1\n", &dir).expect("a v23 file loads");
6954 assert_eq!(
6955 old.flags,
6956 vec![LaneFlags::default(); 2],
6957 "every switch clear"
6958 );
6959
6960 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
6961 assert!(
6962 refuse(b"edith 24\nvideo 1\nflags video 1 hidden hidden\n").contains("twice"),
6963 "a switch named twice"
6964 );
6965 assert!(
6966 refuse(b"edith 24\naudio 1\nflags audio 1 hidden\n").contains("cannot be set"),
6967 "a hidden audio lane"
6968 );
6969 assert!(
6970 refuse(b"edith 24\nvideo 1\nflags video 1 muted\n").contains("cannot be set"),
6971 "a muted video lane"
6972 );
6973 assert!(
6974 refuse(b"edith 24\nvideo 1\nflags video 2 hidden\n").contains("not there"),
6975 "a lane that is not there"
6976 );
6977 assert!(
6978 refuse(b"edith 24\nvideo 1\nflags video 1\n").contains("no switch"),
6979 "a line with no switch"
6980 );
6981 assert!(
6982 refuse(b"edith 23\nvideo 1\nflags video 1 hidden\n").contains("unknown keyword"),
6983 "a flags line before v24 is not a dialect"
6984 );
6985 }
6986
6987 #[test]
6988 fn a_duck_line_round_trips_and_is_bounded_by_name() {
6989 let dir = PathBuf::from("/proj");
6990 let head = "edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6991 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6992 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6993 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
6994 let ok = parse(
6995 format!("{head}duck audio 2 1 -12.0 -40.0 80.0 400.0\n").as_bytes(),
6996 &dir,
6997 )
6998 .expect("a duck of A2 under A1 parses");
6999 assert_eq!(
7000 ok.ducks,
7001 vec![
7002 vec![],
7003 vec![],
7004 vec![crate::duck::Duck {
7005 under: 0,
7006 depth_db: -12.0,
7007 threshold_db: -40.0,
7008 attack_ms: 80.0,
7009 release_ms: 400.0,
7010 }]
7011 ],
7012 "one list per lane, the key named 0-based in the struct"
7013 );
7014 let refuse = |line: &str| {
7015 parse(format!("{head}{line}\n").as_bytes(), &dir)
7016 .unwrap_err()
7017 .to_string()
7018 };
7019 assert!(refuse("duck audio 2 2 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
7020 assert!(refuse("duck audio 2 3 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
7021 assert!(refuse("duck audio 2 0 -12.0 -40.0 80.0 400.0").contains("lane 0"));
7022 assert!(refuse("duck audio 2 1 -41.0 -40.0 80.0 400.0").contains("out of its range"));
7023 assert!(refuse("duck audio 2 1 -12.0 -40.0 0.0 400.0").contains("out of its range"));
7024 assert!(refuse("duck video 1 1 -12.0 -40.0 80.0 400.0").contains("not an audio lane"));
7025 // A dialect before v25 has no ducks, so the same line is an unknown one.
7026 let v24 = format!(
7027 "{}duck audio 2 1 -12.0 -40.0 80.0 400.0\n",
7028 head.replacen("edith 25", "edith 24", 1)
7029 );
7030 assert!(
7031 parse(v24.as_bytes(), &dir)
7032 .unwrap_err()
7033 .to_string()
7034 .contains("unknown keyword"),
7035 "a v24 file cannot carry a duck"
7036 );
7037 // ...and a v24 file without one still loads, with every lane unducked.
7038 let old = parse(head.replacen("edith 25", "edith 24", 1).as_bytes(), &dir)
7039 .expect("v24 still loads");
7040 assert!(old.ducks.iter().all(Vec::is_empty));
7041 }
7042
7043 /// The v42 `effect` lines: a clip's whole stack round-trips in order, switch and
7044 /// every value included, through the same `save_flagged` every save takes; a project
7045 /// with no effect keeps its older header; a v41 file refuses the line; a bad line is
7046 /// refused by name.
7047 #[test]
7048 fn effect_lines_round_trip_in_v42_and_older_files_refuse_them() {
7049 use crate::effects::{Effect, EffectKind};
7050 let dir = std::env::temp_dir().join(format!("edith-effects-{}", std::process::id()));
7051 std::fs::create_dir_all(&dir).unwrap();
7052 let path = dir.join("fx.edith");
7053 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7054 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
7055 save_flagged(
7056 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7057 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7058 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7059 )
7060 .expect("saves");
7061 std::fs::read_to_string(&path).unwrap()
7062 };
7063 let plain = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7064 let before = save(&plain);
7065 assert!(!before.starts_with("edith 42") && !before.contains("effect"), "{before}");
7066 let mut lanes = plain.clone();
7067 let mut blur = Effect::new(EffectKind::Blur);
7068 blur.set("radius", 12.25).unwrap();
7069 let mut key = Effect::new(EffectKind::ChromaKey);
7070 key.on = false;
7071 key.set("tolerance", 0.123_456_7).unwrap();
7072 let stack = vec![Effect::new(EffectKind::Vignette), blur, key, Effect::new(EffectKind::EllipseMask)];
7073 lanes[0].1[0].effects = stack.clone();
7074 let text = save(&lanes);
7075 assert!(text.starts_with("edith 42\n"), "an effect makes it v42: {text}");
7076 assert!(text.contains("\neffect video 1 0 blur 1 12.25\n"), "{text}");
7077 assert!(text.contains("\neffect video 1 0 chroma_key 0 0 255 0 0.1234567 0.1 0.5\n"), "{text}");
7078 let back = load(&path).expect("v42 loads");
7079 assert_eq!(back.lanes[0].1[0].effects, stack, "order, switches and values survive");
7080 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7081 lanes[0].1[0].effects.clear();
7082 assert_eq!(save(&lanes), before, "no effect: the bytes it was");
7083 std::fs::remove_dir_all(&dir).ok();
7084
7085 let dir = PathBuf::from("/proj");
7086 let video_head = "edith 42\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7087 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";
7088 let doc = parse(format!("{video_head}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).expect("parses");
7089 assert_eq!(doc.lanes[0].1[0].effects[0].get("amount"), Some(0.5));
7090 let refuse = |line: &str| parse(format!("{video_head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7091 assert!(refuse("effect video 1 0 sparkle 1 0.5").contains("not one"));
7092 assert!(refuse("effect video 1 0 sharpen 2 0.5").contains("not 0 or 1"));
7093 assert!(refuse("effect video 1 0 sharpen 1 9").contains("out of its range"));
7094 assert!(refuse("effect video 1 0 vignette 1 0.5").contains("wants 2 values"));
7095 assert!(refuse("effect video 1 4 sharpen 1 0.5").contains("does not have"));
7096 assert!(refuse("effect audio 1 0 sharpen 1 0.5").contains("wants a video clip"));
7097 assert!(refuse("effect video 2 0 sharpen 1 0.5").contains("not there"));
7098 let v41 = video_head.replacen("edith 42", "edith 41", 1);
7099 let err = parse(format!("{v41}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).unwrap_err().to_string();
7100 assert!(err.contains("unknown keyword \"effect\""), "{err}");
7101 }
7102
7103 /// The v50 pan lines: a clip pan and a lane pan round-trip, a project with neither keeps its
7104 /// header and its bytes, and an out-of-range or unknown-lane pan is refused by name.
7105 #[test]
7106 fn pan_lines_round_trip_in_v50() {
7107 let dir = std::env::temp_dir().join(format!("edith-pan-{}", std::process::id()));
7108 std::fs::create_dir_all(&dir).unwrap();
7109 let path = dir.join("pan.edith");
7110 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7111 let save = |lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]| {
7112 save_flagged(
7113 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7114 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7115 Limiter::default(), None, 0, flags, &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7116 )
7117 .expect("saves");
7118 std::fs::read_to_string(&path).unwrap()
7119 };
7120 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))]);
7121 let before = save(&plain, &[]);
7122 assert!(!before.contains("pan"), "{before}");
7123 let mut lanes = plain.clone();
7124 lanes[1].1[1].pan = -25;
7125 let flags = [LaneFlags::default(), LaneFlags { pan: 0.5, locked: true, ..LaneFlags::default() }];
7126 let text = save(&lanes, &flags);
7127 assert!(text.starts_with("edith 50\n"), "{text}");
7128 assert!(text.contains("\nlanepan audio 1 0.5\n") && text.contains("\nclippan audio 1 1 -0.25\n"), "{text}");
7129 let back = load(&path).expect("v50 loads");
7130 assert_eq!(back.lanes[1].1[1].pan, -25);
7131 assert_eq!(back.lanes[1].1[0].pan, 0);
7132 assert_eq!(back.flags[1].pan, 0.5);
7133 assert!(back.flags[1].locked, "the switches stay");
7134 assert_eq!(save(&back.lanes, &back.flags), text, "saved again: the same bytes");
7135 let dirp = PathBuf::from("/proj");
7136 let head = "edith 50\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7137 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";
7138 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7139 assert!(refuse("clippan audio 1 0 2").contains("out of its range"));
7140 assert!(refuse("clippan audio 1 4 0.5").contains("does not have"));
7141 assert!(refuse("lanepan audio 3 0.5").contains("not there"));
7142 assert!(refuse("lanepan video 1 0.5").contains("not an audio lane"));
7143 let old = head.replacen("edith 50", "edith 49", 1);
7144 let err = parse(format!("{old}lanepan audio 1 0.5\n").as_bytes(), &dirp).unwrap_err().to_string();
7145 assert!(err.contains("unknown keyword"), "{err}");
7146 std::fs::remove_dir_all(&dir).ok();
7147 }
7148
7149
7150 /// A custom bezier ease is a v56 word: a v56 file loads it and a v55 file naming one is refused.
7151 #[test]
7152 fn bezier_ease_is_a_v56_word() {
7153 let dirp = PathBuf::from("/proj");
7154 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7155 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7156 let line = "tkeys video 1 0 0:lin:0,0,1,0,0,0,0,0,1 20:b420_0_580_1000:0,0,2,0,0,0,0,0,0.5\n";
7157 let doc = parse(format!("edith 56\n{head}{line}").as_bytes(), &dirp).expect("a v56 file loads");
7158 let bezier = crate::transform::Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
7159 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Bezier(bezier));
7160 let err = parse(format!("edith 55\n{head}{line}").as_bytes(), &dirp).unwrap_err().to_string();
7161 assert!(err.contains("tkeys ease"), "{err}");
7162 }
7163
7164 /// The v55 pitch lines: a clip's semitones round-trip and a project with none is the bytes a
7165 /// v51 one was; an out-of-range, unknown-lane or unknown-clip pitch is refused by name, and a
7166 /// pitch line under an older header is refused as unknown.
7167 #[test]
7168 fn pitch_lines_round_trip_in_v55() {
7169 let dir = std::env::temp_dir().join(format!("edith-pitch-{}", std::process::id()));
7170 std::fs::create_dir_all(&dir).unwrap();
7171 let path = dir.join("pitch.edith");
7172 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7173 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
7174 save_flagged(
7175 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7176 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7177 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7178 )
7179 .expect("saves");
7180 std::fs::read_to_string(&path).unwrap()
7181 };
7182 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))]);
7183 let before = save(&plain);
7184 assert!(!before.contains("pitch"), "{before}");
7185 assert!(!before.starts_with("edith 55"), "{before}");
7186 let mut lanes = plain.clone();
7187 lanes[1].1[1].pitch = -7;
7188 let text = save(&lanes);
7189 assert!(text.starts_with("edith 55\n"), "{text}");
7190 assert!(text.contains("\npitch audio 1 1 -7\n"), "{text}");
7191 let back = load(&path).expect("v55 loads");
7192 assert_eq!(back.lanes[1].1[1].pitch, -7);
7193 assert_eq!(back.lanes[1].1[0].pitch, 0);
7194 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7195 let dirp = PathBuf::from("/proj");
7196 let head = "edith 55\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7197 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";
7198 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7199 assert!(refuse("pitch audio 1 0 13").contains("out of its range"));
7200 assert!(refuse("pitch audio 1 0 1.5").contains("out of its range"));
7201 assert!(refuse("pitch audio 1 4 3").contains("does not have"));
7202 assert!(refuse("pitch audio 3 0 3").contains("not there"));
7203 assert!(refuse("pitch video 1 0 3").contains("not an audio lane"));
7204 let old = head.replacen("edith 55", "edith 51", 1);
7205 let err = parse(format!("{old}pitch audio 1 0 3\n").as_bytes(), &dirp).unwrap_err().to_string();
7206 assert!(err.contains("unknown keyword"), "{err}");
7207 std::fs::remove_dir_all(&dir).ok();
7208 }
7209
7210 /// The v51 library lines: bins, filed sources and starred ones round-trip; a project with
7211 /// none keeps its v50 bytes; the lines are refused in v50 and bad ones by name.
7212 #[test]
7213 fn library_lines_round_trip_with_effect_keys_in_v56() {
7214 use crate::project::Bin;
7215 let dir = std::env::temp_dir().join(format!("edith-bins-{}", std::process::id()));
7216 std::fs::create_dir_all(&dir).unwrap();
7217 let path = dir.join("bins.edith");
7218 let mut src = vec![
7219 Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() },
7220 Source { path: dir.join("b.mp4"), audio_stream: 0, ..Default::default() },
7221 ];
7222 let mut lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7223 let mut mask = crate::effects::Effect::new(crate::effects::EffectKind::EllipseMask);
7224 mask.keys = vec![crate::effects::EffectKey {
7225 at: 0, values: [0.5, 0.5, 0.4, 0.4, 0.02, 0.0], ease: KeyEase::Linear,
7226 }];
7227 lanes[0].1[0].effects = vec![mask];
7228 let save = |src: &[Source], bins: &[Bin]| {
7229 let main = encode_flagged(
7230 &dir, src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7231 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7232 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7233 );
7234 let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS, None, crate::speech::DeviceChoice::Auto);
7235 std::fs::write(&path, &bytes).unwrap();
7236 String::from_utf8(bytes).unwrap()
7237 };
7238 let plain = save(&src, &[]);
7239 assert!(plain.starts_with("edith 45\n") || !plain.starts_with("edith 51"), "{plain}");
7240 assert!(!plain.contains("bin") && !plain.contains("srcfav"), "{plain}");
7241 let bins = vec![
7242 Bin { id: 1, parent: 0, name: "Interviews \"A\"".into() },
7243 Bin { id: 3, parent: 1, name: "B roll".into() },
7244 ];
7245 src[0].bin = 3;
7246 src[1].fav = true;
7247 src[1].bin = 1;
7248 let text = save(&src, &bins);
7249 // An effect key is v56, and the library and the notes lines keep it there.
7250 assert!(text.starts_with("edith 56\n"), "{text}");
7251 assert!(text.contains("\nsrcbin 0 3\n") && text.contains("\nsrcfav 1\n"), "{text}");
7252 assert!(text.contains("\nekeys video 1 0 0 0:lin:0.5,0.5,0.4,0.4,0.02,0\n") && text.contains("\nnotes Two cuts\n"), "{text}");
7253 let back = load(&path).expect("v56 loads");
7254 assert_eq!(back.notes, "Two cuts");
7255 assert_eq!(back.bins, bins);
7256 assert_eq!((back.sources[0].bin, back.sources[0].fav), (3, false));
7257 assert_eq!((back.sources[1].bin, back.sources[1].fav), (1, true));
7258 assert_eq!(save(&back.sources, &back.bins), text, "saved again: the same bytes");
7259 let dirp = PathBuf::from("/proj");
7260 let head = "edith 51\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7261 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";
7262 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7263 assert!(refuse("bin 1 0").contains("wants an id"));
7264 assert!(refuse("bin 0 0 x").contains("not a new id"));
7265 assert!(refuse("bin 1 0 x\nbin 1 0 y").contains("not a new id"));
7266 assert!(refuse("bin 2 1 x").contains("not a top-level bin"));
7267 assert!(refuse("bin 1 0 x\nbin 2 0 X").contains("two bins named"));
7268 assert!(refuse("bin 1 0 x\nbin 2 1 y\nbin 3 2 z").contains("not a top-level bin"));
7269 assert!(refuse("srcbin 0 9").contains("not defined"));
7270 assert!(refuse("bin 1 0 x\nsrcbin 4 1").contains("does not have"));
7271 assert!(refuse("srcfav 7").contains("does not have"));
7272 let old = head.replacen("edith 51", "edith 50", 1);
7273 for line in ["bin 1 0 x", "srcfav 0"] {
7274 let err = parse(format!("{old}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7275 assert!(err.contains("unknown keyword"), "{err}");
7276 }
7277 std::fs::remove_dir_all(&dir).ok();
7278 }
7279
7280 /// The v41 `voice` lines: every processor of an audio lane (the noise profile included)
7281 /// round-trips bit for bit; a lane with no voice setting writes none, so a project nobody
7282 /// has cleaned keeps its older header and its exact bytes; a v40 file loads with every
7283 /// processor off and refuses the lines; a number out of range is refused by name.
7284 /// The v43 look lines: wheels, curves and a LUT path (relative inside the
7285 /// project folder) round trip bit-exactly; a grade without a look writes none
7286 /// and stays under its old header; a missing LUT still loads; bad lines are
7287 /// refused by name.
7288 #[test]
7289 fn look_lines_round_trip_in_v43() {
7290 use crate::color::{Curve, Look, Wheels};
7291 let dir = std::env::temp_dir().join(format!("edith-look-{}", std::process::id()));
7292 std::fs::create_dir_all(dir.join("luts")).unwrap();
7293 let cube = dir.join("luts/warm look.cube");
7294 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();
7295 let path = dir.join("look.edith");
7296 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7297 let lanes = two(
7298 vec![Clip { color: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { color: Some(1), ..clip(30, 0, 30, 0, Some(0)) }],
7299 vec![clip(0, 0, 60, 0, Some(0))],
7300 );
7301 let look = Look {
7302 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] },
7303 curves: [
7304 Curve::new(&[[0.25, 0.2], [0.75, 0.8]]).unwrap(),
7305 Curve::default(),
7306 Curve::new(&[[0.0, 0.1], [0.5, 0.5], [1.0, 0.95]]).unwrap(),
7307 Curve::default(),
7308 ],
7309 lut: Some(crate::cube::LutRef::open(&cube)),
7310 lut_mix: 0.7,
7311 };
7312 let color = vec![ColorParams { contrast: 1.1, look, ..Default::default() }, ColorParams { tint: 0.2, ..Default::default() }];
7313 let save = |color: &[ColorParams]| {
7314 save_flagged(
7315 &path, &src, &lanes, &[], &[], &[], &[], color, &[], (1280, 720), Some(30.0),
7316 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7317 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7318 )
7319 .expect("saves");
7320 std::fs::read_to_string(&path).unwrap()
7321 };
7322 let text = save(&color);
7323 assert!(text.starts_with("edith 43\n"), "a look makes it v43: {text}");
7324 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}");
7325 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}");
7326 assert!(text.contains("\nlut 0 0.7 luts/warm look.cube\n"), "relative inside the folder: {text}");
7327 assert!(!text.contains("curve 1") && !text.contains("lut 1"), "no look, no lines");
7328 let back = load(&path).expect("v43 loads");
7329 assert_eq!(back.color, color, "every number survives");
7330 assert_eq!(save(&back.color), text, "a re-save is the same file");
7331 // No look: the old header and no look line.
7332 let plain = save(&[color[1], color[1]]);
7333 assert!(plain.starts_with("edith 3") && !plain.contains("wheels") && !plain.contains("\nlut "), "{plain}");
7334 // A missing LUT loads, and says why it cannot be used.
7335 let gone = text.replace("luts/warm look.cube", "luts/gone.cube");
7336 std::fs::write(&path, &gone).unwrap();
7337 let doc = load(&path).expect("a missing LUT still loads");
7338 let lut = doc.color[0].look.lut.expect("named");
7339 assert!(lut.problem().expect("missing").contains("cannot read"));
7340 std::fs::remove_dir_all(&dir).ok();
7341
7342 let head = "edith 43\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\n\
7343 video 1 0 0 30 0 - - 0 fit 1000 0 0 0 - 0 0\n";
7344 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7345 assert!(refuse("wheels 1 0:0:0:0 0:0:0:0 0:0:0:0").contains("names color 1"));
7346 assert!(refuse("wheels 0 2:0:0:0 0:0:0:0 0:0:0:0").contains("outside -1..1"));
7347 assert!(refuse("wheels 0 0:0:0 0:0:0:0 0:0:0:0").contains("4 values"));
7348 assert!(refuse("curve 0 cyan 0.1:0.2").contains("not master"));
7349 assert!(refuse("curve 0 red 0.5:0.2,0.4:0.3").contains("strictly increase"));
7350 assert!(refuse("curve 0 red 0.5").contains("<x>:<y>"));
7351 assert!(refuse("lut 0 1.5 a.cube").contains("0..=1"));
7352 assert!(refuse("lut 0 1.0").contains("<mix> <path>"));
7353 for old in ["edith 42", "edith 41"] {
7354 let older = head.replacen("edith 43", old, 1);
7355 assert!(parse(format!("{older}lut 0 1.0 a.cube\n").as_bytes(), &dir).is_err(), "a {old} file has no lut line");
7356 }
7357 }
7358
7359 #[test]
7360 fn voice_lines_round_trip_in_v41_and_older_files_load_with_them_off() {
7361 use crate::voice::{PROFILE_BANDS, Strength};
7362 let dir = std::env::temp_dir().join(format!("edith-voice-{}", std::process::id()));
7363 std::fs::create_dir_all(&dir).unwrap();
7364 let path = dir.join("voice.edith");
7365 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7366 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7367 let profile: Vec<f32> = (0..PROFILE_BANDS).map(|b| -80.0 + b as f32 * 0.1).collect();
7368 let fx = VoiceFx::clean_voice(Strength::Strong, profile, Some(-52.0));
7369 let save = |voices: &[VoiceFx]| {
7370 save_flagged(
7371 &path, &src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7372 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7373 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), voices, &[],
7374 )
7375 .expect("saves");
7376 std::fs::read_to_string(&path).unwrap()
7377 };
7378 let text = save(&[VoiceFx::default(), fx.clone()]);
7379 assert!(text.starts_with("edith 41\n"), "a voice makes it v41: {text}");
7380 for kind in ["gate", "nr", "comp", "deess"] {
7381 assert!(text.contains(&format!("\nvoice audio 1 {kind} 1 ")), "{kind}: {text}");
7382 }
7383 let back = load(&path).expect("v41 loads");
7384 assert_eq!(back.voices, vec![VoiceFx::default(), fx.clone()], "every number and the profile survive");
7385 // Saved again from what was loaded: the same bytes.
7386 let again = save(&back.voices);
7387 assert_eq!(again, text);
7388 // Only what differs from the default is written, and a lane with nothing writes no line.
7389 let comp_only = VoiceFx { comp: Compressor { on: true, ..Compressor::DEFAULT }, ..Default::default() };
7390 let text = save(&[VoiceFx::default(), comp_only.clone()]);
7391 assert_eq!(text.matches("\nvoice ").count(), 1, "{text}");
7392 assert_eq!(load(&path).unwrap().voices[1], comp_only);
7393 // Nothing set: not v41 and no voice line -- the bytes a v40 save wrote.
7394 let plain = save(&[VoiceFx::default(), VoiceFx::default()]);
7395 assert!(!plain.contains("voice") && plain.starts_with("edith 3") && !plain.starts_with("edith 41"), "{plain}");
7396 assert_eq!(save(&[]), plain, "no list is the same as a list of defaults");
7397 std::fs::remove_file(&path).ok();
7398
7399 let head = "edith 41\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7400 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";
7401 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7402 assert!(refuse("voice audio 1 gate 1 -45.0 2.0 150.0 60.0 5.0").contains("out of its range"));
7403 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"));
7404 assert!(refuse("voice audio 1 nr 1 0.6 -18.0 -").contains("no noise profile"));
7405 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");
7406 assert!(refuse("voice audio 1 gate 2 -45.0 2.0 150.0 60.0 -18.0").contains("not 0 or 1"));
7407 assert!(refuse("voice audio 1 gate 1 -45.0 2.0").contains("wants 6 fields"));
7408 assert!(refuse("voice audio 1 reverb 1").contains("not a processor"));
7409 assert!(refuse("voice audio 2 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not there"));
7410 assert!(refuse("voice video 1 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not an audio lane"));
7411 // A v40 file carries none, and the same line in one is an unknown keyword.
7412 let v40 = head.replacen("edith 41", "edith 40", 1);
7413 let err = parse(format!("{v40}voice audio 1 gate 1 -45.0 2.0 150.0 60.0 -18.0\n").as_bytes(), &dir)
7414 .unwrap_err()
7415 .to_string();
7416 assert!(err.contains("unknown keyword"), "{err}");
7417 let old = parse(v40.as_bytes(), &dir).expect("v40 still loads");
7418 assert!(old.voices.iter().all(|v| !v.is_active()) && old.voices.len() == 2);
7419 std::fs::remove_dir_all(&dir).ok();
7420 }
7421
7422 #[test]
7423 fn a_lane_ducked_under_two_keys_round_trips_in_v30() {
7424 let dir = PathBuf::from("/proj");
7425 let head = "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7426 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7427 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7428 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7429 audio 3 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7430 let two = format!(
7431 "{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"
7432 );
7433 let ok = parse(two.as_bytes(), &dir).expect("two keys for A3 parse");
7434 assert_eq!(ok.ducks[3].len(), 2, "both ducks kept, in file order");
7435 assert_eq!(ok.ducks[3][0].under, 0);
7436 assert_eq!(ok.ducks[3][1].under, 1);
7437 let refuse = |text: String| parse(text.as_bytes(), &dir).unwrap_err().to_string();
7438 assert!(
7439 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"))
7440 .contains("same key twice")
7441 );
7442 // A v29 file cannot hold two for one lane: refused by name, not dropped.
7443 let v29 = format!(
7444 "{}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",
7445 head.replacen("edith 30", "edith 29", 1)
7446 );
7447 assert!(refuse(v29).contains("names a lane twice"));
7448 }
7449
7450 #[test]
7451 fn a_wrong_first_line_is_refused_by_name() {
7452 let dir = PathBuf::from("/proj");
7453 let err = parse(b"edith 999\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
7454 .unwrap_err()
7455 .to_string();
7456 assert_eq!(err, "line 1: unsupported version 999");
7457 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
7458 assert_eq!(
7459 parse(junk, &dir).unwrap_err().to_string(),
7460 "line 1: not an edith file"
7461 );
7462 }
7463 }
7464
7465 /// The v34 `chapter` line: a project's chapters are saved in frame order and
7466 /// come back as they were, and a project with none is still a v33-or-older
7467 /// file. A v33 file loads with no chapters, and a chapter line in one is refused.
7468 #[test]
7469 fn chapters_round_trip_and_a_v33_file_loads_without_them() {
7470 use crate::project::Chapter;
7471 let dir = std::env::temp_dir().join(format!("edith-chapters-{}", std::process::id()));
7472 std::fs::create_dir_all(&dir).unwrap();
7473 let path = dir.join("chapters.edith");
7474 let chapters = vec![
7475 Chapter { frame: 0, title: "Intro".into() },
7476 Chapter { frame: 1500, title: "Setup: 100% \\ done".into() },
7477 ];
7478 save_flagged(
7479 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7480 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7481 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &chapters, &[], &CaptionStyle::default(), &[], &[],
7482 )
7483 .expect("a project with chapters saves");
7484 let text = std::fs::read_to_string(&path).unwrap();
7485 assert!(text.starts_with("edith 34\n"), "chapters make it v34: {text}");
7486 assert!(text.contains("\nchapter 0 Intro\nchapter 1500 "), "frame order, one line each: {text}");
7487 let back = load(&path).expect("v34 loads");
7488 assert_eq!(back.chapters, chapters);
7489 std::fs::remove_file(&path).ok();
7490
7491 // A project with no chapters keeps the header it always had.
7492 let bare = b"edith 33\nplayhead 0\nsource 0 a.mp4\n";
7493 let old = parse(bare, &dir).expect("a v33 file loads");
7494 assert!(old.chapters.is_empty());
7495 let mixed = parse(b"edith 33\nsource 0 a.mp4\nchapter 0 Intro\n", &dir)
7496 .unwrap_err()
7497 .to_string();
7498 assert_eq!(mixed, "line 3: unknown keyword \"chapter\"");
7499 // Out of order, a name with none, and a frame that is not a frame are refused.
7500 for line in ["chapter 10 B\nchapter 5 A\n", "chapter 5 \n", "chapter x Intro\n"] {
7501 let file = format!("edith 34\nsource 0 a.mp4\n{line}");
7502 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7503 }
7504 std::fs::remove_dir(&dir).ok();
7505 }
7506
7507 /// The v36 `marker` and `marknote` lines: markers (point and range, with and without a
7508 /// note, two on one frame) round-trip and make the file v36; a v35 file loads with none
7509 /// and refuses the lines; a project with no marker keeps its older header.
7510 #[test]
7511 fn markers_round_trip_and_a_v35_file_loads_without_them() {
7512 use crate::project::{Marker, MarkerColor};
7513 let dir = std::env::temp_dir().join(format!("edith-markers-{}", std::process::id()));
7514 std::fs::create_dir_all(&dir).unwrap();
7515 let path = dir.join("markers.edith");
7516 let mk = |frame, length, name: &str, note: &str, color| Marker { frame, length, name: name.into(), note: note.into(), color };
7517 let markers = vec![
7518 mk(0, 0, "Intro", "", MarkerColor::Blue),
7519 mk(100, 50, "Fix: 100% \\ the cut", "line one\nline two", MarkerColor::Red),
7520 mk(100, 0, "Same frame", "", MarkerColor::Purple),
7521 mk(900, 0, "Late", "has a note", MarkerColor::Green),
7522 ];
7523 let save = |markers: &[Marker]| {
7524 save_flagged(
7525 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7526 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7527 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, &CaptionStyle::default(), &[], &[],
7528 )
7529 .expect("saves");
7530 };
7531 save(&markers);
7532 let text = std::fs::read_to_string(&path).unwrap();
7533 assert!(text.starts_with("edith 36\n"), "markers make it v36: {text}");
7534 assert!(text.contains("\nmarker 0 0 blue Intro\nmarker 100 50 red "), "{text}");
7535 assert!(text.contains("\nmarknote 1 line one\\nline two\nmarknote 3 has a note\n"), "{text}");
7536 assert_eq!(load(&path).expect("v36 loads").markers, markers);
7537 save(&[]);
7538 let text = std::fs::read_to_string(&path).unwrap();
7539 assert!(!text.starts_with("edith 36") && !text.contains("marker"), "no markers, an older file: {text}");
7540 std::fs::remove_file(&path).ok();
7541
7542 let old = parse(b"edith 35\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v35 file loads");
7543 assert!(old.markers.is_empty());
7544 let mixed = parse(b"edith 35\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).unwrap_err().to_string();
7545 assert_eq!(mixed, "line 3: unknown keyword \"marker\"");
7546 for line in [
7547 "marker 10 0 red B\nmarker 5 0 red A\n",
7548 "marker 5 0 red \n",
7549 "marker 5 0 pink A\n",
7550 "marker x 0 red A\n",
7551 "marknote 0 hi\n",
7552 ] {
7553 let file = format!("edith 36\nsource 0 a.mp4\n{line}");
7554 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7555 }
7556 std::fs::remove_dir(&dir).ok();
7557 }
7558
7559 /// The v40 `capstyle` line: an animated caption style round-trips and makes the file v40;
7560 /// the default style writes no line and keeps the older header; a v36 file loads as the
7561 /// default and a v39 file refuses the line; a bad line is refused by name.
7562 /// The v40 `cuewords` lines: word times round-trip through the text, a cue without any
7563 /// writes no line, and a v39 file refuses the line.
7564 #[test]
7565 fn cue_word_times_round_trip_through_the_lines() {
7566 let dir = PathBuf::from("/proj");
7567 let cue = |text: &str, words: Vec<(i64, i64, String)>| crate::subtitle::Cue {
7568 start_us: 0,
7569 end_us: 3_000_000,
7570 text: text.into(),
7571 image: None,
7572 words,
7573 karaoke: Vec::new(),
7574 };
7575 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7576 track.cues = vec![
7577 cue("plain", vec![]),
7578 cue("two words", vec![(0, 1_000_000, "two".into()), (1_000_000, 2_500_000, "words".into())]),
7579 ];
7580 let lines = String::from_utf8(cue_word_lines(&[track])).unwrap();
7581 assert_eq!(lines, "cuewords 0 1 0 1000000 two 1000000 2500000 words\n");
7582 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7583 let doc = parse(file.as_bytes(), &dir).expect("v40 parses");
7584 assert_eq!(
7585 doc.cue_words,
7586 vec![(0, 1, vec![(0, 1_000_000, "two".to_string()), (1_000_000, 2_500_000, "words".to_string())])]
7587 );
7588 let old = file.replacen("edith 40", "edith 39", 1);
7589 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("unknown keyword"));
7590 for bad in ["cuewords 0 1 0 5\n", "cuewords 9 1 0 5 a\n", "cuewords 0 1 x 5 a\n"] {
7591 let f = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{bad}");
7592 assert!(parse(f.as_bytes(), &dir).is_err(), "{bad:?} is refused");
7593 }
7594 }
7595
7596 /// The whole project loop for word times: a track with uneven word times is written as
7597 /// `cuewords` lines, read back and attached to a freshly loaded project, and the cue then
7598 /// answers with the same uneven times -- until its text is retyped, which drops them.
7599 #[test]
7600 fn a_projects_cue_word_times_survive_the_file_and_die_with_a_text_edit() {
7601 let words = vec![(0, 200_000, "so".to_string()), (200_000, 2_600_000, "extraordinary".to_string())];
7602 let make = |words: Vec<(i64, i64, String)>| {
7603 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7604 track.cues = vec![crate::subtitle::Cue {
7605 start_us: 0,
7606 end_us: 3_000_000,
7607 text: "So extraordinary".into(),
7608 image: None,
7609 words,
7610 karaoke: Vec::new(),
7611 }];
7612 track
7613 };
7614 let mut project = crate::Project::single("/proj/a.mp4", 150);
7615 assert!(project.add_subtitles(&make(words.clone())));
7616 let lines = String::from_utf8(cue_word_lines(project.subtitles())).unwrap();
7617 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7618 let doc = parse(file.as_bytes(), &PathBuf::from("/proj")).expect("the file parses");
7619
7620 let mut loaded = crate::Project::single("/proj/a.mp4", 150);
7621 assert!(loaded.add_subtitles(&make(Vec::new())));
7622 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "the SRT alone has no word times");
7623 let mut loaded = loaded.with_cue_words(&doc.cue_words);
7624 assert_eq!(loaded.subtitles()[0].cues[0].real_words(), Some(&words[..]), "the uneven times are back");
7625 assert!(loaded.set_cue_text(0, 0, "Something else"));
7626 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "retyped words have no times");
7627 }
7628
7629 #[test]
7630 fn the_caption_style_round_trips_and_a_v36_file_loads_as_static() {
7631 use crate::captionanim::CaptionAnim;
7632 let dir = std::env::temp_dir().join(format!("edith-capstyle-{}", std::process::id()));
7633 std::fs::create_dir_all(&dir).unwrap();
7634 let path = dir.join("capstyle.edith");
7635 let save = |cs: &CaptionStyle| {
7636 save_flagged(
7637 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7638 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7639 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], cs, &[], &[],
7640 )
7641 .expect("saves");
7642 };
7643 let style = CaptionStyle {
7644 anim: CaptionAnim::Karaoke,
7645 highlight: [0x12, 0xab, 0xff],
7646 hl_box: true,
7647 uppercase: true,
7648 words_per_line: 3,
7649 };
7650 save(&style);
7651 let text = std::fs::read_to_string(&path).unwrap();
7652 assert!(text.starts_with("edith 40\n"), "{text}");
7653 assert!(text.contains("\ncapstyle karaoke 12abff 1 1 3\n"), "{text}");
7654 assert_eq!(load(&path).expect("v40 loads").caption_style, style);
7655 // The default is no line and an older header: the bytes an older build wrote.
7656 save(&CaptionStyle::default());
7657 let text = std::fs::read_to_string(&path).unwrap();
7658 assert!(!text.contains("capstyle") && !text.starts_with("edith 40"), "{text}");
7659 assert_eq!(load(&path).unwrap().caption_style, CaptionStyle::default());
7660 let old = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v36 file loads");
7661 assert_eq!(old.caption_style, CaptionStyle::default());
7662 let mixed = parse(b"edith 39\nsource 0 a.mp4\ncapstyle pop ffd600 0 0 0\n", &dir)
7663 .unwrap_err()
7664 .to_string();
7665 assert_eq!(mixed, "line 3: unknown keyword \"capstyle\"");
7666 for line in [
7667 "capstyle spin ffd600 0 0 0",
7668 "capstyle pop ffd60 0 0 0",
7669 "capstyle pop ffd600 2 0 0",
7670 "capstyle pop ffd600 0 0 99",
7671 "capstyle pop ffd600 0 0",
7672 ] {
7673 let file = format!("edith 40\nsource 0 a.mp4\n{line}\n");
7674 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7675 }
7676 std::fs::remove_file(&path).ok();
7677 std::fs::remove_dir(&dir).ok();
7678 }
7679
7680 /// Crafted files that declare more than any editor writes get a clear error,
7681 /// never an allocation or a hang.
7682 #[test]
7683 fn crafted_tables_over_the_caps_are_refused() {
7684 let dir = PathBuf::from("/proj");
7685 let head = "edith 40\nsource 0 a.mp4\n";
7686 let bands = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS + 1].join(" ");
7687 let words = "0 1 w ".repeat(MAX_CUE_WORDS + 1);
7688 let order = (0..=MAX_SEQUENCES).map(|i| i.to_string()).collect::<Vec<_>>().join(" ");
7689 for (file, what) in [
7690 (format!("{head}eq {bands}\n"), "equalizer"),
7691 (format!("{head}cuewords 0 0 {}\n", words.trim_end()), "cuewords"),
7692 (format!("edith 45\nsource 0 a.mp4\nseqorder {order}\n"), "seqorder"),
7693 ] {
7694 let err = parse(file.as_bytes(), &dir).expect_err(what).to_string();
7695 assert!(err.contains("at most") || err.contains("more than"), "{what}: {err}");
7696 }
7697 // And a table of exactly the cap still opens.
7698 let ok = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS].join(" ");
7699 assert!(parse(format!("{head}eq {ok}\n").as_bytes(), &dir).is_ok());
7700 // A project whose lists run past the cap is refused as a whole.
7701 let mut many = String::from("edith 40\nsource 0 a.mp4\n");
7702 for i in 0..=MAX_LIST_ENTRIES {
7703 many.push_str(&format!("chapter {i} c\n"));
7704 }
7705 let err = parse(many.as_bytes(), &dir).unwrap_err().to_string();
7706 assert!(err.contains("at most"), "{err}");
7707 }
7708
7709 #[test]
7710 fn the_newest_version_is_the_magic_line_the_writer_emits() {
7711 assert_eq!(MAGIC, format!("edith {NEWEST_VERSION}").as_bytes());
7712 }
7713
7714 #[test]
7715 fn malformed_lines_name_their_line_number() {
7716 let dir = PathBuf::from("/proj");
7717 let cases: [(&[u8], &str); 10] = [
7718 // v3 wants the stream before the path, and a path after it.
7719 (
7720 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
7721 "line 2: \"a.mp4\" is not a number",
7722 ),
7723 (
7724 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
7725 "line 2: source without a path",
7726 ),
7727 (
7728 b"edith 1\nsource a.mp4\nclip 0 5\n",
7729 "line 3: clip wants 3 fields, found 2",
7730 ),
7731 (
7732 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
7733 "line 3: \"five\" is not a number",
7734 ),
7735 (
7736 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
7737 "line 3: clip [5, 5) is empty",
7738 ),
7739 (
7740 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
7741 "line 3: clip [7, 5) is empty",
7742 ),
7743 (
7744 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
7745 "line 3: clip names source 1 of 1",
7746 ),
7747 (
7748 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
7749 "line 4: source after a clip",
7750 ),
7751 (
7752 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
7753 "line 3: unknown keyword \"\"",
7754 ),
7755 (
7756 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
7757 "line 3: playhead belongs once, before the sources",
7758 ),
7759 ];
7760 for (bytes, want) in cases {
7761 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
7762 }
7763 }
7764
7765 /// The emptied timeline writes and reads back: every lane declared, no clip
7766 /// on any of them, and the source that gave the project its frame rate still
7767 /// named. Nothing about the format changes for it -- an empty lane already
7768 /// had a line of its own.
7769 #[test]
7770 fn a_project_without_clips_round_trips() {
7771 let dir = PathBuf::from("/proj");
7772 let source = Source {
7773 path: PathBuf::from("/proj/a.mp4"),
7774 audio_stream: 0, ..Default::default()
7775 };
7776 let bytes = flat(
7777 &dir,
7778 std::slice::from_ref(&source),
7779 &two(Vec::new(), Vec::new()),
7780 0,
7781 );
7782 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
7783 assert_eq!(back.sources, vec![source]);
7784 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
7785 assert_eq!(back.playhead, 0);
7786 // Older dialects, where the two lanes are implied rather than declared.
7787 assert_eq!(
7788 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
7789 two(Vec::new(), Vec::new())
7790 );
7791 assert!(
7792 parse(b"edith 1\n", &dir)
7793 .expect("a project of nothing")
7794 .sources
7795 .is_empty()
7796 );
7797 }
7798
7799 /// Every truncation of a good file either parses or refuses; none panics.
7800 #[test]
7801 fn truncations_never_panic() {
7802 let (dir, sources, lanes) = doc();
7803 let bytes = flat(&dir, &sources, &lanes, 12);
7804 for cut in 0..bytes.len() {
7805 let _ = parse(&bytes[..cut], &dir);
7806 // ...and the same file with a byte lopped off the front, which
7807 // shifts every field into the wrong place.
7808 let _ = parse(&bytes[cut..], &dir);
7809 }
7810 // A % escape at the very end of a line has nothing to consume.
7811 assert_eq!(
7812 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
7813 .unwrap_err()
7814 .to_string(),
7815 "line 2: truncated % escape in the path"
7816 );
7817 }
7818
7819 /// A clip's visualizer field is a whole byte of flags, and a line naming one
7820 /// past it used to be truncated into a look nobody chose (`300` loaded as
7821 /// `44`, with the fast bit and the ink nibble both wrong). It is refused by
7822 /// name now, like the resolution's bound, the sample rate's range, the tone
7823 /// map and the encoder seat beside it.
7824 #[test]
7825 fn a_visualizer_byte_past_a_byte_is_refused_and_the_legal_ones_still_load() {
7826 // The door the parser reads that field through: the low bits are the
7827 // style, bit 3 the fast flag and the high nibble the ink, so every value a
7828 // byte holds is a look and 256 and up is not one.
7829 assert_eq!(flags_byte(b"0", 1).expect("zero is the plain look"), 0);
7830 assert_eq!(flags_byte(b"255", 1).expect("the whole byte is flags"), 255);
7831 let refused = flags_byte(b"300", 9).expect_err("300 is not a byte of flags");
7832 assert_eq!(
7833 refused.to_string(),
7834 "line 9: 300 is not a set of visualizer flags"
7835 );
7836 }
7837
7838 /// ...and the same field through the parser, on a document of the newest
7839 /// dialect: the legal byte is what lands in the clip, the illegal one is the
7840 /// refusal above rather than a truncation.
7841 #[test]
7842 fn a_clip_line_whose_visualizer_is_past_a_byte_loses_the_whole_load() {
7843 let dir = PathBuf::from("/proj");
7844 let line = |flags: &str| {
7845 format!(
7846 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7847 video 1 0 0 30 0 - - - fit 1000 0 0 0 - {flags} 0\n"
7848 )
7849 };
7850 let doc = parse(line("12").as_bytes(), &dir).expect("12 is a look");
7851 // The keyword is the saver's own for this dialect, so a mismatch here would
7852 // be this test's line and not the field it is about.
7853 assert_eq!(doc.lanes[0].1[0].visualizer, 12);
7854 let refused = parse(line("300").as_bytes(), &dir).expect_err("300 is not a look");
7855 assert!(
7856 refused
7857 .to_string()
7858 .contains("is not a set of visualizer flags"),
7859 "{refused}"
7860 );
7861 }
7862}
7863
7864#[cfg(test)]
7865mod title_tests {
7866 use super::*;
7867
7868 fn sample() -> Vec<Title> {
7869 vec![
7870 Title {
7871 start: 0,
7872 frames: 90,
7873 text: "Episode 17\n100% \\ done".into(),
7874 style: TextStyle {
7875 size: 80,
7876 outline: Outline::Thick,
7877 boxed: false,
7878 place: Place::Centre,
7879 ..TextStyle::default()
7880 },
7881 fade_in: 10,
7882 fade_out: 5,
7883 in_anim: TitleAnim::None,
7884 out_anim: TitleAnim::None,
7885 anim_frames: 0,
7886 keys: Vec::new(),
7887 },
7888 Title {
7889 start: 60,
7890 frames: 120,
7891 text: "Jane Doe \u{2014} Engineer".into(),
7892 style: TextStyle::default(),
7893 fade_in: 0,
7894 fade_out: 0,
7895 in_anim: Default::default(),
7896 out_anim: Default::default(),
7897 anim_frames: 0,
7898 keys: Vec::new(),
7899 },
7900 ]
7901 }
7902
7903 fn styled() -> Vec<Title> {
7904 let mut t = sample();
7905 t[1].style = TextStyle {
7906 hplace: HPlace::Left,
7907 align: Align::Right,
7908 weight: Weight::Bold,
7909 ink: [255, 204, 0],
7910 box_color: [10, 20, 30, 200],
7911 ..TextStyle::default()
7912 };
7913 t
7914 }
7915
7916 #[test]
7917 fn a_title_look_round_trips_and_only_a_styled_one_writes_a_line() {
7918 // Default looks write no `titlestyle` line at all.
7919 assert!(!String::from_utf8(title_lines(&sample())).unwrap().contains("titlestyle"));
7920 let titles = styled();
7921 let body = title_lines(&titles);
7922 let text = String::from_utf8(body.clone()).unwrap();
7923 assert_eq!(text.matches("titlestyle").count(), 1);
7924 assert!(text.contains("titlestyle 1 left right bold ffcc00 0a141ec8\n"), "{text}");
7925 let mut bytes = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7926 bytes.extend_from_slice(&body);
7927 let doc = parse(&bytes, Path::new(".")).expect("a v49 file with a title look parses");
7928 assert_eq!(doc.titles, titles);
7929 let mut again = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7930 again.extend_from_slice(&title_lines(&doc.titles));
7931 assert_eq!(again, bytes);
7932 }
7933
7934 #[test]
7935 fn a_title_look_is_a_v49_line_and_a_bad_one_is_refused_by_name() {
7936 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");
7937 let ok = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(49));
7938 assert!(parse(ok.as_bytes(), Path::new(".")).is_ok());
7939 let old = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(48));
7940 assert!(parse(old.as_bytes(), Path::new(".")).is_err(), "titlestyle is not a v48 line");
7941 // A v48 file with plain titles still loads, with the default look.
7942 let doc = parse(head(48).as_bytes(), Path::new(".")).unwrap();
7943 assert_eq!(doc.titles[0].style, TextStyle { boxed: true, ..TextStyle::default() });
7944 for line in [
7945 "titlestyle 0 middle left bold ffffff 000000ff",
7946 "titlestyle 0 left up bold ffffff 000000ff",
7947 "titlestyle 0 left left heavy ffffff 000000ff",
7948 "titlestyle 0 left left bold fff 000000ff",
7949 "titlestyle 0 left left bold ffffff 000000",
7950 "titlestyle 5 left left bold ffffff 000000ff",
7951 ] {
7952 let text = format!("{}{line}\n", head(49));
7953 assert!(parse(text.as_bytes(), Path::new(".")).is_err(), "{line}");
7954 }
7955 }
7956
7957 #[test]
7958 fn title_lines_round_trip_through_the_loader_with_escapes() {
7959 let titles = sample();
7960 let mut bytes = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7961 bytes.extend_from_slice(&title_lines(&titles));
7962 let doc = parse(&bytes, Path::new(".")).expect("a v26 file with titles parses");
7963 assert_eq!(doc.titles, titles);
7964 // Written and read again, the same bytes come back.
7965 let mut again = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7966 again.extend_from_slice(&title_lines(&doc.titles));
7967 assert_eq!(again, bytes);
7968 }
7969
7970 #[test]
7971 fn a_v25_file_has_no_titles_and_loads() {
7972 let v25 = b"edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7973 let doc = parse(v25, Path::new(".")).expect("v25 still loads");
7974 assert!(doc.titles.is_empty());
7975 let as_v25 = b"edith 25\nplayhead 0\nsource 0 a.mp4\ntitle 0 10 0 0 50 none 0 bottom hi\n";
7976 assert!(
7977 parse(as_v25, Path::new(".")).is_err(),
7978 "title is not a v25 line"
7979 );
7980 }
7981
7982 #[test]
7983 fn a_title_line_outside_its_range_is_refused_by_name() {
7984 let head = "edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7985 for line in [
7986 "title 0 0 0 0 50 none 0 bottom hi",
7987 "title 0 10 0 0 9 none 0 bottom hi",
7988 "title 0 10 0 0 50 wavy 0 bottom hi",
7989 "title 0 10 0 0 50 none 2 bottom hi",
7990 "title 0 10 0 0 50 none 0 middle hi",
7991 "title 0 10 11 0 50 none 0 bottom hi",
7992 "title 0 10 0 0 50 none 0 bottom",
7993 ] {
7994 let body = format!("{head}{line}\n");
7995 assert!(
7996 parse(body.as_bytes(), Path::new(".")).is_err(),
7997 "{line} was accepted"
7998 );
7999 }
8000 }
8001}
8002
8003#[cfg(test)]
8004mod clip_gain_tests {
8005 use super::*;
8006
8007 /// A v26 file loads, every clip at unity; a `clipgain` line in one is a
8008 /// line the dialect does not have, so it is refused by number.
8009 #[test]
8010 fn a_v26_file_loads_at_unity_and_refuses_a_clipgain_line() {
8011 let dir = PathBuf::from("/proj");
8012 let old = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8013 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8014 let doc = parse(old, &dir).expect("a v26 file still loads");
8015 assert_eq!(doc.lanes[0].1[0].gain_db, 0.0);
8016 let with = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8017 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\nclipgain audio 1 0 -6\n";
8018 let err = parse(with, &dir).unwrap_err().to_string();
8019 assert!(err.contains("line 6"), "{err}");
8020 }
8021
8022 /// The writer's own bytes: a gained clip gets a `clipgain` line after its
8023 /// lanes, unity clips get none, and the value comes back exactly.
8024 #[test]
8025 fn clip_gain_lines_are_written_only_off_unity_and_round_trip() {
8026 let dir = PathBuf::from("/proj");
8027 let clip = |gain_db: f32| Clip {
8028 speed_keys: Vec::new(),
8029 reversed: false,
8030 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
8031 angle: Default::default(),
8032 gain_keys: Vec::new(),
8033 pan: 0,
8034 transform_keys: Vec::new(),
8035 opacity_keys: Vec::new(),
8036 color_keys: Vec::new(),
8037 effects: Vec::new(),
8038 start: 0,
8039 in_frame: 0,
8040 out_frame: 30,
8041 source: 0,
8042 link: None,
8043 eq: None,
8044 color: None,
8045 transform: None,
8046 fit: FitPolicy::default(),
8047 speed: Speed::NORMAL,
8048 fade_in: 0,
8049 fade_out: 0,
8050 transition_out: 0,
8051 transition_kind: Default::default(),
8052 visualizer: 0,
8053 viz_paint: 0,
8054 gain_db,
8055 pitch: 0,
8056 };
8057 let lanes = vec![
8058 (LaneKind::Video, vec![clip(0.0)]),
8059 (LaneKind::Audio, vec![clip(-6.5), clip(0.0)]),
8060 ];
8061 let bytes = clip_gain_lines(&lanes);
8062 assert_eq!(bytes, b"clipgain audio 1 0 -6.5\n".to_vec());
8063 let mut text = b"edith 27\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8064 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8065 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8066 audio 1 30 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"
8067 .to_vec();
8068 text.extend_from_slice(&bytes);
8069 let doc = parse(&text, &dir).expect("a v27 file with a clip gain parses");
8070 assert_eq!(doc.lanes[1].1[0].gain_db, -6.5);
8071 assert_eq!(doc.lanes[1].1[1].gain_db, 0.0);
8072 }
8073}
8074
8075#[cfg(test)]
8076mod gain_key_tests {
8077 use super::*;
8078
8079 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8080 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8081
8082 /// A v27 file loads with every clip's envelope empty, and a `gainkeys` line
8083 /// in one is a line the dialect does not have, so it is refused by number.
8084 #[test]
8085 fn a_v27_file_loads_flat_and_refuses_a_gainkeys_line() {
8086 let dir = PathBuf::from("/proj");
8087 let old = format!("edith 27\n{HEAD}");
8088 let doc = parse(old.as_bytes(), &dir).expect("a v27 file still loads");
8089 assert!(doc.lanes[0].1[0].gain_keys.is_empty());
8090 let with = format!("edith 27\n{HEAD}gainkeys audio 1 0 0:-6\n");
8091 let err = parse(with.as_bytes(), &dir).unwrap_err().to_string();
8092 assert!(err.contains("line 6"), "{err}");
8093 }
8094
8095 /// The writer's own bytes: a clip with points gets one `gainkeys` line after
8096 /// its lanes, a clip without gets none, and the points come back exactly.
8097 #[test]
8098 fn gain_key_lines_are_written_only_with_points_and_round_trip() {
8099 let dir = PathBuf::from("/proj");
8100 let mut text = format!("edith 28\n{HEAD}").into_bytes();
8101 text.extend_from_slice(b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n");
8102 let doc = parse(&text, &dir).expect("a v28 file with an envelope parses");
8103 let keys = &doc.lanes[0].1[0].gain_keys;
8104 assert_eq!(
8105 keys,
8106 &[
8107 GainKey::new(0, 0.0),
8108 GainKey::new(30, -20.0),
8109 GainKey::new(45, -6.5),
8110 ]
8111 );
8112 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8113 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8114 let bytes = gain_key_lines(&lanes);
8115 assert_eq!(bytes, b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n".to_vec());
8116 let again = parse(
8117 &[format!("edith 28\n{HEAD}").as_bytes(), &bytes].concat(),
8118 &dir,
8119 )
8120 .expect("the writer's own line parses");
8121 assert_eq!(again.lanes[0].1[0].gain_keys, *keys);
8122 }
8123
8124 /// A ramp can make a clip shorter than its constant footprint, which the lines before
8125 /// its `speedkeys` still show: the next clip, placed against the ramp's length, loads;
8126 /// one that really overlaps the ramped footprint is refused.
8127 #[test]
8128 fn a_clip_placed_against_a_shorter_ramp_loads_and_a_real_overlap_does_not() {
8129 let dir = PathBuf::from("/proj");
8130 let next = |start: u32| {
8131 format!("audio 1 {start} 0 30 0 - - - fit 1000 0 0 0 - 0 0\n")
8132 };
8133 let ok = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(22));
8134 let doc = parse(ok.as_bytes(), &dir).expect("the ramp is 22 frames, the next clip starts at 22");
8135 assert_eq!(doc.lanes[0].1.len(), 2);
8136 let bad = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(21));
8137 assert!(parse(bad.as_bytes(), &dir).is_err(), "21 is inside the ramped clip");
8138 }
8139
8140 /// A `speedkeys` line is a v35 clip's ramp: it reads back as the keys, its footprint
8141 /// is the ramp's, and the writer's own line reads back to the same keys. A clip with no
8142 /// keys writes no line.
8143 #[test]
8144 fn speedkeys_lines_round_trip_and_a_clip_without_a_ramp_writes_none() {
8145 let dir = PathBuf::from("/proj");
8146 let text = format!("edith 35\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8147 let doc = parse(text.as_bytes(), &dir).expect("a v35 file with a ramp parses");
8148 let clip = &doc.lanes[0].1[0];
8149 assert_eq!(
8150 clip.speed_keys,
8151 vec![
8152 SpeedKey { at: 0, speed: Speed::NORMAL },
8153 SpeedKey { at: 30, speed: Speed::from_permille(2000) },
8154 ]
8155 );
8156 // 30 source frames at a rate that climbs from 1x to 2x: 22 timeline frames.
8157 assert_eq!(clip.frames(), 22);
8158 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8159 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8160 assert_eq!(speed_key_lines(&lanes), b"speedkeys audio 1 0 0:1000 30:2000\n".to_vec());
8161 let mut plain = lanes.clone();
8162 plain[0].1[0].speed_keys.clear();
8163 assert!(speed_key_lines(&plain).is_empty(), "no ramp, no line");
8164 let again = parse(
8165 &[format!("edith 35\n{HEAD}").as_bytes(), &speed_key_lines(&lanes)].concat(),
8166 &dir,
8167 )
8168 .expect("the writer's own line parses");
8169 assert_eq!(again.lanes[0].1[0].speed_keys, clip.speed_keys);
8170 }
8171
8172 /// A `transition` line (v37) names how a clip's dissolve is drawn: every kind's name
8173 /// reads back as the kind, the writer's own lines parse, a clip with the default writes
8174 /// none, and an older file (no line) means a dissolve.
8175 #[test]
8176 fn transition_lines_round_trip_every_kind_and_old_files_dissolve() {
8177 let dir = PathBuf::from("/proj");
8178 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8179 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8180 let old = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("v35 parses");
8181 assert_eq!(old.lanes[0].1[0].transition_kind, TransitionKind::Dissolve);
8182 let mut kinds = Vec::new();
8183 for shape in TransitionKind::SHAPES {
8184 match shape.dir() {
8185 Some(_) => kinds.extend(crate::transitions::Dir::ALL.map(|d| shape.with_dir(d))),
8186 None => kinds.push(shape),
8187 }
8188 }
8189 for kind in kinds {
8190 let mut lanes: Vec<(LaneKind, Vec<Clip>)> = old.lanes.clone();
8191 lanes[0].1[0].transition_kind = kind;
8192 let lines = transition_lines(&lanes);
8193 if kind == TransitionKind::Dissolve {
8194 assert!(lines.is_empty(), "the default writes no line");
8195 }
8196 let text = [format!("edith 37\n{head}").as_bytes(), &lines].concat();
8197 let back = parse(&text, &dir).unwrap_or_else(|e| panic!("{}: {e}", kind.name()));
8198 assert_eq!(back.lanes[0].1[0].transition_kind, kind);
8199 }
8200 for bad in ["transition video 1 0 swirl\n", "transition video 1 4 zoom\n", "transition video 2 0 zoom\n"] {
8201 let err = parse(format!("edith 37\n{head}{bad}").as_bytes(), &dir).unwrap_err().to_string();
8202 assert!(err.contains("line 6"), "{bad}: {err}");
8203 }
8204 for old in [35, 36] {
8205 let file = format!("edith {old}\n{head}transition video 1 0 zoom\n");
8206 assert!(parse(file.as_bytes(), &dir).is_err(), "a v{old} reader has no such line");
8207 }
8208 }
8209
8210 /// The writer emits the highest version a project needs: markers alone are v36, a
8211 /// transition kind makes it v37 (markers and all, which round-trip together), only
8212 /// dissolves and no markers fall back to the older header, and a v36 file still loads.
8213 #[test]
8214 fn the_header_is_the_highest_version_needed_and_v36_and_v37_round_trip() {
8215 use crate::project::{Marker, MarkerColor};
8216 let dir = std::env::temp_dir().join(format!("edith-v37-{}", std::process::id()));
8217 std::fs::create_dir_all(&dir).unwrap();
8218 let path = dir.join("v37.edith");
8219 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";
8220 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8221 let sources = doc.sources;
8222 let mut lanes = doc.lanes;
8223 let markers = vec![Marker { frame: 12, length: 0, name: "Beat".into(), note: "a note".into(), color: MarkerColor::Blue }];
8224 let save_styled = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker], cs: &CaptionStyle| {
8225 save_flagged(
8226 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8227 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8228 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, cs, &[], &[],
8229 )
8230 .expect("saves");
8231 std::fs::read_to_string(&path).unwrap()
8232 };
8233 let save = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker]| {
8234 save_styled(lanes, markers, &CaptionStyle::default())
8235 };
8236 assert!(save(&lanes, &markers).starts_with("edith 36\n"), "markers alone are v36");
8237 lanes[0].1[0].transition_kind = TransitionKind::Zoom;
8238 let text = save(&lanes, &markers);
8239 assert!(text.starts_with("edith 37\n"), "a transition makes it v37: {text}");
8240 let back = load(&path).expect("v37 loads");
8241 assert_eq!(back.markers, markers);
8242 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8243 let text = save(&lanes, &[]);
8244 assert!(text.starts_with("edith 37\n") && text.contains("transition "), "{text}");
8245 lanes[0].1[0].reversed = true;
8246 let text = save(&lanes, &markers);
8247 assert!(text.starts_with("edith 38\n") && text.contains("reverse video 1 0"), "a reversed clip makes it v38: {text}");
8248 let back = load(&path).expect("v38 loads");
8249 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8250 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8251 lanes[0].1[0].opacity_keys = vec![OpacityKey { at: 0, opacity: 0.5, ease: KeyEase::Hold }];
8252 let text = save(&lanes, &markers);
8253 assert!(text.starts_with("edith 39\n") && text.contains("okeys video 1 0"), "an animation makes it v39: {text}");
8254 let back = load(&path).expect("v39 loads");
8255 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8256 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8257 // ...and a project caption style on top of all of it makes it v40.
8258 let style = CaptionStyle { anim: crate::captionanim::CaptionAnim::Pop, ..CaptionStyle::default() };
8259 let text = save_styled(&lanes, &markers, &style);
8260 assert!(text.starts_with("edith 40\n") && text.contains("\ncapstyle pop "), "a caption style makes it v40: {text}");
8261 let back = load(&path).expect("v40 loads");
8262 assert!(back.lanes[0].1[0].reversed && back.markers == markers && back.caption_style == style);
8263 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8264 lanes[0].1[0].opacity_keys.clear();
8265 lanes[0].1[0].reversed = false;
8266 lanes[0].1[0].transition_kind = TransitionKind::Dissolve;
8267 let text = save(&lanes, &[]);
8268 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}");
8269 let v36 = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).expect("a v36 file loads");
8270 assert_eq!(v36.markers.len(), 1);
8271 std::fs::remove_dir_all(&dir).ok();
8272 }
8273
8274 /// `lanename` and `deint` lines are v46: both round-trip, a project with neither keeps
8275 /// its older header and exact bytes, an older header refuses them and bad ones are
8276 /// refused by line.
8277 #[test]
8278 fn lane_names_and_deinterlace_round_trip_in_v46_and_without_them_the_bytes_are_unchanged() {
8279 let dir = std::env::temp_dir().join(format!("edith-v46-{}", std::process::id()));
8280 std::fs::create_dir_all(&dir).unwrap();
8281 let path = dir.join("v46.edith");
8282 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";
8283 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8284 let sources = doc.sources;
8285 let mut lanes = doc.lanes;
8286 let n = lanes.len();
8287 let save = |lanes: &[(LaneKind, Vec<Clip>)], names: &[String]| {
8288 save_flagged(
8289 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8290 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8291 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], names,
8292 )
8293 .expect("saves");
8294 std::fs::read_to_string(&path).unwrap()
8295 };
8296 let blank = vec![String::new(); n];
8297 let plain = save(&lanes, &blank);
8298 assert!(!plain.contains("lanename") && !plain.contains("deint") && !plain.starts_with("edith 46"), "{plain}");
8299 let mut names = blank.clone();
8300 names[0] = "Main \\ cam".into();
8301 let text = save(&lanes, &names);
8302 assert!(text.starts_with("edith 46\n") && text.contains("\nlanename video 1 Main \\\\ cam\n"), "{text}");
8303 assert_eq!(load(&path).expect("v46 loads").names[0], "Main \\ cam");
8304 assert_eq!(save(&lanes, &blank), plain, "no names is the bytes it was");
8305 lanes[0].1[0].deinterlace = Deinterlace::Field;
8306 let text = save(&lanes, &blank);
8307 assert!(text.starts_with("edith 46\n") && text.contains("\ndeint video 1 0 field\n"), "{text}");
8308 assert_eq!(load(&path).unwrap().lanes[0].1[0].deinterlace, Deinterlace::Field);
8309 for older in ["edith 45", "edith 44"] {
8310 for line in ["lanename video 1 X\n", "deint video 1 0 off\n"] {
8311 let old = format!("{older}\n{head}{line}");
8312 assert!(parse(old.as_bytes(), &dir).is_err(), "{older} refuses {line:?}");
8313 }
8314 }
8315 for (line, why) in [
8316 ("lanename video 1 \n", "1 to"),
8317 ("lanename video 3 X\n", "not there"),
8318 ("lanename tape 1 X\n", "not a lane kind"),
8319 ("deint video 1 0 weave\n", "frame, field or off"),
8320 ("deint video 1 4 off\n", "does not have"),
8321 ] {
8322 let err = parse(format!("edith 46\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8323 assert!(err.contains(why) && err.contains("line"), "{line:?}: {err}");
8324 }
8325 let long = "x".repeat(crate::project::MAX_LANE_NAME_CHARS + 1);
8326 assert!(parse(format!("edith 46\n{head}lanename video 1 {long}\n").as_bytes(), &dir).is_err());
8327 std::fs::remove_file(&path).ok();
8328 std::fs::remove_dir(&dir).ok();
8329 }
8330
8331 /// A `stab` line is a v44 clip's stabilisation: it round-trips through a save, a
8332 /// project with no stabilised clip keeps its older header and its exact bytes, an
8333 /// older file refuses the line and a bad one is refused by its line number.
8334 #[test]
8335 fn stab_lines_round_trip_in_v44_and_without_one_the_bytes_are_unchanged() {
8336 let dir = std::env::temp_dir().join(format!("edith-stab-{}", std::process::id()));
8337 std::fs::create_dir_all(&dir).unwrap();
8338 let path = dir.join("v44.edith");
8339 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";
8340 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8341 let sources = doc.sources;
8342 let mut lanes = doc.lanes;
8343 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
8344 save_flagged(
8345 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8346 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8347 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
8348 )
8349 .expect("saves");
8350 std::fs::read_to_string(&path).unwrap()
8351 };
8352 let plain = save(&lanes);
8353 assert!(!plain.contains("stab") && !plain.starts_with("edith 44"), "{plain}");
8354 let st = crate::stabilise::Stabilise::new(0.75, crate::stabilise::Crop::Full);
8355 lanes[0].1[0].stabilise = Some(st);
8356 let text = save(&lanes);
8357 assert!(text.starts_with("edith 44\n") && text.contains("\nstab video 1 0 0.75 full\n"), "{text}");
8358 assert_eq!(load(&path).expect("v44 loads").lanes[0].1[0].stabilise, Some(st));
8359 lanes[0].1[0].stabilise = None;
8360 assert_eq!(save(&lanes), plain, "off again is the bytes it was");
8361 for older in ["edith 43", "edith 42", "edith 41"] {
8362 let old = format!("{older}\n{head}stab video 1 0 0.5 zoom\n");
8363 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("stab"), "{older} has no stab line");
8364 }
8365 for (line, why) in [
8366 ("stab video 1 0 0.5\n", "wants a video clip"),
8367 ("stab video 1 0 1.5 zoom\n", "from 0 to 1"),
8368 ("stab video 1 0 0.5 tilt\n", "zoom or full"),
8369 ("stab video 1 4 0.5 zoom\n", "which the lane does not have"),
8370 ] {
8371 let err = parse(format!("edith 44\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8372 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8373 }
8374 std::fs::remove_dir_all(&dir).ok();
8375 }
8376
8377 /// A `reverse` line is a v38 clip's direction: it reads back as `reversed`, the
8378 /// writer's own line reads back the same, a project with none is written under
8379 /// the v35 header it always was, and an older file or a bad line is refused by
8380 /// its line number.
8381 #[test]
8382 fn reverse_lines_round_trip_and_older_files_and_bad_lines_are_refused() {
8383 let dir = PathBuf::from("/proj");
8384 let text = format!("edith 38\n{HEAD}reverse audio 1 0\n");
8385 let doc = parse(text.as_bytes(), &dir).expect("a v38 file with a reversed clip parses");
8386 assert!(doc.lanes[0].1[0].reversed);
8387 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8388 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8389 assert_eq!(reverse_lines(&lanes), b"reverse audio 1 0\n".to_vec());
8390 let mut plain = lanes.clone();
8391 plain[0].1[0].reversed = false;
8392 assert!(reverse_lines(&plain).is_empty(), "forward, no line");
8393 let again = parse(
8394 &[format!("edith 38\n{HEAD}").as_bytes(), &reverse_lines(&lanes)].concat(),
8395 &dir,
8396 )
8397 .expect("the writer's own line parses");
8398 assert!(again.lanes[0].1[0].reversed);
8399 // A v37 file (or older) has no such line.
8400 for old in [35, 37] {
8401 let file = format!("edith {old}\n{HEAD}reverse audio 1 0\n");
8402 let err = parse(file.as_bytes(), &dir).unwrap_err().to_string();
8403 assert!(err.contains("reverse"), "v{old}: {err}");
8404 }
8405 let head = format!("edith 38\n{HEAD}");
8406 for (line, why) in [
8407 ("reverse audio 1\n", "wants a lane and a clip"),
8408 ("reverse subtitle 1 0\n", "not a lane kind"),
8409 ("reverse audio 9 0\n", "a lane that is not there"),
8410 ("reverse audio 1 5\n", "which the lane does not have"),
8411 ] {
8412 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8413 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8414 }
8415 }
8416
8417 /// A v34 file has no `speedkeys` line, and a bad ramp is refused by its line: a speed
8418 /// out of range, keys out of frame order, a key without a speed, or more than the cap.
8419 #[test]
8420 fn a_v34_file_refuses_a_speedkeys_line_and_a_bad_ramp_is_refused() {
8421 let dir = PathBuf::from("/proj");
8422 let v34 = format!("edith 34\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8423 let err = parse(v34.as_bytes(), &dir).unwrap_err().to_string();
8424 assert!(err.contains("speedkeys"), "{err}");
8425 let head = format!("edith 35\n{HEAD}");
8426 for line in [
8427 "speedkeys audio 1 0 0:9000\n",
8428 "speedkeys audio 1 0 30:1000 0:1000\n",
8429 "speedkeys audio 1 0 0\n",
8430 "speedkeys audio 1 0 0:1000 1:1000 2:1000 3:1000 4:1000 5:1000 6:1000 7:1000 8:1000\n",
8431 ] {
8432 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8433 assert!(err.contains("line 6"), "{line}: {err}");
8434 }
8435 }
8436
8437 /// A point out of source order, one out of range, or a clip with more than
8438 /// the cap are all refused by line; the dialect keeps the invariants.
8439 #[test]
8440 fn a_bad_gainkeys_line_is_refused() {
8441 let dir = PathBuf::from("/proj");
8442 let head = format!("edith 28\n{HEAD}");
8443 for line in [
8444 "gainkeys audio 1 0 30:-6 0:0\n",
8445 "gainkeys audio 1 0 0:-90\n",
8446 "gainkeys audio 1 0 0\n",
8447 "gainkeys audio 1 0 0 0x\n",
8448 ] {
8449 let text = format!("{head}{line}");
8450 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8451 assert!(err.contains("line 6"), "{line}: {err}");
8452 }
8453 let many: String = (0..=MAX_GAIN_KEYS as u32)
8454 .map(|i| format!(" {i}:0"))
8455 .collect();
8456 let text = format!("{head}gainkeys audio 1 0 0{many}\n");
8457 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8458 assert!(err.contains("more than"), "{err}");
8459 }
8460}
8461
8462#[cfg(test)]
8463mod animation_key_tests {
8464 use super::*;
8465
8466 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8467 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8468 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8469
8470 /// A v35 file written before the easings existed still loads, every key linear
8471 /// (or the `ease` it said), and resaving it does not change a key.
8472 #[test]
8473 fn a_v35_file_upgrades_with_its_keys_linear_and_resaves_as_v32_bytes() {
8474 let dir = PathBuf::from("/proj");
8475 let text = format!(
8476 "edith 35\n{HEAD}gainkeys audio 1 0 0:0 20:-6.5\n\
8477 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"
8478 );
8479 let doc = parse(text.as_bytes(), &dir).expect("a v35 file loads");
8480 let clips = &doc.lanes[1].1;
8481 assert_eq!(clips[0].gain_keys, [GainKey::new(0, 0.0), GainKey::new(20, -6.5)]);
8482 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Ease);
8483 assert!(doc.lanes[0].1[0].opacity_keys.is_empty() && doc.lanes[0].1[0].color_keys.is_empty());
8484 // The writers' lines for those clips are the bytes the file had.
8485 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0 20:-6.5\n".to_vec());
8486 assert_eq!(
8487 tkey_lines(&doc.lanes),
8488 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()
8489 );
8490 assert!(doc.lanes.iter().all(|(_, clips)| !clips.iter().any(needs_v39)), "still not a v39 project");
8491 assert!(opacity_key_lines(&doc.lanes).is_empty() && color_key_lines(&doc.lanes).is_empty());
8492 }
8493
8494 /// The v39 lines read back, in range and in order, and an older dialect has
8495 /// no such lines (nor the new easings) and says so by line number.
8496 #[test]
8497 fn v39_reads_okeys_ckeys_and_eased_points_and_older_dialects_refuse_them() {
8498 let dir = PathBuf::from("/proj");
8499 let new = format!(
8500 "edith 39\n{HEAD}okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n\
8501 ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n\
8502 gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n\
8503 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"
8504 );
8505 let doc = parse(new.as_bytes(), &dir).expect("a v39 file loads");
8506 let v = &doc.lanes[0].1[0];
8507 assert_eq!(v.opacity_keys.len(), 3);
8508 assert_eq!(v.opacity_keys[0].ease, KeyEase::EaseIn);
8509 assert_eq!(v.opacity_keys[1], OpacityKey { at: 10, opacity: 0.5, ease: KeyEase::Hold });
8510 assert_eq!(v.color_keys[0].ease, KeyEase::EaseOut);
8511 assert_eq!(v.color_keys[1].params.contrast, 2.0);
8512 assert_eq!(v.transform_keys[1].ease, KeyEase::Hold);
8513 let g = &doc.lanes[1].1[0].gain_keys;
8514 assert_eq!((g[0].ease, g[1].ease, g[2].ease), (KeyEase::EaseOut, KeyEase::Hold, KeyEase::Linear));
8515 // ...and writing them gives the same lines back.
8516 assert_eq!(
8517 opacity_key_lines(&doc.lanes),
8518 b"okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n".to_vec()
8519 );
8520 assert_eq!(
8521 color_key_lines(&doc.lanes),
8522 b"ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n".to_vec()
8523 );
8524 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n".to_vec());
8525
8526 // A v35 reader has none of it.
8527 let old = format!("edith 35\n{HEAD}okeys video 1 0 0:lin:0\n");
8528 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("line 7"));
8529 // ...and so has a v38 one.
8530 let old = format!("edith 38\n{HEAD}okeys video 1 0 0:lin:0\n");
8531 assert!(parse(old.as_bytes(), &dir).is_err(), "a v38 reader has no okeys line");
8532 let old = format!("edith 35\n{HEAD}tkeys video 1 0 0:hold:0,0,1,0,0,0,0,0,1\n");
8533 assert!(parse(old.as_bytes(), &dir).is_err(), "a hold ease is not a v35 word");
8534 }
8535
8536 #[test]
8537 fn bad_okeys_and_ckeys_lines_are_refused() {
8538 let dir = PathBuf::from("/proj");
8539 for bad in [
8540 "okeys video 1 0 0:lin:1.5", // opacity out of range
8541 "okeys video 1 0 5:lin:0 5:lin:1", // two at one frame
8542 "okeys video 1 0 9:lin:0 5:lin:1", // not in source order
8543 "okeys video 1 0 0:wobble:1", // unknown ease
8544 "okeys audio 1 0 0:lin:1", // not a video lane
8545 "okeys video 1 3 0:lin:1", // no such clip
8546 "ckeys video 1 0 0:lin:2,1,1,0", // brightness out of range
8547 "ckeys video 1 0 0:lin:0,1,1", // three values
8548 "ckeys video 1 0 0:lin:0,3,1,0", // contrast out of range
8549 ] {
8550 let text = format!("edith 39\n{HEAD}{bad}\n");
8551 assert!(parse(text.as_bytes(), &dir).is_err(), "{bad}");
8552 }
8553 }
8554}